package com.xfestudio.xfeservermanager.core.rollback;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.xfestudio.xfeservermanager.api.world.WorldChangeKind;
import com.xfestudio.xfeservermanager.api.world.WorldChangeRecord;
import com.xfestudio.xfeservermanager.api.world.WorldStatePayload;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.junit.jupiter.api.Test;
class RollbackPlannerTest {
@Test
void previewIsReverseOrderedFixedWatermarkAndReportsEverySafetyIssue() {
TestWorld world = new TestWorld();
JournalEntry ready = entry(1, 0, state("stone"), state("dirt"), true);
JournalEntry conflict = entry(2, 16, state("stone"), state("dirt"), true);
JournalEntry unloaded = entry(3, 32, state("stone"), state("dirt"), true);
JournalEntry incompatible = entry(4, 48, state("missing"), state("dirt"), true);
JournalEntry unrestorable = entry(5, 64, state("stone"), state("dirt"), false);
world.loaded.add(chunk(ready));
world.loaded.add(chunk(conflict));
world.loaded.add(chunk(incompatible));
world.loaded.add(chunk(unrestorable));
world.states.put(ready.change().eventId(), ready.change().afterState());
world.states.put(conflict.change().eventId(), state("diamond"));
world.states.put(incompatible.change().eventId(), incompatible.change().afterState());
world.states.put(unrestorable.change().eventId(), unrestorable.change().afterState());
world.incompatibleResources.add("missing");
var gap = new JournalGap(Instant.EPOCH, Instant.EPOCH.plusSeconds(1), "overload", 25);
var planner = planner(new JournalSlice(99, List.of(ready, conflict, unloaded, incompatible, unrestorable), List.of(gap)), world);
RollbackPlan plan = planner.preview(query(), false, false, false);
assertEquals(99, plan.watermark());
assertEquals(List.of(5L, 4L, 3L, 2L, 1L), plan.items().stream().map(item -> item.entry().sequence()).toList());
assertEquals(List.of(PlanDisposition.NOT_RESTORABLE, PlanDisposition.INCOMPATIBLE,
PlanDisposition.UNLOADED, PlanDisposition.CONFLICT, PlanDisposition.READY),
plan.items().stream().map(RollbackPlanItem::disposition).toList());
assertFalse(plan.completeRecoveryPossible());
assertEquals(25, plan.gaps().get(0).droppedEvents());
}
@Test
void forceAndTemporaryLoadingRequireOwnerAndPreviewStillShowsConflicts() {
TestWorld world = new TestWorld();
JournalEntry entry = entry(1, 0, state("before"), state("after"), true);
world.loaded.add(chunk(entry));
world.states.put(entry.change().eventId(), state("unexpected"));
var planner = planner(new JournalSlice(1, List.of(entry), List.of()), world);
assertThrows(SecurityException.class, () -> planner.preview(query(), true, false, false));
RollbackPlan forced = planner.preview(query(), true, false, true);
assertEquals(PlanDisposition.CONFLICT, forced.items().get(0).disposition());
assertTrue(forced.items().get(0).executable(true));
}
@Test
void capsTemporaryLoadsAtOneHundredTwentyEightDistinctChunks() {
TestWorld world = new TestWorld();
var entries = new ArrayList<JournalEntry>();
for (int index = 0; index < 129; index++) entries.add(entry(index + 1, index * 16, state("a"), state("b"), true));
RollbackPlan plan = planner(new JournalSlice(129, entries, List.of()), world)
.preview(query(), false, true, true);
assertEquals(128, plan.items().stream().filter(item -> item.disposition() == PlanDisposition.READY_REQUIRES_CHUNK_LOAD).count());
assertEquals(1, plan.items().stream().filter(item -> item.disposition() == PlanDisposition.CHUNK_LOAD_LIMIT).count());
}
@Test
void simulatesStackedChangesAndOrdersRedoForward() {
TestWorld world = new TestWorld();
JournalEntry first = entry(1, 0, state("a"), state("b"), true);
JournalEntry second = entry(2, 0, state("b"), state("c"), true);
world.loaded.add(chunk(first));
world.states.put(second.change().eventId(), state("c"));
var planner = planner(new JournalSlice(2, List.of(first, second), List.of()), world);
RollbackPlan rollback = planner.preview(query(), false, false, false);
assertEquals(List.of(2L, 1L), rollback.items().stream().map(item -> item.entry().sequence()).toList());
assertTrue(rollback.items().stream().allMatch(item -> item.disposition() == PlanDisposition.READY));
var completed = new RollbackOperation(UUID.randomUUID(), rollback, RollbackStatus.COMPLETED, 2,
List.of(second.change().eventId(), first.change().eventId()), List.of(), Instant.now());
world.states.put(first.change().eventId(), state("a"));
RollbackPlan redo = planner.previewRedo(completed, false, false, false);
assertEquals(List.of(1L, 2L), redo.items().stream().map(item -> item.entry().sequence()).toList());
assertTrue(redo.items().stream().allMatch(item -> item.disposition() == PlanDisposition.READY));
}
@Test
void entityAndItemRestorationRequireOwnerAndRedoPreservesOriginalGaps() {
TestWorld world = new TestWorld();
JournalEntry block = entry(1, 0, state("before"), state("after"), true);
WorldChangeRecord base = block.change();
JournalEntry entity = new JournalEntry(2, new WorldChangeRecord(
UUID.randomUUID(), base.timestamp().plusSeconds(1), base.tick() + 1,
base.dimensionId(), base.x(), base.y(), base.z(), WorldChangeKind.ENTITY_DEATH,
"minecraft:zombie", base.actorId(), base.cause(), base.beforeState(), base.afterState(),
"tx-entity", base.modFingerprint(), true));
world.loaded.add(chunk(entity));
world.states.put(entity.change().eventId(), entity.change().afterState());
JournalGap gap = new JournalGap(Instant.EPOCH, Instant.EPOCH.plusSeconds(1), "overload", 3);
var planner = planner(new JournalSlice(2, List.of(entity), List.of(gap)), world);
RollbackPlan unauthorized = planner.preview(query(), false, false, false);
assertEquals(PlanDisposition.OWNER_AUTHORIZATION_REQUIRED, unauthorized.items().get(0).disposition());
RollbackPlan authorized = planner.preview(query(), false, false, true);
assertEquals(PlanDisposition.READY, authorized.items().get(0).disposition());
var completed = new RollbackOperation(UUID.randomUUID(), authorized, RollbackStatus.COMPLETED, 1,
List.of(entity.change().eventId()), List.of(), Instant.now());
world.states.put(entity.change().eventId(), entity.change().beforeState());
RollbackPlan redo = planner.previewRedo(completed, false, false, true);
assertEquals(1, redo.gaps().size());
assertFalse(redo.completeRecoveryPossible());
}
@Test
void rejectsAmbiguousDuplicateJournalEntries() {
JournalEntry entry = entry(1, 0, state("before"), state("after"), true);
assertThrows(IllegalArgumentException.class,
() -> new JournalSlice(1, List.of(entry, entry), List.of()));
}
private static RollbackPlanner planner(JournalSlice slice, TestWorld world) {
return new RollbackPlanner(ignored -> slice, world,
Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneOffset.UTC));
}
static RollbackQuery query() {
return new RollbackQuery(Instant.EPOCH, Instant.parse("2030-01-01T00:00:00Z"),
Set.of(), Set.of(), Set.of(), null, null, null);
}
static JournalEntry entry(long sequence, int x, WorldStatePayload before, WorldStatePayload after, boolean restorable) {
return new JournalEntry(sequence, new WorldChangeRecord(UUID.randomUUID(), Instant.EPOCH.plusSeconds(sequence),
sequence, "minecraft:overworld", x, 64, 0, WorldChangeKind.BLOCK_CHANGE,
"minecraft:stone", "player", "test", before, after, "tx-" + sequence, "vanilla", restorable));
}
static WorldStatePayload state(String name) {
return new WorldStatePayload("xfeservermanager:test", 1, "application/octet-stream",
name.getBytes(java.nio.charset.StandardCharsets.UTF_8), Map.of("name", name));
}
static Chunk chunk(JournalEntry entry) {
return new Chunk(entry.change().dimensionId(), Math.floorDiv(entry.change().x(), 16), Math.floorDiv(entry.change().z(), 16));
}
record Chunk(String dimension, int x, int z) { }
static class TestWorld implements WorldAccessPort {
final Set<Chunk> loaded = new HashSet<>();
final Map<UUID, WorldStatePayload> states = new HashMap<>();
final Set<String> incompatibleResources = new HashSet<>();
final List<UUID> applied = new ArrayList<>();
final Set<Chunk> acquired = new HashSet<>();
@Override public boolean isChunkLoaded(String dimensionId, int chunkX, int chunkZ) {
return loaded.contains(new Chunk(dimensionId, chunkX, chunkZ));
}
@Override public WorldStatePayload currentState(WorldChangeRecord change) {
return states.get(change.eventId());
}
@Override public Compatibility compatibility(WorldChangeRecord change, WorldStatePayload target) {
String name = target == null ? "" : target.metadata().getOrDefault("name", "");
return incompatibleResources.contains(name) ? Compatibility.unsupported("registry item is missing") : Compatibility.supported();
}
@Override public boolean acquireChunk(String dimensionId, int chunkX, int chunkZ) {
var chunk = new Chunk(dimensionId, chunkX, chunkZ);
acquired.add(chunk);
loaded.add(chunk);
return true;
}
@Override public void releaseChunk(String dimensionId, int chunkX, int chunkZ) {
var chunk = new Chunk(dimensionId, chunkX, chunkZ);
acquired.remove(chunk);
loaded.remove(chunk);
}
@Override public void apply(WorldChangeRecord change, WorldStatePayload target) {
states.put(change.eventId(), target);
applied.add(change.eventId());
}
}
}
package com.xfestudio.xfeservermanager.core.rollback;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.xfestudio.xfeservermanager.api.world.WorldChangeKind;
import com.xfestudio.xfeservermanager.api.world.WorldChangeRecord;
import com.xfestudio.xfeservermanager.api.world.WorldStatePayload;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.junit.jupiter.api.Test;
class RollbackPlannerTest {
@Test
void previewIsReverseOrderedFixedWatermarkAndReportsEverySafetyIssue() {
TestWorld world = new TestWorld();
JournalEntry ready = entry(1, 0, state("stone"), state("dirt"), true);
JournalEntry conflict = entry(2, 16, state("stone"), state("dirt"), true);
JournalEntry unloaded = entry(3, 32, state("stone"), state("dirt"), true);
JournalEntry incompatible = entry(4, 48, state("missing"), state("dirt"), true);
JournalEntry unrestorable = entry(5, 64, state("stone"), state("dirt"), false);
world.loaded.add(chunk(ready));
world.loaded.add(chunk(conflict));
world.loaded.add(chunk(incompatible));
world.loaded.add(chunk(unrestorable));
world.states.put(ready.change().eventId(), ready.change().afterState());
world.states.put(conflict.change().eventId(), state("diamond"));
world.states.put(incompatible.change().eventId(), incompatible.change().afterState());
world.states.put(unrestorable.change().eventId(), unrestorable.change().afterState());
world.incompatibleResources.add("missing");
var gap = new JournalGap(Instant.EPOCH, Instant.EPOCH.plusSeconds(1), "overload", 25);
var planner = planner(new JournalSlice(99, List.of(ready, conflict, unloaded, incompatible, unrestorable), List.of(gap)), world);
RollbackPlan plan = planner.preview(query(), false, false, false);
assertEquals(99, plan.watermark());
assertEquals(List.of(5L, 4L, 3L, 2L, 1L), plan.items().stream().map(item -> item.entry().sequence()).toList());
assertEquals(List.of(PlanDisposition.NOT_RESTORABLE, PlanDisposition.INCOMPATIBLE,
PlanDisposition.UNLOADED, PlanDisposition.CONFLICT, PlanDisposition.READY),
plan.items().stream().map(RollbackPlanItem::disposition).toList());
assertFalse(plan.completeRecoveryPossible());
assertEquals(25, plan.gaps().get(0).droppedEvents());
}
@Test
void forceAndTemporaryLoadingRequireOwnerAndPreviewStillShowsConflicts() {
TestWorld world = new TestWorld();
JournalEntry entry = entry(1, 0, state("before"), state("after"), true);
world.loaded.add(chunk(entry));
world.states.put(entry.change().eventId(), state("unexpected"));
var planner = planner(new JournalSlice(1, List.of(entry), List.of()), world);
assertThrows(SecurityException.class, () -> planner.preview(query(), true, false, false));
RollbackPlan forced = planner.preview(query(), true, false, true);
assertEquals(PlanDisposition.CONFLICT, forced.items().get(0).disposition());
assertTrue(forced.items().get(0).executable(true));
}
@Test
void capsTemporaryLoadsAtOneHundredTwentyEightDistinctChunks() {
TestWorld world = new TestWorld();
var entries = new ArrayList<JournalEntry>();
for (int index = 0; index < 129; index++) entries.add(entry(index + 1, index * 16, state("a"), state("b"), true));
RollbackPlan plan = planner(new JournalSlice(129, entries, List.of()), world)
.preview(query(), false, true, true);
assertEquals(128, plan.items().stream().filter(item -> item.disposition() == PlanDisposition.READY_REQUIRES_CHUNK_LOAD).count());
assertEquals(1, plan.items().stream().filter(item -> item.disposition() == PlanDisposition.CHUNK_LOAD_LIMIT).count());
}
@Test
void simulatesStackedChangesAndOrdersRedoForward() {
TestWorld world = new TestWorld();
JournalEntry first = entry(1, 0, state("a"), state("b"), true);
JournalEntry second = entry(2, 0, state("b"), state("c"), true);
world.loaded.add(chunk(first));
world.states.put(second.change().eventId(), state("c"));
var planner = planner(new JournalSlice(2, List.of(first, second), List.of()), world);
RollbackPlan rollback = planner.preview(query(), false, false, false);
assertEquals(List.of(2L, 1L), rollback.items().stream().map(item -> item.entry().sequence()).toList());
assertTrue(rollback.items().stream().allMatch(item -> item.disposition() == PlanDisposition.READY));
var completed = new RollbackOperation(UUID.randomUUID(), rollback, RollbackStatus.COMPLETED, 2,
List.of(second.change().eventId(), first.change().eventId()), List.of(), Instant.now());
world.states.put(first.change().eventId(), state("a"));
RollbackPlan redo = planner.previewRedo(completed, false, false, false);
assertEquals(List.of(1L, 2L), redo.items().stream().map(item -> item.entry().sequence()).toList());
assertTrue(redo.items().stream().allMatch(item -> item.disposition() == PlanDisposition.READY));
}
@Test
void entityAndItemRestorationRequireOwnerAndRedoPreservesOriginalGaps() {
TestWorld world = new TestWorld();
JournalEntry block = entry(1, 0, state("before"), state("after"), true);
WorldChangeRecord base = block.change();
JournalEntry entity = new JournalEntry(2, new WorldChangeRecord(
UUID.randomUUID(), base.timestamp().plusSeconds(1), base.tick() + 1,
base.dimensionId(), base.x(), base.y(), base.z(), WorldChangeKind.ENTITY_DEATH,
"minecraft:zombie", base.actorId(), base.cause(), base.beforeState(), base.afterState(),
"tx-entity", base.modFingerprint(), true));
world.loaded.add(chunk(entity));
world.states.put(entity.change().eventId(), entity.change().afterState());
JournalGap gap = new JournalGap(Instant.EPOCH, Instant.EPOCH.plusSeconds(1), "overload", 3);
var planner = planner(new JournalSlice(2, List.of(entity), List.of(gap)), world);
RollbackPlan unauthorized = planner.preview(query(), false, false, false);
assertEquals(PlanDisposition.OWNER_AUTHORIZATION_REQUIRED, unauthorized.items().get(0).disposition());
RollbackPlan authorized = planner.preview(query(), false, false, true);
assertEquals(PlanDisposition.READY, authorized.items().get(0).disposition());
var completed = new RollbackOperation(UUID.randomUUID(), authorized, RollbackStatus.COMPLETED, 1,
List.of(entity.change().eventId()), List.of(), Instant.now());
world.states.put(entity.change().eventId(), entity.change().beforeState());
RollbackPlan redo = planner.previewRedo(completed, false, false, true);
assertEquals(1, redo.gaps().size());
assertFalse(redo.completeRecoveryPossible());
}
@Test
void rejectsAmbiguousDuplicateJournalEntries() {
JournalEntry entry = entry(1, 0, state("before"), state("after"), true);
assertThrows(IllegalArgumentException.class,
() -> new JournalSlice(1, List.of(entry, entry), List.of()));
}
private static RollbackPlanner planner(JournalSlice slice, TestWorld world) {
return new RollbackPlanner(ignored -> slice, world,
Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneOffset.UTC));
}
static RollbackQuery query() {
return new RollbackQuery(Instant.EPOCH, Instant.parse("2030-01-01T00:00:00Z"),
Set.of(), Set.of(), Set.of(), null, null, null);
}
static JournalEntry entry(long sequence, int x, WorldStatePayload before, WorldStatePayload after, boolean restorable) {
return new JournalEntry(sequence, new WorldChangeRecord(UUID.randomUUID(), Instant.EPOCH.plusSeconds(sequence),
sequence, "minecraft:overworld", x, 64, 0, WorldChangeKind.BLOCK_CHANGE,
"minecraft:stone", "player", "test", before, after, "tx-" + sequence, "vanilla", restorable));
}
static WorldStatePayload state(String name) {
return new WorldStatePayload("xfeservermanager:test", 1, "application/octet-stream",
name.getBytes(java.nio.charset.StandardCharsets.UTF_8), Map.of("name", name));
}
static Chunk chunk(JournalEntry entry) {
return new Chunk(entry.change().dimensionId(), Math.floorDiv(entry.change().x(), 16), Math.floorDiv(entry.change().z(), 16));
}
record Chunk(String dimension, int x, int z) { }
static class TestWorld implements WorldAccessPort {
final Set<Chunk> loaded = new HashSet<>();
final Map<UUID, WorldStatePayload> states = new HashMap<>();
final Set<String> incompatibleResources = new HashSet<>();
final List<UUID> applied = new ArrayList<>();
final Set<Chunk> acquired = new HashSet<>();
@Override public boolean isChunkLoaded(String dimensionId, int chunkX, int chunkZ) {
return loaded.contains(new Chunk(dimensionId, chunkX, chunkZ));
}
@Override public WorldStatePayload currentState(WorldChangeRecord change) {
return states.get(change.eventId());
}
@Override public Compatibility compatibility(WorldChangeRecord change, WorldStatePayload target) {
String name = target == null ? "" : target.metadata().getOrDefault("name", "");
return incompatibleResources.contains(name) ? Compatibility.unsupported("registry item is missing") : Compatibility.supported();
}
@Override public boolean acquireChunk(String dimensionId, int chunkX, int chunkZ) {
var chunk = new Chunk(dimensionId, chunkX, chunkZ);
acquired.add(chunk);
loaded.add(chunk);
return true;
}
@Override public void releaseChunk(String dimensionId, int chunkX, int chunkZ) {
var chunk = new Chunk(dimensionId, chunkX, chunkZ);
acquired.remove(chunk);
loaded.remove(chunk);
}
@Override public void apply(WorldChangeRecord change, WorldStatePayload target) {
states.put(change.eventId(), target);
applied.add(change.eventId());
}
}
}