Link unchanged studio files by size and mtime

- Remember the source file sizes and modification times each studio activation was snapshotted from
- Skip the snapshot when the source still matches the record for the active epoch
- Link files whose size and modification time match the record instead of reading both copies
- Fall back to comparing content when no record exists for the active epoch
This commit is contained in:
piexel committed 2026-11-17 04:32:30 +01:00
1 parent 6ec3acdf64
commit 17d6f12a6b
9 files changed
+139 -29

No files matched your search

@@ -0,0 +1,16 @@
package art.arcane.iris.generation.runtime;
import art.arcane.iris.world.history.GenerationEpoch;
import art.arcane.iris.world.history.PackTreeState;
import java.util.Optional;
/**
* The Studio source state an activated epoch was snapshotted from. While that epoch is still active, source files
* whose size and modification time match it are known to equal the epoch's published files.
*/
record ActivatedStudioSource(String epochId, PackTreeState sourceState) {
Optional<PackTreeState> sourceStateOf(GenerationEpoch active) {
return active.epochId().equals(epochId) ? Optional.of(sourceState) : Optional.empty();
}
}
@@ -48,6 +48,7 @@ import static art.arcane.iris.generation.runtime.EngineShutdownSequence.runClean
final class EngineHotloader {
private final IrisEngine engine;
private final Object studioTransitionLock = new Object();
private ActivatedStudioSource activatedStudioSource;
EngineHotloader(IrisEngine engine) {
this.engine = engine;
@@ -231,7 +232,7 @@ final class EngineHotloader {
long startedAt = System.nanoTime();
engine.requireRunning("hotload the Studio pack");
GenerationHistory history = router.history();
update = StudioGenerationUpdate.prepare(engine, history);
update = StudioGenerationUpdate.prepare(engine, history, activatedStudioSource);
if (update == null) {
return;
}
@@ -284,7 +285,7 @@ final class EngineHotloader {
elapsedMillis(drainedAt, checkpointedAt), elapsedMillis(checkpointedAt, stagedAt),
elapsedMillis(stagedAt, promotedAt), elapsedMillis(promotedAt, completedAt));
broadcastStudioHotload(false, "");
auditActivatedPack(history, activated);
followUpActivation(history, update, activated);
} catch (Throwable failure) {
if (previous != null) {
synchronized (engine.lifecycleLock) {
@@ -335,12 +336,14 @@ final class EngineHotloader {
/**
* Never throws: it runs after the activation is durable, where any failure would mark the engine failed.
*/
private void auditActivatedPack(GenerationHistory history, GenerationActivation activated) {
private void followUpActivation(GenerationHistory history, StudioGenerationUpdate update,
GenerationActivation activated) {
try {
activatedStudioSource = update.activatedAs(activated.epochId());
new StudioPackAudit(engine, history, activated.epochId(), message -> broadcastStudioHotload(true, message))
.runInBackground();
} catch (Throwable auditFailure) {
IrisLogging.reportError("Failed to start Studio pack validation.", auditFailure);
} catch (Throwable followUpFailure) {
IrisLogging.reportError("Failed to follow up the Studio pack activation.", followUpFailure);
}
}
@@ -30,13 +30,25 @@ record StudioGenerationUpdate(
) implements AutoCloseable {
private static final String TRIAL_MANTLE_DIRECTORY = ".trial-mantle";
static StudioGenerationUpdate prepare(IrisEngine engine, GenerationHistory history) throws IOException {
/**
* @param previous the source the active epoch came from, when this engine activated it; without it every file
* is compared by content against the active epoch
* @return null when the source still matches the active epoch
*/
static StudioGenerationUpdate prepare(IrisEngine engine, GenerationHistory history,
ActivatedStudioSource previous) throws IOException {
Path source = engine.getStudioGenerationSource().toRealPath();
IrisData.invalidateLoadedAuthoringResources(source.toFile());
PackTreeState sourceState = PackTreeState.capture(source);
PackTreeState activeSourceState = previous == null ? null
: previous.sourceStateOf(history.activeEpoch()).orElse(null);
if (sourceState.equals(activeSourceState)) {
return null;
}
Path stagingRoot = Files.createTempDirectory(history.paths().generationRoot(), ".studio-");
try {
StudioGenerationUpdate update = prepareStaged(engine, history, source, sourceState, stagingRoot);
StudioGenerationUpdate update = prepareStaged(
engine, history, source, sourceState, activeSourceState, stagingRoot);
if (update == null) {
AtomicDirectoryPublisher.deleteTree(stagingRoot);
}
@@ -52,10 +64,11 @@ record StudioGenerationUpdate(
}
private static StudioGenerationUpdate prepareStaged(IrisEngine engine, GenerationHistory history, Path source,
PackTreeState sourceState, Path stagingRoot)
throws IOException {
PackTreeState sourceState, PackTreeState activeSourceState,
Path stagingRoot) throws IOException {
Path snapshot = stagingRoot.resolve(source.getFileName());
GenerationPackRepository.snapshotPackTree(source, snapshot, history.activePackLinkBasis().orElse(null));
GenerationPackRepository.snapshotPackTree(
source, snapshot, history.activePackLinkBasis().orElse(null), activeSourceState);
VerifiedPackTree pack = VerifiedPackTree.hash(snapshot);
if (isActive(history.activeEpoch(), pack)) {
return null;
@@ -125,6 +138,10 @@ record StudioGenerationUpdate(
return cause.getClass().getSimpleName() + ": " + cause.getMessage();
}
ActivatedStudioSource activatedAs(String epochId) {
return new ActivatedStudioSource(epochId, sourceState);
}
@Override
public void close() throws IOException {
AtomicDirectoryPublisher.deleteTree(stagingRoot);
@@ -125,7 +125,7 @@ public final class GenerationPackRepository {
Path stage = Files.createTempDirectory(epochDirectory, ".pack-");
try {
Files.delete(stage);
copyPackTree(source, stage, defaultExecutor(), defaultWorkers(), publicationCopyMode(), basisPack);
copyPackTree(source, stage, defaultExecutor(), defaultWorkers(), publicationCopyMode(), basisPack, null);
requireFingerprint(stage, packFingerprint, packFingerprintVersion);
return commitStage(epochId, stage, packFingerprint, packFingerprintVersion);
} finally {
@@ -306,17 +306,24 @@ public final class GenerationPackRepository {
/**
* Copies a pack without syncing it, for scratch copies that are not published as they are. Files identical to
* the optional {@code basisPack} are hard-linked to it, so the copy must be treated as read-only.
*
* @param basisSourceState the state the source had when {@code basisPack} was copied from it, or null. With it,
* a file whose size and modification time still match is linked without reading either
* copy; without it, files are compared by content
*/
public static void snapshotPackTree(Path source, Path target, Path basisPack) throws IOException {
copyPackTree(source, target, defaultExecutor(), defaultWorkers(), PackCopyMode.SCRATCH, basisPack);
public static void snapshotPackTree(Path source, Path target, Path basisPack, PackTreeState basisSourceState)
throws IOException {
copyPackTree(source, target, defaultExecutor(), defaultWorkers(), PackCopyMode.SCRATCH, basisPack,
basisSourceState);
}
static void copyPackTree(Path source, Path target, Executor executor, int workers) throws IOException {
copyPackTree(source, target, executor, workers, PackCopyMode.DURABLE, null);
copyPackTree(source, target, executor, workers, PackCopyMode.DURABLE, null, null);
}
static void copyPackTree(
Path source, Path target, Executor executor, int workers, PackCopyMode mode, Path basisPack
Path source, Path target, Executor executor, int workers, PackCopyMode mode, Path basisPack,
PackTreeState basisSourceState
) throws IOException {
Objects.requireNonNull(executor, "executor");
if (workers < 1 || workers > MAXIMUM_COPY_WORKERS) {
@@ -336,10 +343,14 @@ public final class GenerationPackRepository {
Files.createDirectories(copyDestination(normalizedSource, normalizedTarget, directory)));
List<Path> sourceFiles = sourceState.files().keySet().stream().map(normalizedSource::resolve).toList();
Path basis = basisPack == null ? null : basisPack.toAbsolutePath().normalize();
UnchangedFile unchanged = basisSourceState == null
? GenerationPackRepository::hasSameContent
: (relative, sourceFile, basisFile) -> basisSourceState.stamp(relative).equals(sourceState.stamp(relative));
Set<Path> unsyncedCopies = ConcurrentHashMap.newKeySet();
executeFilePhase(sourceFiles, executor, workers, sourceFile -> {
Path destination = copyDestination(normalizedSource, normalizedTarget, sourceFile);
if (basis != null && linkUnchangedFile(normalizedSource.relativize(sourceFile), sourceFile, basis, destination)) {
if (basis != null && linkUnchangedFile(
normalizedSource.relativize(sourceFile), sourceFile, basis, destination, unchanged)) {
return;
}
Files.copy(sourceFile, destination, StandardCopyOption.COPY_ATTRIBUTES);
@@ -408,14 +419,16 @@ public final class GenerationPackRepository {
return new PackTreeState(files);
}
private static boolean linkUnchangedFile(Path relative, Path sourceFile, Path basis, Path destination) {
private static boolean linkUnchangedFile(
Path relative, Path sourceFile, Path basis, Path destination, UnchangedFile unchanged
) {
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) {
|| !unchanged.test(relative, sourceFile, basisFile)) {
return false;
}
Files.createLink(destination, basisFile);
@@ -425,6 +438,10 @@ public final class GenerationPackRepository {
}
}
private static boolean hasSameContent(Path relative, Path sourceFile, Path basisFile) throws IOException {
return Files.mismatch(basisFile, sourceFile) == -1L;
}
private static Executor defaultExecutor() {
return IrisPlatforms.isBound() ? MultiBurst.ioBurst : ForkJoinPool.commonPool();
}
@@ -562,6 +579,11 @@ public final class GenerationPackRepository {
void run(Path file) throws IOException;
}
@FunctionalInterface
private interface UnchangedFile {
boolean test(Path relative, Path sourceFile, Path basisFile) throws IOException;
}
private record FileWork(List<Path> files, FileAction action, AtomicInteger next, AtomicBoolean failed) {
}
@@ -138,7 +138,7 @@ public class EngineHotloaderRecoveryTest {
try (MockedStatic<StudioGenerationUpdate> updates = mockStatic(StudioGenerationUpdate.class);
MockedStatic<IrisBoundarySignatureSampler> signatures = mockStatic(IrisBoundarySignatureSampler.class);
MockedStatic<IrisSettings> configuration = mockStatic(IrisSettings.class)) {
updates.when(() -> StudioGenerationUpdate.prepare(engine, history)).thenReturn(update);
updates.when(() -> StudioGenerationUpdate.prepare(engine, history, null)).thenReturn(update);
configuration.when(IrisSettings::get).thenReturn(settings);
IllegalStateException thrown = assertThrows(IllegalStateException.class,
@@ -5,6 +5,7 @@ import art.arcane.iris.configuration.IrisSettings;
import art.arcane.iris.structure.placement.IrisStructureLocator;
import art.arcane.iris.structure.placement.StructureReachability;
import art.arcane.iris.world.IrisWorld;
import art.arcane.iris.world.history.GenerationActivation;
import art.arcane.iris.world.history.GenerationHistory;
import art.arcane.iris.world.history.GenerationHistoryRuntimeRouter;
import art.arcane.iris.world.history.IrisBoundarySignatureSampler;
@@ -66,7 +67,7 @@ public class EngineHotloaderRetirementTest {
}
});
planning.get(5L, TimeUnit.SECONDS);
return null;
return mock(GenerationActivation.class);
}).when(cutover).promotePending();
StudioGenerationUpdate update = mock(StudioGenerationUpdate.class);
IrisSettings settings = mock(IrisSettings.class, RETURNS_DEEP_STUBS);
@@ -76,7 +77,7 @@ public class EngineHotloaderRetirementTest {
MockedStatic<IrisStructureLocator> structures = mockStatic(IrisStructureLocator.class);
MockedStatic<StructureReachability> reachability = mockStatic(StructureReachability.class);
MockedStatic<IrisSettings> configuration = mockStatic(IrisSettings.class)) {
updates.when(() -> StudioGenerationUpdate.prepare(engine, history)).thenReturn(update);
updates.when(() -> StudioGenerationUpdate.prepare(engine, history, null)).thenReturn(update);
configuration.when(IrisSettings::get).thenReturn(settings);
new EngineHotloader(engine).hotloadSilently();
@@ -8,6 +8,7 @@ import art.arcane.iris.world.history.GenerationEpochContractFactory;
import art.arcane.iris.world.history.GenerationHistory;
import art.arcane.iris.world.history.GenerationHistoryPaths;
import art.arcane.iris.world.history.GenerationPackFingerprint;
import art.arcane.iris.world.history.PackTreeState;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
@@ -60,6 +61,37 @@ public final class StudioGenerationUpdateTest {
assertThrows(IOException.class, () -> GenerationPackFingerprint.compute(alias, GenerationPackFingerprint.CURRENT_VERSION));
}
@Test
public void sourceMatchingTheActivatedRecordNeedsNoSnapshot() throws Exception {
Path source = temporary.newFolder("recorded-pack").toPath();
Files.createDirectories(source.resolve("dimensions"));
Files.writeString(source.resolve("dimensions/test.json"), "{}");
IrisEngine engine = mock(IrisEngine.class);
GenerationHistory history = mock(GenerationHistory.class);
GenerationEpoch active = mock(GenerationEpoch.class);
when(engine.getStudioGenerationSource()).thenReturn(source);
when(history.activeEpoch()).thenReturn(active);
when(active.epochId()).thenReturn("a".repeat(64));
ActivatedStudioSource recorded = new ActivatedStudioSource("a".repeat(64), PackTreeState.capture(source));
assertNull(StudioGenerationUpdate.prepare(engine, history, recorded));
verify(history).activeEpoch();
verifyNoMoreInteractions(history);
}
@Test
public void recordOfAnotherEpochIsIgnored() throws Exception {
Path source = temporary.newFolder("stale-record-pack").toPath();
Files.createDirectories(source.resolve("dimensions"));
Files.writeString(source.resolve("dimensions/test.json"), "{}");
GenerationEpoch active = mock(GenerationEpoch.class);
when(active.epochId()).thenReturn("a".repeat(64));
ActivatedStudioSource stale = new ActivatedStudioSource("b".repeat(64), PackTreeState.capture(source));
assertTrue(stale.sourceStateOf(active).isEmpty());
}
private void assertUnchangedSourceStagesNothing(Path authoringRoot, Path source) throws Exception {
String fingerprint = GenerationPackFingerprint.compute(source, GenerationPackFingerprint.CURRENT_VERSION);
GenerationHistoryPaths paths = GenerationHistoryPaths.forDimension(temporary.newFolder().toPath());
@@ -74,7 +106,7 @@ public final class StudioGenerationUpdateTest {
when(active.packFingerprintVersion()).thenReturn(GenerationPackFingerprint.CURRENT_VERSION);
when(active.packFingerprint()).thenReturn(fingerprint);
assertNull(StudioGenerationUpdate.prepare(engine, history));
assertNull(StudioGenerationUpdate.prepare(engine, history, null));
assertEquals("unchanged manifest", Files.readString(paths.manifest()));
try (Stream<Path> entries = Files.list(paths.generationRoot())) {
@@ -133,7 +165,7 @@ public final class StudioGenerationUpdateTest {
when(engine.getStudioGenerationSource()).thenReturn(alias);
GenerationHistory history = mock(GenerationHistory.class);
IOException failure = assertThrows(IOException.class, () -> StudioGenerationUpdate.prepare(engine, history));
IOException failure = assertThrows(IOException.class, () -> StudioGenerationUpdate.prepare(engine, history, null));
assertTrue(failure.getMessage(), failure.getMessage().contains("Pack contains a symbolic link"));
verifyNoInteractions(history);
@@ -178,7 +210,7 @@ public final class StudioGenerationUpdateTest {
when(data.getDimensionLoader()).thenReturn(dimensions);
try (MockedStatic<IrisData> loaders = mockStatic(IrisData.class)) {
loaders.when(() -> IrisData.openRuntime(any(File.class))).thenReturn(data);
return assertThrows(IOException.class, () -> StudioGenerationUpdate.prepare(engine, history));
return assertThrows(IOException.class, () -> StudioGenerationUpdate.prepare(engine, history, null));
}
}
@@ -89,7 +89,7 @@ public class GenerationHistoryTest extends GenerationHistorySupport {
GenerationHistory history = GenerationHistory.create(world, packA, fingerprint(packA), 42L, contract(),
GenerationRegistryContract.empty(), EpochPolicy.STUDIO);
Path tree = history.paths().generationRoot().resolve(".studio-test");
GenerationPackRepository.snapshotPackTree(packB, tree, history.activePackLinkBasis().orElseThrow());
GenerationPackRepository.snapshotPackTree(packB, tree, history.activePackLinkBasis().orElseThrow(), null);
VerifiedPackTree verified = VerifiedPackTree.hash(tree);
AtomicInteger hashes = new AtomicInteger();
try (MockedStatic<GenerationPackFingerprint> ignored = mockStatic(GenerationPackFingerprint.class, invocation -> {
@@ -117,7 +117,7 @@ public class GenerationPackRepositoryTest {
Path source = createPack("snapshot-source", "{}");
Path snapshot = temporaryFolder.getRoot().toPath().resolve("snapshot");
GenerationPackRepository.snapshotPackTree(source, snapshot, null);
GenerationPackRepository.snapshotPackTree(source, snapshot, null, null);
assertEquals(fingerprint(source), fingerprint(snapshot));
assertFalse(Files.isSameFile(source.resolve("dimensions/main.json"), snapshot.resolve("dimensions/main.json")));
@@ -134,13 +134,32 @@ public class GenerationPackRepositoryTest {
Files.writeString(source.resolve("biomes.json"), "{\"name\":\"plains\"}");
Path snapshot = temporaryFolder.getRoot().toPath().resolve("basis-snapshot");
GenerationPackRepository.snapshotPackTree(source, snapshot, basis);
GenerationPackRepository.snapshotPackTree(source, snapshot, basis, null);
assertTrue(Files.isSameFile(basis.resolve("biomes.json"), snapshot.resolve("biomes.json")));
assertFalse(Files.isSameFile(basis.resolve("dimensions/main.json"), snapshot.resolve("dimensions/main.json")));
assertEquals(fingerprint(source), fingerprint(snapshot));
}
@Test
public void recordedSourceStateLinksFilesByStampWithoutComparingContent() throws Exception {
Path dimensionRoot = temporaryFolder.newFolder("stamp-world").toPath();
Path source = createPack("stamp-source", "{}");
Files.writeString(source.resolve("biomes.json"), "{\"name\":\"plains\"}");
GenerationPackRepository repository = new GenerationPackRepository(dimensionRoot, EpochPolicy.STUDIO);
Path basis = repository.publish(digest('1'), fingerprint(source), GenerationPackFingerprint.CURRENT_VERSION, source);
PackTreeState recorded = PackTreeState.capture(source);
Files.writeString(basis.resolve("biomes.json"), "{\"name\":\"desert\"}");
Files.writeString(source.resolve("dimensions/main.json"), "{\"changed\":true}");
Path snapshot = temporaryFolder.getRoot().toPath().resolve("stamp-snapshot");
GenerationPackRepository.snapshotPackTree(source, snapshot, basis, recorded);
assertTrue(Files.isSameFile(basis.resolve("biomes.json"), snapshot.resolve("biomes.json")));
assertFalse(Files.isSameFile(basis.resolve("dimensions/main.json"), snapshot.resolve("dimensions/main.json")));
assertEquals("{\"changed\":true}", Files.readString(snapshot.resolve("dimensions/main.json")));
}
@Test
public void packTreeStateNoticesRewrittenAddedAndIgnoredFiles() throws Exception {
Path source = createPack("state-source", "{}");
@@ -162,7 +181,7 @@ public class GenerationPackRepositoryTest {
Path dimensionRoot = temporaryFolder.newFolder("adopt-world").toPath();
GenerationPackRepository repository = new GenerationPackRepository(dimensionRoot, EpochPolicy.STUDIO);
Path tree = Files.createDirectories(repository.generationRoot()).resolve("staged");
GenerationPackRepository.snapshotPackTree(createPack("adopt-source", "{}"), tree, null);
GenerationPackRepository.snapshotPackTree(createPack("adopt-source", "{}"), tree, null, null);
VerifiedPackTree verified = VerifiedPackTree.hash(tree);
AtomicInteger hashes = new AtomicInteger();
try (MockedStatic<GenerationPackFingerprint> ignored = countingHashes(hashes)) {
@@ -184,7 +203,7 @@ public class GenerationPackRepositoryTest {
temporaryFolder.newFolder("rehash-world").toPath(), EpochPolicy.DURABLE);
durable.publish(digest('a'), expected, GenerationPackFingerprint.CURRENT_VERSION, source);
Path tree = Files.createDirectories(durable.generationRoot()).resolve("staged");
GenerationPackRepository.snapshotPackTree(source, tree, null);
GenerationPackRepository.snapshotPackTree(source, tree, null, null);
AtomicInteger hashes = new AtomicInteger();
try (MockedStatic<GenerationPackFingerprint> ignored = countingHashes(hashes)) {
durable.requireExactPack(digest('a'), expected, GenerationPackFingerprint.CURRENT_VERSION);