diff --git a/core/src/main/java/art/arcane/iris/generation/runtime/EngineHotloader.java b/core/src/main/java/art/arcane/iris/generation/runtime/EngineHotloader.java index 7f33bc846..0907b75eb 100644 --- a/core/src/main/java/art/arcane/iris/generation/runtime/EngineHotloader.java +++ b/core/src/main/java/art/arcane/iris/generation/runtime/EngineHotloader.java @@ -259,8 +259,8 @@ final class EngineHotloader { IrisSettings settings = IrisSettings.get(); int transitionWidth = settings.getStudio().isBlendChanges() ? settings.getGenerator().getGenerationTransitionWidthBlocks() : 0; - history.stageUpdate(update.source(), update.fingerprint(), update.dimensionContract(), - update.registryContract(), transitionWidth); + history.stageUpdateReplacingStalePending(update.source(), update.fingerprint(), + update.dimensionContract(), update.registryContract(), transitionWidth); } long stagedAt = System.nanoTime(); cutover.promotePending(); diff --git a/core/src/main/java/art/arcane/iris/world/history/GenerationBoundaryStore.java b/core/src/main/java/art/arcane/iris/world/history/GenerationBoundaryStore.java index be3db16cf..5778ac3ba 100644 --- a/core/src/main/java/art/arcane/iris/world/history/GenerationBoundaryStore.java +++ b/core/src/main/java/art/arcane/iris/world/history/GenerationBoundaryStore.java @@ -121,6 +121,22 @@ public final class GenerationBoundaryStore { return publishCatalog(activationId, builder); } + synchronized void discardSnapshot(long activationId) throws IOException { + Path target = snapshotPath(activationId); + if (!Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) { + return; + } + validateStorageAncestors(); + try (GenerationPublicationLock ignored = GenerationPublicationLock.acquire( + directory, + ".activation-" + activationId + SNAPSHOT_FILE_SUFFIX + ".lock" + )) { + if (Files.deleteIfExists(target)) { + forceDirectory(directory); + } + } + } + public GenerationBoundary load(long activationId) throws IOException { requireActivation(activationId); validateStorageAncestors(); diff --git a/core/src/main/java/art/arcane/iris/world/history/GenerationHistory.java b/core/src/main/java/art/arcane/iris/world/history/GenerationHistory.java index 947405aae..920d23bcd 100644 --- a/core/src/main/java/art/arcane/iris/world/history/GenerationHistory.java +++ b/core/src/main/java/art/arcane/iris/world/history/GenerationHistory.java @@ -344,6 +344,31 @@ public final class GenerationHistory { ); } + /** + * Stages an update like {@link #stageUpdate(Path, String, GenerationEpoch.DimensionContract, + * GenerationRegistryContract, int)}, but first discards a pending activation for a different pack that never + * published its transition. A failed Studio hotload leaves such an activation behind, and the newer pack supersedes + * it. + */ + public synchronized GenerationActivation stageUpdateReplacingStalePending( + Path packSource, + String packFingerprint, + GenerationEpoch.DimensionContract dimensionContract, + GenerationRegistryContract registryContract, + int transitionWidthBlocks + ) throws IOException { + return stageUpdate( + packSource, + packFingerprint, + GenerationPackFingerprint.CURRENT_VERSION, + dimensionContract, + registryContract, + transitionWidthBlocks, + kernels.current(), + StalePendingUpdate.REPLACE + ); + } + synchronized GenerationActivation stageUpdate( Path packSource, String packFingerprint, @@ -359,7 +384,8 @@ public final class GenerationHistory { dimensionContract, registryContract, transitionWidthBlocks, - version + version, + StalePendingUpdate.REJECT ); } @@ -370,7 +396,8 @@ public final class GenerationHistory { GenerationEpoch.DimensionContract dimensionContract, GenerationRegistryContract registryContract, int transitionWidthBlocks, - GenerationKernelRegistry.Version version + GenerationKernelRegistry.Version version, + StalePendingUpdate stalePending ) throws IOException { GenerationEpoch candidate = epoch( packFingerprint, @@ -394,17 +421,20 @@ public final class GenerationHistory { } Optional pending = store.pendingActivation(); - if (pending.isPresent()) { - GenerationActivation activation = pending.get(); - if (!activation.epochId().equals(candidate.epochId())) { + if (pending.isPresent() && !pending.get().epochId().equals(candidate.epochId())) { + if (stalePending == StalePendingUpdate.REJECT) { throw new IllegalStateException("A different generation activation is already pending."); } + discardStalePending(pending.get()); + pending = Optional.empty(); + } + if (pending.isPresent()) { packs.requireExactPack( candidate.epochId(), candidate.packFingerprint(), candidate.packFingerprintVersion() ); - return activation; + return pending.get(); } if (store.activeEpoch().equals(candidate)) { @@ -436,6 +466,29 @@ public final class GenerationHistory { return store.preparePendingActivation(candidate, transitionWidthBlocks); } + /** + * Snapshots go before the manifest entry: a snapshot left without its activation would block the next activation + * that reuses the ID, while an activation left without snapshots simply publishes them again. + */ + private void discardStalePending(GenerationActivation stale) throws IOException { + if (stale.transition().isComplete()) { + throw new IllegalStateException("A different generation activation is already pending."); + } + long activationId = stale.activationId(); + boundaries.discardSnapshot(activationId); + terrainSignatures.discardSnapshot(activationId); + boundaryCache.remove(activationId); + terrainSignatureCache.remove(activationId); + transitionPlanCache.remove(activationId); + reclaimedChunksByActivation.remove(activationId); + store.discardPendingActivation(activationId); + } + + private enum StalePendingUpdate { + REJECT, + REPLACE + } + GenerationActivation promotePending( Collection signatures ) throws IOException { @@ -605,7 +658,8 @@ public final class GenerationHistory { active.dimensionContract(), active.registryContract(), transitionWidthBlocks, - kernels.current() + kernels.current(), + StalePendingUpdate.REJECT ); } @@ -1001,18 +1055,42 @@ public final class GenerationHistory { } /** - * Moves the given chunks that the active boundary froze to the active activation, so they generate with the current - * pack. Ownership keeps the claim; chunks outside the boundary already belong to the active pack and are skipped. + * Hands the given chunks to the active activation so they regenerate like new chunks. Ownership, the boundary's + * reclaimed set, recorded semantics and saved biomes change together, so a later promotion still finds every + * record owned by the activation that claimed it. Records go first: a crash in between leaves chunks with an owner + * and no record, which generation recovers from, instead of records that contradict their owner. * - * @return how many chunks changed hands + * @return how many chunks changed owner */ - public synchronized int reclaimForActivePack(List chunks) throws IOException { + public synchronized int releaseForRegeneration(List chunks) throws IOException { GenerationActivation active = store.activeActivation(); if (active.isInitial()) { return 0; } long activationId = active.activationId(); GenerationBoundary boundary = boundary(activationId); + List released = chunksTheActivePackMayOwn(chunks, boundary, activationId); + semantics.forgetEarlierClaims(released, activationId); + savedBiomes.forgetEarlierClaims(released, activationId); + return reclaimBoundaryChunks(released, boundary, activationId); + } + + private List chunksTheActivePackMayOwn( + List chunks, GenerationBoundary boundary, long activationId + ) { + List released = new ArrayList<>(chunks.size()); + for (GenerationBoundary.ChunkCoordinate chunk : chunks) { + if (boundary.isHistoricalChunk(chunk.chunkX(), chunk.chunkZ()) + || resolveActivation(chunk.chunkX(), chunk.chunkZ()).activationId() == activationId) { + released.add(chunk); + } + } + return released; + } + + private int reclaimBoundaryChunks( + List chunks, GenerationBoundary boundary, long activationId + ) throws IOException { ReclaimedChunks reclaimed = reclaimedChunks(activationId, boundary); int moved = 0; for (GenerationBoundary.ChunkCoordinate chunk : chunks) { diff --git a/core/src/main/java/art/arcane/iris/world/history/GenerationHistoryRuntimeRouter.java b/core/src/main/java/art/arcane/iris/world/history/GenerationHistoryRuntimeRouter.java index 8e7d498e6..7c97ff55d 100644 --- a/core/src/main/java/art/arcane/iris/world/history/GenerationHistoryRuntimeRouter.java +++ b/core/src/main/java/art/arcane/iris/world/history/GenerationHistoryRuntimeRouter.java @@ -139,16 +139,15 @@ public final class GenerationHistoryRuntimeRouter implements AutoCloseable { } /** - * Hands historical chunks to the active pack, so they generate like new chunks. Regen uses it to rebuild chunks from - * before the last hotload with the current pack, objects and caves included. + * Hands chunks to the active pack, so they generate like new chunks. Regen uses it to rebuild chunks from before the + * last hotload with the current pack, objects and caves included. */ - public int reclaimForActivePack(List chunks) throws IOException { + public int releaseForRegeneration(List chunks) throws IOException { try (GenerationTransitionGate.Participation ignored = engine.getGenerationSessions().transitionGate().enter()) { - int reclaimed = history.reclaimForActivePack(chunks); - if (reclaimed > 0) { - objectContinuations.clear(); - } - return reclaimed; + int released = history.releaseForRegeneration(chunks); + biomes.invalidateQueries(chunks); + objectContinuations.clear(); + return released; } } diff --git a/core/src/main/java/art/arcane/iris/world/history/GenerationHistoryStore.java b/core/src/main/java/art/arcane/iris/world/history/GenerationHistoryStore.java index d329221c1..9e09d655d 100644 --- a/core/src/main/java/art/arcane/iris/world/history/GenerationHistoryStore.java +++ b/core/src/main/java/art/arcane/iris/world/history/GenerationHistoryStore.java @@ -183,6 +183,13 @@ public final class GenerationHistoryStore { return updated.pendingActivation().orElseThrow(); } + public synchronized void discardPendingActivation(long expectedActivationId) throws IOException { + requireUsable(); + GenerationManifest updated = manifest.discardPending(expectedActivationId); + writeUpdatedManifest(updated); + manifest = updated; + } + public synchronized GenerationActivation completePendingTransition( long expectedActivationId, String boundaryIdentity, diff --git a/core/src/main/java/art/arcane/iris/world/history/GenerationManifest.java b/core/src/main/java/art/arcane/iris/world/history/GenerationManifest.java index 5d02242e9..d360a7a61 100644 --- a/core/src/main/java/art/arcane/iris/world/history/GenerationManifest.java +++ b/core/src/main/java/art/arcane/iris/world/history/GenerationManifest.java @@ -155,6 +155,32 @@ public final class GenerationManifest { )); } + GenerationManifest discardPending(long expectedActivationId) { + GenerationActivation pending = pendingActivation() + .orElseThrow(() -> new IllegalStateException("No generation activation is pending.")); + if (pending.activationId() != expectedActivationId) { + throw new IllegalStateException("Pending activation changed before it was discarded."); + } + if (pending.transition().isComplete()) { + throw new IllegalStateException("A pending activation that published its transition cannot be discarded."); + } + TreeMap nextActivations = new TreeMap<>(activations); + nextActivations.remove(pending.activationId()); + TreeMap nextEpochs = new TreeMap<>(epochs); + boolean epochStillReferenced = nextActivations.values().stream() + .anyMatch(activation -> activation.epochId().equals(pending.epochId())); + if (!epochStillReferenced) { + nextEpochs.remove(pending.epochId()); + } + return new GenerationManifest(new State( + schemaVersion, + nextEpochs, + nextActivations, + activeActivationId, + null + )); + } + GenerationManifest completePendingTransition( long expectedActivationId, String boundaryIdentity, diff --git a/core/src/main/java/art/arcane/iris/world/history/GenerationSemanticIndex.java b/core/src/main/java/art/arcane/iris/world/history/GenerationSemanticIndex.java index c6daba662..0b7cc0e40 100644 --- a/core/src/main/java/art/arcane/iris/world/history/GenerationSemanticIndex.java +++ b/core/src/main/java/art/arcane/iris/world/history/GenerationSemanticIndex.java @@ -31,6 +31,7 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.Comparator; import java.util.EnumMap; import java.util.EnumSet; @@ -341,19 +342,7 @@ public final class GenerationSemanticIndex { int regionZ = regionZ(regionKey); RegionShard previous = loadRegionLocked(regionKey, regionX, regionZ); RegionShard replacement = previous.retainingStoredClaims(stored, selected); - int count = previous.recordCount() - replacement.recordCount(); - if (count == 0) { - continue; - } - byte[] encoded = replacement.encode(); - String hash = sha256(encoded); - publisher.publish(directory, regionX, regionZ, encoded); - pointerPublisher.publish(directory, regionX, regionZ, hash); - String previousHash = shardHashes.put(regionKey, hash); - regionRecordCounts.put(regionKey, replacement.recordCount()); - cacheRegion(regionKey, replacement); - removed += count; - deleteUnreferencedShard(regionX, regionZ, previousHash, hash); + removed += replaceRegionLocked(regionKey, previous, replacement); } return removed; } finally { @@ -362,6 +351,61 @@ public final class GenerationSemanticIndex { } } + /** + * Drops the records of the given chunks that an activation other than the one now owning them claimed, so those + * chunks can be generated and recorded again by their owner. + * + * @return how many records were dropped + */ + public int forgetEarlierClaims(Collection chunks, long owningActivationId) + throws IOException { + Map chunksByRegion = new LinkedHashMap<>(); + for (GenerationBoundary.ChunkCoordinate chunk : chunks) { + chunksByRegion.computeIfAbsent(packRegion(chunk.chunkX() >> 5, chunk.chunkZ() >> 5), + ignored -> new LongOpenHashSet()).add(ChunkGenerationOwnership.packChunk(chunk.chunkX(), chunk.chunkZ())); + } + if (chunksByRegion.isEmpty()) { + return 0; + } + lock.writeLock().lock(); + publicationLock.lock(); + try { + compactJournals(); + int removed = 0; + for (Map.Entry region : chunksByRegion.entrySet()) { + long regionKey = region.getKey(); + RegionShard previous = loadRegionLocked(regionKey, regionX(regionKey), regionZ(regionKey)); + RegionShard replacement = previous.withoutEarlierClaims(region.getValue(), owningActivationId); + removed += replaceRegionLocked(regionKey, previous, replacement); + } + if (removed > 0) { + riverRevision.incrementAndGet(); + } + return removed; + } finally { + publicationLock.unlock(); + lock.writeLock().unlock(); + } + } + + private int replaceRegionLocked(long regionKey, RegionShard previous, RegionShard replacement) throws IOException { + int count = previous.recordCount() - replacement.recordCount(); + if (count == 0) { + return 0; + } + int regionX = regionX(regionKey); + int regionZ = regionZ(regionKey); + byte[] encoded = replacement.encode(); + String hash = sha256(encoded); + publisher.publish(directory, regionX, regionZ, encoded); + pointerPublisher.publish(directory, regionX, regionZ, hash); + String previousHash = shardHashes.put(regionKey, hash); + regionRecordCounts.put(regionKey, replacement.recordCount()); + cacheRegion(regionKey, replacement); + deleteUnreferencedShard(regionX, regionZ, previousHash, hash); + return count; + } + public void compactJournals() throws IOException { lock.writeLock().lock(); publicationLock.lock(); @@ -2596,6 +2640,23 @@ public final class GenerationSemanticIndex { return replacement; } + private RegionShard withoutEarlierClaims(LongOpenHashSet chunks, long owningActivationId) { + RegionShard replacement = new RegionShard(regionX, regionZ); + for (int index = 0; index < records.length; index++) { + ChunkGenerationSemantics record = records[index]; + if (record == null) { + continue; + } + boolean forgotten = record.activationId() != owningActivationId + && chunks.contains(ChunkGenerationOwnership.packChunk(record.chunkX(), record.chunkZ())); + if (!forgotten) { + replacement.records[index] = record; + replacement.recordCount++; + } + } + return replacement; + } + private RegionShard withRecord(ChunkGenerationSemantics semantics) { if ((semantics.chunkX() >> 5) != regionX || (semantics.chunkZ() >> 5) != regionZ) { throw new IllegalArgumentException("Chunk does not belong to generation semantic shard"); diff --git a/core/src/main/java/art/arcane/iris/world/history/SavedBiomeRuntime.java b/core/src/main/java/art/arcane/iris/world/history/SavedBiomeRuntime.java index 84e22451d..2c6844acb 100644 --- a/core/src/main/java/art/arcane/iris/world/history/SavedBiomeRuntime.java +++ b/core/src/main/java/art/arcane/iris/world/history/SavedBiomeRuntime.java @@ -22,6 +22,7 @@ import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; +import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -255,8 +256,18 @@ public final class SavedBiomeRuntime implements AutoCloseable { public void capture(SavedBiomeChunk chunk) throws IOException { requireOpen(); store.claimAndPersist(chunk); + invalidateQuery(chunk.chunkX(), chunk.chunkZ()); + } + + void invalidateQueries(Collection chunks) { + for (GenerationBoundary.ChunkCoordinate chunk : chunks) { + invalidateQuery(chunk.chunkX(), chunk.chunkZ()); + } + } + + private void invalidateQuery(int chunkX, int chunkZ) { synchronized (queries) { - long key = key(chunk.chunkX(), chunk.chunkZ()); + long key = key(chunkX, chunkZ); PreparedQuery removed = queries.remove(key); if (removed != null) { queryBytes -= removed.estimatedBytes(); diff --git a/core/src/main/java/art/arcane/iris/world/history/SavedBiomeStore.java b/core/src/main/java/art/arcane/iris/world/history/SavedBiomeStore.java index 23a6520e1..972e75a7b 100644 --- a/core/src/main/java/art/arcane/iris/world/history/SavedBiomeStore.java +++ b/core/src/main/java/art/arcane/iris/world/history/SavedBiomeStore.java @@ -21,6 +21,7 @@ import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; import java.util.ArrayList; +import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; @@ -351,6 +352,48 @@ public final class SavedBiomeStore { return removed; } + /** + * Drops the saved biomes of the given chunks that an activation other than the one now owning them captured, so + * their owner can capture them again. + * + * @return how many chunks were dropped + */ + public int forgetEarlierClaims(Collection chunks, long owningActivationId) + throws IOException { + requireSafeAncestors(); + if (chunks.isEmpty() || !Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) { + return 0; + } + Map> chunksByRegion = new LinkedHashMap<>(); + for (GenerationBoundary.ChunkCoordinate chunk : chunks) { + chunksByRegion.computeIfAbsent(key(chunk.chunkX() >> 5, chunk.chunkZ() >> 5), + ignored -> new ArrayList<>()).add(chunk); + } + int removed = 0; + for (List regionChunks : chunksByRegion.values()) { + GenerationBoundary.ChunkCoordinate anchor = regionChunks.getFirst(); + synchronized (regionLock(anchor.chunkX(), anchor.chunkZ())) { + requireWritable(); + RegionIndex region = region(anchor.chunkX(), anchor.chunkZ()); + boolean[] discarded = new boolean[1024]; + int count = 0; + for (GenerationBoundary.ChunkCoordinate chunk : regionChunks) { + int slot = slot(chunk.chunkX(), chunk.chunkZ()); + if (!discarded[slot] && region.offsets[slot] != 0L + && readRecord(region, slot).activationId() != owningActivationId) { + discarded[slot] = true; + count++; + } + } + if (count != 0) { + rewriteRegion(region, discarded); + removed = Math.addExact(removed, count); + } + } + } + return removed; + } + int cachedRegionCount() { synchronized (regions) { return regions.size(); diff --git a/core/src/main/java/art/arcane/iris/world/history/TerrainBoundarySignatureStore.java b/core/src/main/java/art/arcane/iris/world/history/TerrainBoundarySignatureStore.java index 93dcd09e0..11201350e 100644 --- a/core/src/main/java/art/arcane/iris/world/history/TerrainBoundarySignatureStore.java +++ b/core/src/main/java/art/arcane/iris/world/history/TerrainBoundarySignatureStore.java @@ -224,6 +224,22 @@ public final class TerrainBoundarySignatureStore { return load(activationId); } + synchronized void discardSnapshot(long activationId) throws IOException { + Path target = snapshotPath(activationId); + if (!Files.exists(directory, LinkOption.NOFOLLOW_LINKS)) { + return; + } + validateStorageAncestors(); + try (GenerationPublicationLock ignored = GenerationPublicationLock.acquire( + directory, + ".activation-" + activationId + SNAPSHOT_FILE_SUFFIX + ".lock" + )) { + if (Files.deleteIfExists(target)) { + forceDirectory(directory); + } + } + } + public Snapshot load(long activationId) throws IOException { requireActivation(activationId); validateStorageAncestors(); diff --git a/core/src/main/java/art/arcane/iris/world/history/VersionedGenerationSource.java b/core/src/main/java/art/arcane/iris/world/history/VersionedGenerationSource.java index cac85b3af..8e33033c1 100644 --- a/core/src/main/java/art/arcane/iris/world/history/VersionedGenerationSource.java +++ b/core/src/main/java/art/arcane/iris/world/history/VersionedGenerationSource.java @@ -180,7 +180,7 @@ public final class VersionedGenerationSource implements GenerationSource { public void releaseForRegeneration(List chunks) throws IOException { GenerationHistoryRuntimeRouter attached = router; if (attached != null) { - attached.reclaimForActivePack(chunks); + attached.releaseForRegeneration(chunks); } } diff --git a/core/src/test/java/art/arcane/iris/world/history/GenerationHistoryTest.java b/core/src/test/java/art/arcane/iris/world/history/GenerationHistoryTest.java index 4ed630491..ca3d9aaac 100644 --- a/core/src/test/java/art/arcane/iris/world/history/GenerationHistoryTest.java +++ b/core/src/test/java/art/arcane/iris/world/history/GenerationHistoryTest.java @@ -178,12 +178,12 @@ public class GenerationHistoryTest extends GenerationHistorySupport { stage(history, packB); history.promotePending(signaturesForChunks(chunks)); - int moved = history.reclaimForActivePack(List.of( + int moved = history.releaseForRegeneration(List.of( new GenerationBoundary.ChunkCoordinate(3, 4), new GenerationBoundary.ChunkCoordinate(40, 40))); assertEquals(1, moved); - assertEquals(0, history.reclaimForActivePack(List.of(new GenerationBoundary.ChunkCoordinate(3, 4)))); + assertEquals(0, history.releaseForRegeneration(List.of(new GenerationBoundary.ChunkCoordinate(3, 4)))); TransitionGenerationPlan plan = history.transitionPlan(2L); assertFalse(plan.isHistoricalChunk(3, 4)); assertTrue(plan.allowsNewDiscreteContentAt(3 * 16, 4 * 16)); diff --git a/core/src/test/java/art/arcane/iris/world/history/GenerationStudioRecoveryTest.java b/core/src/test/java/art/arcane/iris/world/history/GenerationStudioRecoveryTest.java new file mode 100644 index 000000000..c3ebd258f --- /dev/null +++ b/core/src/test/java/art/arcane/iris/world/history/GenerationStudioRecoveryTest.java @@ -0,0 +1,154 @@ +package art.arcane.iris.world.history; + +import org.junit.Test; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +public class GenerationStudioRecoveryTest extends GenerationHistorySupport { + private static final GenerationBoundary.ChunkCoordinate REGENERATED = new GenerationBoundary.ChunkCoordinate(3, 4); + + @Test + public void regenForgetsEarlierRecordsSoTheNextPromotionStaysConsistent() throws Exception { + Path world = temporaryFolder.newFolder("regen-release-world").toPath(); + GenerationHistory history = createHistory(world, createPack("regen-release-a", "alpha")); + int[][] chunks = {{3, 4}, {5, 4}}; + writeRegion(Files.createDirectories(world.resolve("region")).resolve("r.0.0.mca"), chunks); + claimSemantics(history, 3, 4, 1L); + claimSemantics(history, 5, 4, 1L); + assertTrue(history.savedBiomes().claimAndPersist(savedBiomes(3, 4, 1L))); + stage(history, createPack("regen-release-b", "beta")); + promoteLive(history); + + assertEquals(1, history.releaseForRegeneration(List.of(REGENERATED))); + + assertEquals(2L, history.resolveActivation(3, 4).activationId()); + assertTrue(history.semantics(3, 4).isEmpty()); + assertTrue(history.savedBiomes().get(3, 4).isEmpty()); + assertEquals(1L, history.semantics(5, 4).orElseThrow().activationId()); + claimSemantics(history, 3, 4, 2L); + assertTrue(history.savedBiomes().claimAndPersist(savedBiomes(3, 4, 2L))); + stage(history, createPack("regen-release-c", "gamma")); + promoteLive(history); + + assertEquals(3L, history.activeActivation().activationId()); + GenerationHistory reopened = GenerationHistory.open(world); + assertEquals(2L, reopened.semantics(3, 4).orElseThrow().activationId()); + assertEquals(2L, reopened.resolveActivation(3, 4).activationId()); + } + + @Test + public void regenHealsRecordsThatAnEarlierReclaimLeftOnTheOldActivation() throws Exception { + Path world = temporaryFolder.newFolder("regen-heal-world").toPath(); + GenerationHistory history = createHistory(world, createPack("regen-heal-a", "alpha")); + int[][] chunks = {{3, 4}}; + writeRegion(Files.createDirectories(world.resolve("region")).resolve("r.0.0.mca"), chunks); + claimSemantics(history, 3, 4, 1L); + stage(history, createPack("regen-heal-b", "beta")); + promoteLive(history); + history.releaseForRegeneration(List.of(REGENERATED)); + claimSemantics(history, 3, 4, 2L); + + assertEquals(0, history.releaseForRegeneration(List.of(REGENERATED))); + + assertEquals(2L, history.semantics(3, 4).orElseThrow().activationId()); + } + + @Test + public void newerStudioUpdateReplacesAPendingActivationThatNeverPromoted() throws Exception { + Path world = temporaryFolder.newFolder("stale-pending-world").toPath(); + GenerationHistory history = createHistory(world, createPack("stale-pending-a", "alpha")); + Path failedPack = createPack("stale-pending-b", "beta"); + Path nextPack = createPack("stale-pending-c", "gamma"); + String failedEpoch = stage(history, failedPack).epochId(); + + assertThrows(IllegalStateException.class, () -> stage(history, nextPack)); + GenerationActivation replaced = stageReplacing(history, nextPack); + + assertEquals(2L, replaced.activationId()); + assertFalse(replaced.epochId().equals(failedEpoch)); + assertTrue(history.manifest().epochs().stream().noneMatch(epoch -> epoch.epochId().equals(failedEpoch))); + history.promotePending(List.of()); + assertEquals(replaced.epochId(), GenerationHistory.open(world).activeActivation().epochId()); + } + + @Test + public void replacedPendingActivationPublishesItsOwnBoundary() throws Exception { + Path world = temporaryFolder.newFolder("stale-boundary-world").toPath(); + GenerationHistory history = createHistory(world, createPack("stale-boundary-a", "alpha")); + Path region = Files.createDirectories(world.resolve("region")).resolve("r.0.0.mca"); + writeRegion(region, new int[][]{{3, 4}}); + stage(history, createPack("stale-boundary-b", "beta")); + assertThrows(IOException.class, () -> history.promotePending(boundary -> { + throw new IOException("signature capture failed"); + })); + assertTrue(history.pendingActivation().isPresent()); + int[][] grown = {{3, 4}, {5, 4}}; + writeRegion(region, grown); + + stageReplacing(history, createPack("stale-boundary-c", "gamma")); + history.promotePending(signaturesForChunks(grown)); + + assertEquals(2L, history.activeActivation().activationId()); + assertTrue(history.transitionPlan(2L).isHistoricalChunk(5, 4)); + } + + @Test + public void revertingToTheActivePackDropsTheStalePendingActivation() throws Exception { + Path world = temporaryFolder.newFolder("stale-revert-world").toPath(); + Path activePack = createPack("stale-revert-a", "alpha"); + GenerationHistory history = createHistory(world, activePack); + stage(history, createPack("stale-revert-b", "beta")); + + GenerationActivation staged = stageReplacing(history, activePack); + + assertEquals(history.activeActivation(), staged); + assertTrue(history.pendingActivation().isEmpty()); + assertEquals(1, history.manifest().activations().size()); + } + + private static void promoteLive(GenerationHistory history) throws IOException { + try (GenerationHistory.LiveCutover cutover = history.beginLiveCutover()) { + cutover.promote(boundary -> (blockX, blockZ) -> signature(blockX, blockZ)); + } + } + + private static GenerationActivation stageReplacing(GenerationHistory history, Path pack) throws IOException { + return history.stageUpdateReplacingStalePending( + pack, + fingerprint(pack), + contract(), + GenerationRegistryContract.empty(), + 256 + ); + } + + private static void claimSemantics(GenerationHistory history, int chunkX, int chunkZ, long activationId) + throws IOException { + try (GenerationHistory.GenerationStage stage = history.openStage(chunkX, chunkZ)) { + assertTrue(history.claimGeneratedSemantics(stage, + ChunkGenerationSemantics.builder(chunkX, chunkZ, activationId).addObject("object").seal().build())); + } + } + + private static SavedBiomeChunk savedBiomes(int chunkX, int chunkZ, long activationId) { + SavedBiomeChunk.Cell cell = new SavedBiomeChunk.Cell(activationId, "biome/main", "region/main"); + SavedBiomeChunk.Column column = new SavedBiomeChunk.Column(cell, cell, + List.of(new SavedBiomeChunk.Span(-64, 320, cell))); + SavedBiomeChunk.Builder builder = SavedBiomeChunk.builder( + new SavedBiomeChunk.Header(chunkX, chunkZ, activationId, -64, 384)); + for (int z = 0; z < 16; z++) { + for (int x = 0; x < 16; x++) { + builder.column(x, z, column); + } + } + return builder.build(); + } +} diff --git a/core/src/test/java/art/arcane/iris/world/history/VersionedGenerationSourceTest.java b/core/src/test/java/art/arcane/iris/world/history/VersionedGenerationSourceTest.java index 1f0b9115a..b3cadf651 100644 --- a/core/src/test/java/art/arcane/iris/world/history/VersionedGenerationSourceTest.java +++ b/core/src/test/java/art/arcane/iris/world/history/VersionedGenerationSourceTest.java @@ -64,7 +64,7 @@ public class VersionedGenerationSourceTest { List chunks = List.of(new GenerationBoundary.ChunkCoordinate(-72, -15)); new VersionedGenerationSource(router).releaseForRegeneration(chunks); - verify(router).reclaimForActivePack(chunks); + verify(router).releaseForRegeneration(chunks); } @Test