From 95395cbc8794e953872e881c6a2124d3080dd7ca Mon Sep 17 00:00:00 2001 From: Brian Fopiano Date: Sat, 28 Nov 2026 09:55:11 -0500 Subject: [PATCH] Cache saved terrain status - Add per-slot terrain status cache under the iris folder - Reuse a bit only when header location and timestamp match - Decode again when timestamps fall near the previous scan time - Never reuse bits for chunks stored in external mcc files - Skip reading region files when every pending chunk is cached - Use the cache only for the startup recovery scan - Ignore unreadable or mismatched cache files and rescan fully - Cover warm hits, invalidation and corrupt cache in tests --- .../iris/world/history/GenerationHistory.java | 3 +- .../history/SavedTerrainRecoveryScan.java | 78 +++- .../history/SavedTerrainStatusCache.java | 379 ++++++++++++++++++ .../history/SavedTerrainRecoveryScanTest.java | 211 ++++++++++ 4 files changed, 665 insertions(+), 6 deletions(-) create mode 100644 core/src/main/java/art/arcane/iris/world/history/SavedTerrainStatusCache.java 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 548ad2e5b..8b1b73081 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 @@ -697,7 +697,8 @@ public final class GenerationHistory { && !selected.contains(ownership.resolve(chunkX, chunkZ, outgoing)); WorldChunkInventory inventory; if (startupRecovery) { - inventory = SavedTerrainRecoveryScan.scan(paths.dimensionRoot(), allocated, retained); + inventory = SavedTerrainRecoveryScan.scan(paths.dimensionRoot(), allocated, retained, + paths.irisRoot().resolve(SavedTerrainStatusCache.FILE_NAME)); } else { try (SavedTerrainChunkReader.StatusReader reader = new SavedTerrainChunkReader.StatusReader(paths.dimensionRoot())) { inventory = allocated.filter((chunkX, chunkZ) -> retained.test(chunkX, chunkZ) diff --git a/core/src/main/java/art/arcane/iris/world/history/SavedTerrainRecoveryScan.java b/core/src/main/java/art/arcane/iris/world/history/SavedTerrainRecoveryScan.java index e3fba4542..71b83745b 100644 --- a/core/src/main/java/art/arcane/iris/world/history/SavedTerrainRecoveryScan.java +++ b/core/src/main/java/art/arcane/iris/world/history/SavedTerrainRecoveryScan.java @@ -3,6 +3,7 @@ package art.arcane.iris.world.history; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; +import java.util.Arrays; import java.util.BitSet; import java.util.List; import java.util.Optional; @@ -20,10 +21,16 @@ final class SavedTerrainRecoveryScan implements AutoCloseable { private final int regionByteLimit; private final SavedTerrainChunkReader.StatusReader[] readers; private final ExecutorService executor; + private final SavedTerrainStatusCache cache; private byte[] regionBuffer = new byte[0]; SavedTerrainRecoveryScan(Path world, Limits limits) { + this(world, limits, null); + } + + SavedTerrainRecoveryScan(Path world, Limits limits, SavedTerrainStatusCache cache) { this.world = world; + this.cache = cache; regionByteLimit = limits.regionBytes(); readers = new SavedTerrainChunkReader.StatusReader[limits.workers()]; for (int index = 0; index < readers.length; index++) { @@ -35,11 +42,26 @@ final class SavedTerrainRecoveryScan implements AutoCloseable { static WorldChunkInventory scan(Path world, WorldChunkInventory inventory, WorldChunkInventory.ChunkPredicate retained) throws IOException { + return scan(world, inventory, retained, null); + } + + /** + * Scans with the status cache at {@code cacheFile}, or without a cache when it is null. The cache is + * written once, after the whole scan succeeded. + */ + static WorldChunkInventory scan(Path world, WorldChunkInventory inventory, + WorldChunkInventory.ChunkPredicate retained, Path cacheFile) throws IOException { Runtime runtime = Runtime.getRuntime(); + SavedTerrainStatusCache cache = cacheFile == null ? null : SavedTerrainStatusCache.load(cacheFile, world); + WorldChunkInventory result; try (SavedTerrainRecoveryScan scan = new SavedTerrainRecoveryScan(world, - Limits.forRuntime(runtime.availableProcessors(), runtime.maxMemory()))) { - return scan.filter(inventory, retained); + Limits.forRuntime(runtime.availableProcessors(), runtime.maxMemory()), cache)) { + result = scan.filter(inventory, retained); } + if (cache != null) { + cache.save(); + } + return result; } WorldChunkInventory filter(WorldChunkInventory inventory, WorldChunkInventory.ChunkPredicate retained) @@ -81,18 +103,39 @@ final class SavedTerrainRecoveryScan implements AutoCloseable { } } if (pending.isEmpty()) { + if (cache != null) { + cache.carry(region.x(), region.z()); + } return accepted; } Path file = world.resolve("region/r." + region.x() + "." + region.z() + ".mca"); + SavedTerrainStatusCache.Header header = cache == null ? null : readHeader(file); + SavedTerrainStatusCache.Update update = null; + if (header != null) { + update = cache.begin(region.x(), region.z(), header, pending, accepted); + if (pending.isEmpty()) { + update.commit(); + return accepted; + } + } int snapshotLimit = Math.min(regionByteLimit, pending.cardinality() * 64 * 1024); Optional captured = SavedTerrainRegionSnapshot.read(file, snapshotLimit, regionBuffer); if (captured.isEmpty()) { + BitSet terrain = new BitSet(1024); for (int slot = pending.nextSetBit(0); slot >= 0; slot = pending.nextSetBit(slot + 1)) { requireNotInterrupted(); if (SavedTerrainChunk.hasTerrain(readers[0].readStatus(region.chunkX(slot), region.chunkZ(slot)))) { - accepted.set(slot); + terrain.set(slot); } } + accepted.or(terrain); + if (update != null) { + SavedTerrainStatusCache.Header after = readHeader(file); + if (after != null && header.sameHeader(after)) { + record(update, region, header, pending, terrain); + } + update.commit(); + } return accepted; } SavedTerrainRegionSnapshot snapshot = captured.get(); @@ -106,8 +149,9 @@ final class SavedTerrainRecoveryScan implements AutoCloseable { pending.clear(slot); } } + BitSet terrain; if (executor == null || pending.cardinality() < MIN_PARALLEL_CHUNKS) { - accepted.or(decode(new DecodeRegion(region, pending, snapshot), 0, 1)); + terrain = decode(new DecodeRegion(region, pending, snapshot), 0, 1); } else { List> tasks = new ArrayList<>(readers.length); DecodeRegion input = new DecodeRegion(region, pending, snapshot); @@ -115,12 +159,36 @@ final class SavedTerrainRecoveryScan implements AutoCloseable { int worker = index; tasks.add(executor.submit(() -> decode(input, worker, readers.length))); } - accepted.or(await(tasks)); + terrain = await(tasks); } + accepted.or(terrain); snapshot.validateUnchanged(); + if (update != null) { + record(update, region, new SavedTerrainStatusCache.Header(header.fileKey(), header.size(), + Arrays.copyOf(snapshot.bytes(), SavedTerrainStatusCache.Header.BYTES)), pending, terrain); + update.commit(); + } return accepted; } + private void record(SavedTerrainStatusCache.Update update, Region region, SavedTerrainStatusCache.Header header, + BitSet decoded, BitSet terrain) { + for (int slot = decoded.nextSetBit(0); slot >= 0; slot = decoded.nextSetBit(slot + 1)) { + if (!cache.isExternal(region.chunkX(slot), region.chunkZ(slot))) { + update.record(slot, header.location(slot), header.timestamp(slot), terrain.get(slot)); + } + } + } + + private static SavedTerrainStatusCache.Header readHeader(Path file) { + try { + return SavedTerrainStatusCache.Header.read(file); + } catch (IOException ignored) { + // The uncached read reports the real problem with this region. + return null; + } + } + private BitSet decode(DecodeRegion input, int worker, int stride) throws IOException { BitSet accepted = new BitSet(1024); int ordinal = 0; diff --git a/core/src/main/java/art/arcane/iris/world/history/SavedTerrainStatusCache.java b/core/src/main/java/art/arcane/iris/world/history/SavedTerrainStatusCache.java new file mode 100644 index 000000000..60e352b6a --- /dev/null +++ b/core/src/main/java/art/arcane/iris/world/history/SavedTerrainStatusCache.java @@ -0,0 +1,379 @@ +package art.arcane.iris.world.history; + +import art.arcane.iris.spi.IrisLogging; +import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; +import it.unimi.dsi.fastutil.longs.LongOpenHashSet; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.NoSuchFileException; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.Arrays; +import java.util.BitSet; +import java.util.Objects; +import java.util.zip.CRC32; + +/** + * Remembers the decoded "has terrain" bit of each saved chunk between startups. A bit is reused only while the + * slot's location word and timestamp in the region header are unchanged, the timestamp is at least two seconds + * older than the scan that decoded it, and the chunk is not stored in an external .mcc file. Ownership filtering + * is never cached; callers apply it on every scan. + */ +final class SavedTerrainStatusCache { + static final String FILE_NAME = "terrain-status.cache"; + + private static final int MAGIC = 0x49545343; + private static final int VERSION = 1; + private static final int SLOTS = 1024; + private static final int HEADER_BYTES = 2 * 4096; + private static final long MAX_CACHE_BYTES = 1L << 30; + + private final Path file; + private final Path regionDirectory; + private final long scanSeconds; + private final long previousScanSeconds; + private final Long2ObjectOpenHashMap previous; + private final Long2ObjectOpenHashMap next = new Long2ObjectOpenHashMap<>(); + private LongOpenHashSet externalChunks; + private boolean externalChunksUnknown; + + private SavedTerrainStatusCache(Path file, Path world, long scanSeconds, Contents contents) { + this.file = file; + regionDirectory = world.toAbsolutePath().normalize().resolve(GenerationHistoryPaths.REGION_DIRECTORY_NAME); + this.scanSeconds = scanSeconds; + previousScanSeconds = contents.scanSeconds(); + previous = contents.regions(); + } + + static SavedTerrainStatusCache load(Path file, Path world) { + Objects.requireNonNull(file, "file"); + Objects.requireNonNull(world, "world"); + long now = System.currentTimeMillis() / 1000L; + return new SavedTerrainStatusCache(file, world, now, readContents(file)); + } + + /** + * Starts the cache update for one region and moves every pending slot whose cached bit is still valid out of + * {@code pending}, setting it in {@code accepted} when the chunk has terrain. + */ + Update begin(int regionX, int regionZ, Header header, BitSet pending, BitSet accepted) { + Update update = new Update(regionX, regionZ, header); + Region cached = previous.get(ChunkGenerationOwnership.packChunk(regionX, regionZ)); + if (cached == null || !cached.matches(header)) { + return update; + } + for (int entry = 0; entry < cached.slots().length; entry++) { + int slot = cached.slots()[entry]; + if (header.location(slot) != cached.locations()[entry] + || header.timestamp(slot) != cached.timestamps()[entry] + || !reusable(cached.locations()[entry], cached.timestamps()[entry], previousScanSeconds) + || isExternal(regionX * 32 + (slot & 31), regionZ * 32 + (slot >> 5))) { + continue; + } + boolean terrain = cached.terrain().get(entry); + update.keep(slot, cached.locations()[entry], cached.timestamps()[entry], terrain); + if (pending.get(slot)) { + pending.clear(slot); + if (terrain) { + accepted.set(slot); + } + } + } + return update; + } + + /** + * Keeps a region's cached entries as they are, for a region the scan did not need to read. + */ + void carry(int regionX, int regionZ) { + long key = ChunkGenerationOwnership.packChunk(regionX, regionZ); + Region cached = previous.get(key); + if (cached != null) { + next.put(key, cached); + } + } + + /** + * True when the chunk has an external .mcc payload, or when the region directory could not be listed. + */ + boolean isExternal(int chunkX, int chunkZ) { + if (externalChunks == null && !externalChunksUnknown) { + try { + externalChunks = listExternalChunks(regionDirectory); + } catch (IOException | RuntimeException failure) { + externalChunksUnknown = true; + IrisLogging.warnOnce("saved-terrain-cache-external", () -> "Not using the saved terrain status cache" + + " because " + regionDirectory + " could not be listed: " + failure); + } + } + return externalChunksUnknown + || externalChunks.contains(ChunkGenerationOwnership.packChunk(chunkX, chunkZ)); + } + + /** + * Writes the cache with the regions visited by this scan. Regions that were not visited are dropped. Failures + * are logged and never reach the caller. + */ + void save() { + try { + byte[] encoded = encode(scanSeconds, next); + Path directory = file.toAbsolutePath().getParent(); + Files.createDirectories(directory); + Path temporary = Files.createTempFile(directory, "." + file.getFileName() + "-", ".tmp"); + try { + Files.write(temporary, encoded); + Files.move(temporary, file, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + } finally { + Files.deleteIfExists(temporary); + } + } catch (IOException | RuntimeException failure) { + IrisLogging.warnOnce("saved-terrain-cache-write", () -> "Could not write the saved terrain status cache " + + file + ": " + failure); + } + } + + private boolean reusable(int location, int timestamp, long decodedAt) { + return location != 0 && Integer.toUnsignedLong(timestamp) < decodedAt - 1L; + } + + private static LongOpenHashSet listExternalChunks(Path regionDirectory) throws IOException { + LongOpenHashSet chunks = new LongOpenHashSet(); + try (DirectoryStream entries = Files.newDirectoryStream(regionDirectory, "c.*.*.mcc")) { + for (Path entry : entries) { + String[] parts = entry.getFileName().toString().split("\\."); + if (parts.length != 4) { + continue; + } + try { + chunks.add(ChunkGenerationOwnership.packChunk(Integer.parseInt(parts[1]), + Integer.parseInt(parts[2]))); + } catch (NumberFormatException ignored) { + // Not a chunk payload name; the region reader ignores it too. + } + } + } catch (NoSuchFileException ignored) { + return chunks; + } + return chunks; + } + + private static Contents readContents(Path file) { + try { + if (!Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) { + return Contents.EMPTY; + } + if (Files.size(file) > MAX_CACHE_BYTES) { + throw new IOException("cache file is too large"); + } + return decode(Files.readAllBytes(file)); + } catch (IOException | RuntimeException failure) { + IrisLogging.warnOnce("saved-terrain-cache-read", () -> "Ignoring the saved terrain status cache " + + file + ": " + failure.getMessage()); + return Contents.EMPTY; + } + } + + private static byte[] encode(long scanSeconds, Long2ObjectOpenHashMap regions) throws IOException { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(buffer)) { + output.writeInt(MAGIC); + output.writeInt(VERSION); + output.writeLong(scanSeconds); + output.writeInt(regions.size()); + for (Region region : regions.values()) { + output.writeInt(region.x()); + output.writeInt(region.z()); + output.writeLong(region.size()); + output.writeUTF(region.fileKey()); + output.writeShort(region.slots().length); + for (int entry = 0; entry < region.slots().length; entry++) { + output.writeShort(region.slots()[entry]); + output.writeInt(region.locations()[entry]); + output.writeInt(region.timestamps()[entry]); + output.writeBoolean(region.terrain().get(entry)); + } + } + CRC32 checksum = new CRC32(); + checksum.update(buffer.toByteArray()); + output.writeLong(checksum.getValue()); + } + return buffer.toByteArray(); + } + + private static Contents decode(byte[] bytes) throws IOException { + if (bytes.length < Long.BYTES) { + throw new IOException("cache file is truncated"); + } + CRC32 checksum = new CRC32(); + checksum.update(bytes, 0, bytes.length - Long.BYTES); + if (ByteBuffer.wrap(bytes, bytes.length - Long.BYTES, Long.BYTES).getLong() != checksum.getValue()) { + throw new IOException("cache checksum does not match"); + } + DataInputStream input = new DataInputStream(new ByteArrayInputStream(bytes, 0, bytes.length - Long.BYTES)); + if (input.readInt() != MAGIC) { + throw new IOException("not a saved terrain status cache"); + } + int version = input.readInt(); + if (version != VERSION) { + throw new IOException("unsupported cache version " + version); + } + long scanSeconds = input.readLong(); + int regionCount = input.readInt(); + if (regionCount < 0) { + throw new IOException("invalid region count"); + } + Long2ObjectOpenHashMap regions = new Long2ObjectOpenHashMap<>(Math.min(regionCount, 65536)); + for (int index = 0; index < regionCount; index++) { + int x = input.readInt(); + int z = input.readInt(); + long size = input.readLong(); + String fileKey = input.readUTF(); + int count = input.readUnsignedShort(); + if (size < HEADER_BYTES || count > SLOTS) { + throw new IOException("invalid region entry"); + } + int[] slots = new int[count]; + int[] locations = new int[count]; + int[] timestamps = new int[count]; + BitSet terrain = new BitSet(count); + int previousSlot = -1; + for (int entry = 0; entry < count; entry++) { + int slot = input.readUnsignedShort(); + if (slot >= SLOTS || slot <= previousSlot) { + throw new IOException("invalid chunk slot"); + } + previousSlot = slot; + slots[entry] = slot; + locations[entry] = input.readInt(); + timestamps[entry] = input.readInt(); + terrain.set(entry, input.readBoolean()); + } + if (regions.put(ChunkGenerationOwnership.packChunk(x, z), + new Region(x, z, size, fileKey, slots, locations, timestamps, terrain)) != null) { + throw new IOException("duplicate region entry"); + } + } + if (input.available() != 0) { + throw new IOException("unexpected trailing data"); + } + return new Contents(scanSeconds, regions); + } + + final class Update { + private final int regionX; + private final int regionZ; + private final Header header; + private final int[] locations = new int[SLOTS]; + private final int[] timestamps = new int[SLOTS]; + private final BitSet known = new BitSet(SLOTS); + private final BitSet terrain = new BitSet(SLOTS); + + private Update(int regionX, int regionZ, Header header) { + this.regionX = regionX; + this.regionZ = regionZ; + this.header = header; + } + + /** + * Records a freshly decoded bit. Call only after the region was confirmed unchanged during decoding. + */ + void record(int slot, int location, int timestamp, boolean hasTerrain) { + if (reusable(location, timestamp, scanSeconds)) { + keep(slot, location, timestamp, hasTerrain); + } else { + known.clear(slot); + } + } + + void commit() { + int count = known.cardinality(); + int[] slots = new int[count]; + int[] storedLocations = new int[count]; + int[] storedTimestamps = new int[count]; + BitSet storedTerrain = new BitSet(count); + int entry = 0; + for (int slot = known.nextSetBit(0); slot >= 0; slot = known.nextSetBit(slot + 1)) { + slots[entry] = slot; + storedLocations[entry] = locations[slot]; + storedTimestamps[entry] = timestamps[slot]; + storedTerrain.set(entry, terrain.get(slot)); + entry++; + } + next.put(ChunkGenerationOwnership.packChunk(regionX, regionZ), new Region(regionX, regionZ, + header.size(), header.fileKey(), slots, storedLocations, storedTimestamps, storedTerrain)); + } + + private void keep(int slot, int location, int timestamp, boolean hasTerrain) { + locations[slot] = location; + timestamps[slot] = timestamp; + known.set(slot); + terrain.set(slot, hasTerrain); + } + } + + /** + * The 8 KiB header of a region file together with the identity of the file it came from. + */ + record Header(String fileKey, long size, byte[] bytes) { + static final int BYTES = HEADER_BYTES; + + static Header read(Path file) throws IOException { + Path normalized = file.toAbsolutePath().normalize(); + BasicFileAttributes attributes = Files.readAttributes(normalized, BasicFileAttributes.class, + LinkOption.NOFOLLOW_LINKS); + if (!attributes.isRegularFile() || attributes.size() < HEADER_BYTES) { + throw new IOException("Saved chunk region header is unavailable: " + normalized); + } + byte[] bytes = new byte[HEADER_BYTES]; + try (FileChannel input = FileChannel.open(normalized, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) { + ByteBuffer buffer = ByteBuffer.wrap(bytes); + while (buffer.hasRemaining()) { + if (input.read(buffer) < 0) { + throw new IOException("Truncated saved chunk region: " + normalized); + } + } + } + Object key = attributes.fileKey(); + return new Header(key == null ? "" : key.toString(), attributes.size(), bytes); + } + + int location(int slot) { + return word(slot * Integer.BYTES); + } + + int timestamp(int slot) { + return word(4096 + slot * Integer.BYTES); + } + + boolean sameHeader(Header other) { + return fileKey.equals(other.fileKey) && Arrays.equals(bytes, other.bytes); + } + + private int word(int offset) { + return (bytes[offset] & 255) << 24 | (bytes[offset + 1] & 255) << 16 + | (bytes[offset + 2] & 255) << 8 | bytes[offset + 3] & 255; + } + } + + record Region(int x, int z, long size, String fileKey, int[] slots, int[] locations, int[] timestamps, + BitSet terrain) { + boolean matches(Header header) { + return fileKey.equals(header.fileKey()) && header.size() >= size; + } + } + + private record Contents(long scanSeconds, Long2ObjectOpenHashMap regions) { + static final Contents EMPTY = new Contents(0L, new Long2ObjectOpenHashMap<>()); + } +} diff --git a/core/src/test/java/art/arcane/iris/world/history/SavedTerrainRecoveryScanTest.java b/core/src/test/java/art/arcane/iris/world/history/SavedTerrainRecoveryScanTest.java index 58e1f2966..46ec07ebc 100644 --- a/core/src/test/java/art/arcane/iris/world/history/SavedTerrainRecoveryScanTest.java +++ b/core/src/test/java/art/arcane/iris/world/history/SavedTerrainRecoveryScanTest.java @@ -11,8 +11,10 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.RandomAccessFile; +import java.nio.ByteBuffer; import java.nio.file.Files; import java.nio.file.Path; +import java.util.zip.CRC32; import java.util.zip.DeflaterOutputStream; import java.util.zip.GZIPOutputStream; @@ -118,6 +120,215 @@ public final class SavedTerrainRecoveryScanTest { assertFalse(Files.exists(world.resolve("region"))); } + @Test + public void warmCacheReusesStatusWithoutDecodingUnchangedChunks() throws Exception { + for (int regionBytes : new int[]{8192, 4 * 1024 * 1024}) { + Path world = temporaryFolder.newFolder().toPath(); + Path cacheFile = world.resolve("iris").resolve(SavedTerrainStatusCache.FILE_NAME); + writeChunkGrid(world); + WorldChunkInventory inventory = WorldChunkInventory.scan(world); + WorldChunkInventory expected = uncachedScan(world, inventory); + assertSameChunks(inventory, expected, cachedScan(world, cacheFile, regionBytes, (x, z) -> false)); + assertTrue(Files.isRegularFile(cacheFile)); + corruptAll(world); + assertThrows(IOException.class, () -> uncachedScan(world, inventory)); + assertSameChunks(inventory, expected, cachedScan(world, cacheFile, regionBytes, (x, z) -> false)); + assertSameChunks(inventory, expected, cachedScan(world, cacheFile, regionBytes, (x, z) -> false)); + } + } + + @Test + public void ownershipIsAppliedOnEveryScanInsteadOfCached() throws Exception { + Path world = temporaryFolder.newFolder().toPath(); + Path cacheFile = world.resolve("iris").resolve(SavedTerrainStatusCache.FILE_NAME); + write(world, new Chunk(0, 0, 2, false, encode(0, 0, "minecraft:biomes")), OLD); + write(world, new Chunk(1, 0, 2, false, encode(1, 0, "minecraft:full")), OLD); + WorldChunkInventory inventory = WorldChunkInventory.scan(world); + WorldChunkInventory first = cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> x == 0); + assertEquals(2, first.size()); + WorldChunkInventory second = cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false); + assertEquals(1, second.size()); + assertTrue(second.contains(1, 0)); + corruptAll(world); + assertEquals(2, cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> x == 0).size()); + WorldChunkInventory third = cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false); + assertEquals(1, third.size()); + assertTrue(third.contains(1, 0)); + assertSameChunks(inventory, second, third); + } + + @Test + public void changedHeaderWordsAreDecodedAgain() throws Exception { + Path world = temporaryFolder.newFolder().toPath(); + Path cacheFile = world.resolve("iris").resolve(SavedTerrainStatusCache.FILE_NAME); + writeChunkGrid(world); + cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false); + write(world, new Chunk(2, 0, 2, false, encode(2, 0, "minecraft:biomes")), OLD); + WorldChunkInventory inventory = WorldChunkInventory.scan(world); + WorldChunkInventory rewritten = cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false); + assertSameChunks(inventory, uncachedScan(world, inventory), rewritten); + assertFalse(rewritten.contains(2, 0)); + + cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false); + setTimestamp(world, 3, 0, OLD + 1); + corrupt(world, 3, 0); + IOException failure = assertThrows(IOException.class, + () -> cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false)); + assertTrue(failure.getMessage().contains("3,0")); + } + + @Test + public void chunksSavedNearTheScanTimeAreDecodedAgain() throws Exception { + Path world = temporaryFolder.newFolder().toPath(); + Path cacheFile = world.resolve("iris").resolve(SavedTerrainStatusCache.FILE_NAME); + writeChunkGrid(world); + long now = System.currentTimeMillis() / 1000L; + setTimestamp(world, 4, 1, now); + setTimestamp(world, 5, 1, now + 30); + cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false); + corrupt(world, 4, 1); + assertTrue(assertThrows(IOException.class, + () -> cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false)).getMessage().contains("4,1")); + write(world, new Chunk(4, 1, 2, false, encode(4, 1, "minecraft:full")), OLD); + cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false); + corrupt(world, 5, 1); + assertTrue(assertThrows(IOException.class, + () -> cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false)).getMessage().contains("5,1")); + } + + @Test + public void externalPayloadsAreDecodedOnEveryScan() throws Exception { + Path world = temporaryFolder.newFolder().toPath(); + Path cacheFile = world.resolve("iris").resolve(SavedTerrainStatusCache.FILE_NAME); + writeChunkGrid(world); + write(world, new Chunk(6, 2, 2, false, encode(6, 2, "minecraft:full")), OLD); + write(world, new Chunk(7, 2, 2, true, encode(7, 2, "minecraft:full")), OLD); + for (int regionBytes : new int[]{8192, 4 * 1024 * 1024}) { + cachedScan(world, cacheFile, regionBytes, (x, z) -> false); + Path external = world.resolve("region").resolve("c.7.2.mcc"); + byte[] payload = Files.readAllBytes(external); + Files.write(external, new byte[]{1, 2, 3}); + assertTrue(assertThrows(IOException.class, + () -> cachedScan(world, cacheFile, regionBytes, (x, z) -> false)).getMessage().contains("7,2")); + Files.write(external, payload); + } + } + + @Test + public void unreadableCacheFallsBackToAFullScan() throws Exception { + Path world = temporaryFolder.newFolder().toPath(); + Path cacheFile = world.resolve("iris").resolve(SavedTerrainStatusCache.FILE_NAME); + writeChunkGrid(world); + WorldChunkInventory inventory = WorldChunkInventory.scan(world); + WorldChunkInventory expected = uncachedScan(world, inventory); + cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false); + byte[] valid = Files.readAllBytes(cacheFile); + + byte[] flipped = valid.clone(); + flipped[flipped.length / 2] ^= 1; + byte[] wrongVersion = valid.clone(); + wrongVersion[7] = 99; + CRC32 checksum = new CRC32(); + checksum.update(wrongVersion, 0, wrongVersion.length - Long.BYTES); + ByteBuffer.wrap(wrongVersion, wrongVersion.length - Long.BYTES, Long.BYTES).putLong(checksum.getValue()); + for (byte[] broken : new byte[][]{flipped, wrongVersion, new byte[]{1, 2, 3}, new byte[0]}) { + Files.write(cacheFile, broken); + assertSameChunks(inventory, expected, cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false)); + } + + Files.write(cacheFile, flipped); + corrupt(world, 1, 1); + assertThrows(IOException.class, () -> cachedScan(world, cacheFile, 4 * 1024 * 1024, (x, z) -> false)); + } + + @Test + public void staticStartupScanWritesTheCacheOnlyAfterSuccess() throws Exception { + Path world = temporaryFolder.newFolder().toPath(); + Path cacheFile = world.resolve("iris").resolve(SavedTerrainStatusCache.FILE_NAME); + writeChunkGrid(world); + corrupt(world, 1, 1); + assertThrows(IOException.class, () -> SavedTerrainRecoveryScan.scan(world, WorldChunkInventory.scan(world), + (x, z) -> false, cacheFile)); + assertFalse(Files.exists(cacheFile)); + write(world, new Chunk(1, 1, 2, false, encode(1, 1, "minecraft:full")), OLD); + WorldChunkInventory inventory = WorldChunkInventory.scan(world); + WorldChunkInventory expected = uncachedScan(world, inventory); + assertSameChunks(inventory, expected, SavedTerrainRecoveryScan.scan(world, inventory, (x, z) -> false, cacheFile)); + corruptAll(world); + assertSameChunks(inventory, expected, SavedTerrainRecoveryScan.scan(world, inventory, (x, z) -> false, cacheFile)); + } + + private static final long OLD = 1_700_000_000L; + + private static void writeChunkGrid(Path world) throws IOException { + for (int x = 0; x < 12; x++) { + for (int z = 0; z < 12; z++) { + write(world, new Chunk(x, z, 2, false, + encode(x, z, (x + z) % 3 == 0 ? "minecraft:biomes" : "minecraft:full")), OLD); + } + } + write(world, new Chunk(40, 3, 2, false, encode(40, 3, "minecraft:noise")), OLD); + } + + private static WorldChunkInventory uncachedScan(Path world, WorldChunkInventory inventory) throws IOException { + try (SavedTerrainChunkReader.StatusReader reader = new SavedTerrainChunkReader.StatusReader(world)) { + return inventory.filter((x, z) -> SavedTerrainChunk.hasTerrain(reader.readStatus(x, z))); + } + } + + private static WorldChunkInventory cachedScan(Path world, Path cacheFile, int regionBytes, + WorldChunkInventory.ChunkPredicate retained) throws IOException { + SavedTerrainStatusCache cache = SavedTerrainStatusCache.load(cacheFile, world); + WorldChunkInventory result; + try (SavedTerrainRecoveryScan scan = new SavedTerrainRecoveryScan(world, + new SavedTerrainRecoveryScan.Limits(2, regionBytes), cache)) { + result = scan.filter(WorldChunkInventory.scan(world), retained); + } + cache.save(); + return result; + } + + private static void assertSameChunks(WorldChunkInventory inventory, WorldChunkInventory expected, + WorldChunkInventory actual) throws IOException { + assertEquals(expected.size(), actual.size()); + inventory.forEach((x, z) -> assertEquals(expected.contains(x, z), actual.contains(x, z))); + } + + private static void corruptAll(Path world) throws IOException { + WorldChunkInventory.scan(world).forEach((x, z) -> corrupt(world, x, z)); + } + + private static void corrupt(Path world, int x, int z) throws IOException { + try (RandomAccessFile file = new RandomAccessFile(regionFile(world, x, z).toFile(), "rw")) { + file.seek(slot(x, z) * 4L); + int sector = file.readInt() >>> 8; + file.seek(sector * 4096L + 4); + int compression = file.readUnsignedByte(); + file.seek(sector * 4096L + 4); + file.writeByte((compression & 128) | 99); + } + } + + private static void setTimestamp(Path world, int x, int z, long seconds) throws IOException { + try (RandomAccessFile file = new RandomAccessFile(regionFile(world, x, z).toFile(), "rw")) { + file.seek(4096L + slot(x, z) * 4L); + file.writeInt((int) seconds); + } + } + + private static Path regionFile(Path world, int x, int z) { + return world.resolve("region").resolve("r." + Math.floorDiv(x, 32) + "." + Math.floorDiv(z, 32) + ".mca"); + } + + private static int slot(int x, int z) { + return Math.floorMod(z, 32) * 32 + Math.floorMod(x, 32); + } + + private static void write(Path world, Chunk chunk, long timestamp) throws IOException { + write(world, chunk); + setTimestamp(world, chunk.x(), chunk.z(), timestamp); + } + private static byte[] encode(int x, int z, String status) throws IOException { CompoundTag root = new CompoundTag(); root.putInt("xPos", x);