Link unchanged files into new generation epochs

- Hard-link pack files that match the active epoch instead of copying and syncing them again
- Skip fsync for the discarded studio update snapshot
This commit is contained in:
piexel committed 2026-11-15 17:00:55 +01:00
1 parent ed037ea40b
commit 81293f2d4b
4 files changed
+126 -17

No files matched your search

@@ -37,7 +37,7 @@ record StudioGenerationUpdate(
Path stagingRoot = Files.createTempDirectory(history.paths().generationRoot(), ".studio-"); Path stagingRoot = Files.createTempDirectory(history.paths().generationRoot(), ".studio-");
Path snapshot = stagingRoot.resolve(source.getFileName()); Path snapshot = stagingRoot.resolve(source.getFileName());
try { try {
GenerationPackRepository.copyPackTree(source, snapshot); GenerationPackRepository.snapshotPackTree(source, snapshot);
if (!fingerprint.equals(GenerationPackFingerprint.compute(snapshot, GenerationPackFingerprint.CURRENT_VERSION))) { if (!fingerprint.equals(GenerationPackFingerprint.compute(snapshot, GenerationPackFingerprint.CURRENT_VERSION))) {
throw new IOException("Studio pack changed while its update snapshot was being captured."); throw new IOException("Studio pack changed while its update snapshot was being captured.");
} }
@@ -429,12 +429,21 @@ public final class GenerationHistory {
candidate.epochId(), candidate.epochId(),
candidate.packFingerprint(), candidate.packFingerprint(),
candidate.packFingerprintVersion(), candidate.packFingerprintVersion(),
packSource packSource,
activePackAsLinkBasis()
); );
forceEpochPublication(paths, candidate.epochId()); forceEpochPublication(paths, candidate.epochId());
return store.preparePendingActivation(candidate, transitionWidthBlocks); return store.preparePendingActivation(candidate, transitionWidthBlocks);
} }
private Path activePackAsLinkBasis() {
try {
return packs.requireSafePackRoot(store.activeEpoch().epochId());
} catch (IOException missingOrUnsafe) {
return null;
}
}
GenerationActivation promotePending( GenerationActivation promotePending(
Collection<TerrainBoundarySignature> signatures Collection<TerrainBoundarySignature> signatures
) throws IOException { ) throws IOException {
@@ -21,9 +21,11 @@ import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CancellationException; import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException; import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction; import java.util.concurrent.RecursiveAction;
@@ -61,11 +63,25 @@ public final class GenerationPackRepository {
return epochRoot(epochId).resolve("pack"); return epochRoot(epochId).resolve("pack");
} }
public synchronized Path publish( public Path publish(
String epochId, String epochId,
String packFingerprint, String packFingerprint,
int packFingerprintVersion, int packFingerprintVersion,
Path source Path source
) throws IOException {
return publish(epochId, packFingerprint, packFingerprintVersion, source, null);
}
/**
* Files identical to the published {@code basisPack} are hard-linked instead of copied. Published packs are
* immutable and were already synced, so only new or changed files pay for a copy and an fsync.
*/
public synchronized Path publish(
String epochId,
String packFingerprint,
int packFingerprintVersion,
Path source,
Path basisPack
) throws IOException { ) throws IOException {
String requiredEpochId = requireDigest(epochId, "epochId"); String requiredEpochId = requireDigest(epochId, "epochId");
String requiredFingerprint = requireDigest(packFingerprint, "packFingerprint"); String requiredFingerprint = requireDigest(packFingerprint, "packFingerprint");
@@ -75,7 +91,7 @@ public final class GenerationPackRepository {
".epoch-" + requiredEpochId + ".lock" ".epoch-" + requiredEpochId + ".lock"
)) { )) {
ensureEpochsRoot(); ensureEpochsRoot();
return publishLocked(requiredEpochId, requiredFingerprint, packFingerprintVersion, source); return publishLocked(requiredEpochId, requiredFingerprint, packFingerprintVersion, source, basisPack);
} }
} }
@@ -83,7 +99,8 @@ public final class GenerationPackRepository {
String epochId, String epochId,
String packFingerprint, String packFingerprint,
int packFingerprintVersion, int packFingerprintVersion,
Path source Path source,
Path basisPack
) throws IOException { ) throws IOException {
Path epochDirectory = ensureChildDirectory(epochsRoot, epochId); Path epochDirectory = ensureChildDirectory(epochsRoot, epochId);
Path target = epochDirectory.resolve("pack"); Path target = epochDirectory.resolve("pack");
@@ -94,7 +111,7 @@ public final class GenerationPackRepository {
Path stage = Files.createTempDirectory(epochDirectory, ".pack-"); Path stage = Files.createTempDirectory(epochDirectory, ".pack-");
try { try {
Files.delete(stage); Files.delete(stage);
copyPackTree(source, stage); copyPackTree(source, stage, defaultExecutor(), defaultWorkers(), PackCopyMode.DURABLE, basisPack);
requireFingerprint(stage, packFingerprint, packFingerprintVersion); requireFingerprint(stage, packFingerprint, packFingerprintVersion);
try (AtomicDirectoryPublisher.Publication publication = try (AtomicDirectoryPublisher.Publication publication =
AtomicDirectoryPublisher.publishAbsent(stage, target)) { AtomicDirectoryPublisher.publishAbsent(stage, target)) {
@@ -202,12 +219,23 @@ public final class GenerationPackRepository {
} }
public static void copyPackTree(Path source, Path target) throws IOException { public static void copyPackTree(Path source, Path target) throws IOException {
Executor executor = IrisPlatforms.isBound() ? MultiBurst.ioBurst : ForkJoinPool.commonPool(); copyPackTree(source, target, defaultExecutor(), defaultWorkers());
int workers = Math.max(1, Math.min(MAXIMUM_COPY_WORKERS, Runtime.getRuntime().availableProcessors())); }
copyPackTree(source, target, executor, workers);
/**
* Copies a pack without syncing it, for scratch copies that are discarded and never published.
*/
public static void snapshotPackTree(Path source, Path target) throws IOException {
copyPackTree(source, target, defaultExecutor(), defaultWorkers(), PackCopyMode.SCRATCH, null);
} }
static void copyPackTree(Path source, Path target, Executor executor, int workers) throws IOException { static void copyPackTree(Path source, Path target, Executor executor, int workers) throws IOException {
copyPackTree(source, target, executor, workers, PackCopyMode.DURABLE, null);
}
static void copyPackTree(
Path source, Path target, Executor executor, int workers, PackCopyMode mode, Path basisPack
) throws IOException {
Objects.requireNonNull(executor, "executor"); Objects.requireNonNull(executor, "executor");
if (workers < 1 || workers > MAXIMUM_COPY_WORKERS) { if (workers < 1 || workers > MAXIMUM_COPY_WORKERS) {
throw new IllegalArgumentException("Pack copy workers must be between 1 and " + MAXIMUM_COPY_WORKERS + "."); throw new IllegalArgumentException("Pack copy workers must be between 1 and " + MAXIMUM_COPY_WORKERS + ".");
@@ -268,17 +296,49 @@ public final class GenerationPackRepository {
throw new IOException("Unable to copy pack entry: " + file, failure); throw new IOException("Unable to copy pack entry: " + file, failure);
} }
}); });
executeFilePhase(sourceFiles, executor, workers, sourceFile -> Path basis = basisPack == null ? null : basisPack.toAbsolutePath().normalize();
Files.copy(sourceFile, copyDestination(normalizedSource, normalizedTarget, sourceFile), Set<Path> unsyncedCopies = ConcurrentHashMap.newKeySet();
StandardCopyOption.COPY_ATTRIBUTES)); executeFilePhase(sourceFiles, executor, workers, sourceFile -> {
executeFilePhase(sourceFiles, executor, workers, sourceFile -> Path destination = copyDestination(normalizedSource, normalizedTarget, sourceFile);
forceFile(copyDestination(normalizedSource, normalizedTarget, sourceFile))); if (basis != null && linkUnchangedFile(normalizedSource.relativize(sourceFile), sourceFile, basis, destination)) {
return;
}
Files.copy(sourceFile, destination, StandardCopyOption.COPY_ATTRIBUTES);
unsyncedCopies.add(destination);
});
if (mode == PackCopyMode.SCRATCH) {
return;
}
executeFilePhase(List.copyOf(unsyncedCopies), executor, workers, GenerationPackRepository::forceFile);
}
private static boolean linkUnchangedFile(Path relative, Path sourceFile, Path basis, Path destination) {
Path basisFile = basis.resolve(relative).normalize();
if (!basisFile.startsWith(basis)) {
return false;
}
try {
if (!Files.isRegularFile(basisFile, LinkOption.NOFOLLOW_LINKS)
|| Files.mismatch(basisFile, sourceFile) != -1L) {
return false;
}
Files.createLink(destination, basisFile);
return true;
} catch (IOException | UnsupportedOperationException | SecurityException unsupported) {
return false;
}
}
private static Executor defaultExecutor() {
return IrisPlatforms.isBound() ? MultiBurst.ioBurst : ForkJoinPool.commonPool();
}
private static int defaultWorkers() {
return Math.max(1, Math.min(MAXIMUM_COPY_WORKERS, Runtime.getRuntime().availableProcessors()));
} }
static void forceDirectoryTree(Path root, FileAction force) throws IOException { static void forceDirectoryTree(Path root, FileAction force) throws IOException {
Executor executor = IrisPlatforms.isBound() ? MultiBurst.ioBurst : ForkJoinPool.commonPool(); forceDirectoryTree(root, defaultExecutor(), defaultWorkers(), force);
int workers = Math.max(1, Math.min(MAXIMUM_COPY_WORKERS, Runtime.getRuntime().availableProcessors()));
forceDirectoryTree(root, executor, workers, force);
} }
static void forceDirectoryTree(Path root, Executor executor, int workers, FileAction force) throws IOException { static void forceDirectoryTree(Path root, Executor executor, int workers, FileAction force) throws IOException {
@@ -396,6 +456,11 @@ public final class GenerationPackRepository {
return requiredValue; return requiredValue;
} }
enum PackCopyMode {
DURABLE,
SCRATCH
}
@FunctionalInterface @FunctionalInterface
interface FileAction { interface FileAction {
void run(Path file) throws IOException; void run(Path file) throws IOException;
@@ -49,6 +49,41 @@ public class GenerationPackRepositoryTest {
)); ));
} }
@Test
public void publishLinksUnchangedFilesFromTheBasisPackAndCopiesChangedOnes() throws Exception {
Path dimensionRoot = temporaryFolder.newFolder("basis-world").toPath();
Path first = createPack("basis-first", "{}");
Files.createDirectories(first.resolve("biomes"));
Files.writeString(first.resolve("biomes/plains.json"), "{\"name\":\"plains\"}");
GenerationPackRepository repository = new GenerationPackRepository(dimensionRoot);
Path basis = repository.publish(digest('1'), fingerprint(first), GenerationPackFingerprint.CURRENT_VERSION, first);
Path second = createPack("basis-second", "{\"changed\":true}");
Files.createDirectories(second.resolve("biomes"));
Files.writeString(second.resolve("biomes/plains.json"), "{\"name\":\"plains\"}");
Files.writeString(second.resolve("biomes/desert.json"), "{\"name\":\"desert\"}");
Path published = repository.publish(
digest('2'), fingerprint(second), GenerationPackFingerprint.CURRENT_VERSION, second, basis);
assertTrue(Files.isSameFile(basis.resolve("biomes/plains.json"), published.resolve("biomes/plains.json")));
assertFalse(Files.isSameFile(basis.resolve("dimensions/main.json"), published.resolve("dimensions/main.json")));
assertEquals("{\"changed\":true}", Files.readString(published.resolve("dimensions/main.json")));
assertEquals("{}", Files.readString(basis.resolve("dimensions/main.json")));
assertEquals("{\"name\":\"desert\"}", Files.readString(published.resolve("biomes/desert.json")));
assertEquals(fingerprint(second), fingerprint(published));
}
@Test
public void scratchSnapshotCopiesThePackWithoutLinkingTheSource() throws Exception {
Path source = createPack("snapshot-source", "{}");
Path snapshot = temporaryFolder.getRoot().toPath().resolve("snapshot");
GenerationPackRepository.snapshotPackTree(source, snapshot);
assertEquals(fingerprint(source), fingerprint(snapshot));
assertFalse(Files.isSameFile(source.resolve("dimensions/main.json"), snapshot.resolve("dimensions/main.json")));
}
@Test @Test
public void rejectsMutationOfAnExistingEpoch() throws Exception { public void rejectsMutationOfAnExistingEpoch() throws Exception {
Path dimensionRoot = temporaryFolder.newFolder("mutation-world").toPath(); Path dimensionRoot = temporaryFolder.newFolder("mutation-world").toPath();