Share pack work across studio hotload steps

- Gate studio pack content through the data the trial runtime builds from instead of a second full load
- Skip the registry capture's pack re-hash when the caller already verified the fingerprint
- Skip boundary store fsyncs for histories whose policy does not sync
This commit is contained in:
piexel committed 2026-11-25 10:16:30 +01:00
1 parent 22c8e68007
commit 3aa302e56c
6 files changed
+70 -32

No files matched your search

@@ -92,10 +92,10 @@ record StudioGenerationUpdate(
Path stagingRoot, VerifiedPackTree pack, Path stagingRoot, VerifiedPackTree pack,
PackTreeState sourceState) throws IOException { PackTreeState sourceState) throws IOException {
GenerationEpoch active = history.activeEpoch(); GenerationEpoch active = history.activeEpoch();
requireLoadable(pack);
IrisData data = IrisData.openRuntime(pack.root().toFile()); IrisData data = IrisData.openRuntime(pack.root().toFile());
try { try {
data.useVerifiedGenerationPackFingerprint(pack.fingerprint()); data.useVerifiedGenerationPackFingerprint(pack.fingerprint());
requireLoadable(pack, data);
IrisDimension replacement = data.getDimensionLoader().load(active.dimensionContract().dimensionKey()); IrisDimension replacement = data.getDimensionLoader().load(active.dimensionContract().dimensionKey());
if (replacement == null) { if (replacement == null) {
throw new IOException("Studio pack update is missing dimension '" throw new IOException("Studio pack update is missing dimension '"
@@ -123,8 +123,8 @@ record StudioGenerationUpdate(
} }
} }
private static void requireLoadable(VerifiedPackTree pack) throws IOException { private static void requireLoadable(VerifiedPackTree pack, IrisData data) throws IOException {
PackValidationResult validation = PackValidator.validate(pack.root().toFile()); PackValidationResult validation = PackValidator.validate(pack.root().toFile(), data);
if (!validation.isLoadable()) { if (!validation.isLoadable()) {
throw new IOException("Studio pack update is invalid: " + String.join("; ", validation.getBlockingErrors())); throw new IOException("Studio pack update is invalid: " + String.join("; ", validation.getBlockingErrors()));
} }
@@ -77,15 +77,23 @@ public final class PackValidator {
} }
public static PackValidationResult validate(File packFolder) { public static PackValidationResult validate(File packFolder) {
return validate(packFolder, true); return validate(packFolder, true, null);
}
/**
* Gates content through {@code loadedPack} instead of a detached loader, so a caller that goes on to build a
* runtime from the same data does not load the pack a second time. The data stays open.
*/
public static PackValidationResult validate(File packFolder, IrisData loadedPack) {
return validate(packFolder, true, Objects.requireNonNull(loadedPack, "loadedPack"));
} }
public static PackValidationResult validateForDatapackBootstrap(File packFolder) { public static PackValidationResult validateForDatapackBootstrap(File packFolder) {
return validate(packFolder, false); return validate(packFolder, false, null);
} }
public static PackValidationResult validateForPackaging(File packFolder) { public static PackValidationResult validateForPackaging(File packFolder) {
return validate(packFolder, false); return validate(packFolder, false, null);
} }
public static void requireValidObjectSettings(File packFolder, String dimensionKey, JSONObject dimension) { public static void requireValidObjectSettings(File packFolder, String dimensionKey, JSONObject dimension) {
@@ -97,11 +105,13 @@ public final class PackValidator {
} }
} }
private static PackValidationResult validate(File packFolder, boolean validateLiveRegistries) { private static PackValidationResult validate(File packFolder, boolean validateLiveRegistries,
return PackValidationIo.withinValidationRun(() -> validateWithinRun(packFolder, validateLiveRegistries)); IrisData loadedPack) {
return PackValidationIo.withinValidationRun(() -> validateWithinRun(packFolder, validateLiveRegistries, loadedPack));
} }
private static PackValidationResult validateWithinRun(File packFolder, boolean validateLiveRegistries) { private static PackValidationResult validateWithinRun(File packFolder, boolean validateLiveRegistries,
IrisData loadedPack) {
String packName = packFolder == null ? "<unknown>" : packFolder.getName(); String packName = packFolder == null ? "<unknown>" : packFolder.getName();
List<String> blockingErrors = new ArrayList<>(); List<String> blockingErrors = new ArrayList<>();
List<String> warnings = new ArrayList<>(); List<String> warnings = new ArrayList<>();
@@ -174,7 +184,7 @@ public final class PackValidator {
? IrisPlatforms.get().minecraftVersion() ? IrisPlatforms.get().minecraftVersion()
: null; : null;
List<CompatFinding> compatFindings = validateLiveRegistries List<CompatFinding> compatFindings = validateLiveRegistries
? gateContent(packFolder, dimensionFiles, minecraftVersion, blockingErrors, warnings) ? gateContent(packFolder, dimensionFiles, minecraftVersion, blockingErrors, warnings, loadedPack)
: List.of(); : List.of();
// Keys the version gate already names in its own line are not repeated as unknown-key findings. // Keys the version gate already names in its own line are not repeated as unknown-key findings.
@@ -197,14 +207,15 @@ public final class PackValidator {
File[] dimensionFiles, File[] dimensionFiles,
String minecraftVersion, String minecraftVersion,
List<String> blockingErrors, List<String> blockingErrors,
List<String> warnings List<String> warnings,
IrisData loadedPack
) { ) {
if (!IrisPlatforms.isBound()) { if (!IrisPlatforms.isBound()) {
return List.of(); return List.of();
} }
IrisData data = null; IrisData data = null;
try { try {
data = IrisData.openRuntime(packFolder); data = loadedPack == null ? IrisData.openRuntime(packFolder) : loadedPack;
if (!data.getContentGate().ready()) { if (!data.getContentGate().ready()) {
return List.of(); return List.of();
} }
@@ -218,7 +229,7 @@ public final class PackValidator {
+ ": " + Objects.requireNonNullElse(e.getMessage(), "No failure detail.")); + ": " + Objects.requireNonNullElse(e.getMessage(), "No failure detail."));
return List.of(); return List.of();
} finally { } finally {
if (data != null) { if (data != null && data != loadedPack) {
try { try {
data.close(); data.close();
} catch (Throwable closeFailure) { } catch (Throwable closeFailure) {
@@ -156,6 +156,10 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
@Getter(AccessLevel.NONE) @Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE) @Setter(AccessLevel.NONE)
@EqualsAndHashCode.Exclude @EqualsAndHashCode.Exclude
private transient volatile boolean generationPackFingerprintVerifiedByCaller;
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
@EqualsAndHashCode.Exclude
private transient volatile GenerationRegistryContract generationRegistryContract; private transient volatile GenerationRegistryContract generationRegistryContract;
@Getter(AccessLevel.NONE) @Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE) @Setter(AccessLevel.NONE)
@@ -232,6 +236,7 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
dump(); dump();
clearLists(); clearLists();
generationPackFingerprint = null; generationPackFingerprint = null;
generationPackFingerprintVerifiedByCaller = false;
contentGate = null; contentGate = null;
dimensionCustomBiomeResourceKeys.clear(); dimensionCustomBiomeResourceKeys.clear();
} }
@@ -341,6 +346,11 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
throw new IllegalStateException("Iris data already has a different generation pack fingerprint."); throw new IllegalStateException("Iris data already has a different generation pack fingerprint.");
} }
generationPackFingerprint = required; generationPackFingerprint = required;
generationPackFingerprintVerifiedByCaller = true;
}
public boolean hasCallerVerifiedGenerationPackFingerprint() {
return generationPackFingerprintVerifiedByCaller;
} }
public boolean hasGenerationRegistryContract() { public boolean hasGenerationRegistryContract() {
@@ -710,6 +720,7 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
IrisObjectScale.invalidate(this); IrisObjectScale.invalidate(this);
contentGate = null; contentGate = null;
generationPackFingerprint = null; generationPackFingerprint = null;
generationPackFingerprintVerifiedByCaller = false;
synchronized (dimensionCustomBiomeResourceKeys) { synchronized (dimensionCustomBiomeResourceKeys) {
dimensionCustomBiomeResourceKeys.clear(); dimensionCustomBiomeResourceKeys.clear();
} }
@@ -63,8 +63,14 @@ public final class GenerationBoundaryStore {
private final Path dimensionRoot; private final Path dimensionRoot;
private final Path directory; private final Path directory;
private final EpochPolicy policy;
public GenerationBoundaryStore(Path dimensionRoot) { public GenerationBoundaryStore(Path dimensionRoot) {
this(dimensionRoot, EpochPolicy.DURABLE);
}
public GenerationBoundaryStore(Path dimensionRoot, EpochPolicy policy) {
this.policy = Objects.requireNonNull(policy, "policy");
Path root = Objects.requireNonNull(dimensionRoot, "Dimension root").toAbsolutePath().normalize(); Path root = Objects.requireNonNull(dimensionRoot, "Dimension root").toAbsolutePath().normalize();
this.dimensionRoot = root; this.dimensionRoot = root;
this.directory = root.resolve("iris").resolve("generation").resolve("boundaries").normalize(); this.directory = root.resolve("iris").resolve("generation").resolve("boundaries").normalize();
@@ -223,7 +229,7 @@ public final class GenerationBoundaryStore {
".activation-" + activationId + SNAPSHOT_FILE_SUFFIX + ".lock" ".activation-" + activationId + SNAPSHOT_FILE_SUFFIX + ".lock"
)) { )) {
ensureDirectory(); ensureDirectory();
PublishedCatalog catalog = builder.publish(directory, activationId); PublishedCatalog catalog = builder.publish(directory, activationId, policy);
Path target = snapshotPath(activationId); Path target = snapshotPath(activationId);
if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) { if (Files.exists(target, LinkOption.NOFOLLOW_LINKS)) {
GenerationBoundary existing = load(activationId); GenerationBoundary existing = load(activationId);
@@ -235,7 +241,7 @@ public final class GenerationBoundaryStore {
} }
return existing; return existing;
} }
publishAtomic(target, catalog.encoded(), "generation boundary catalog"); publishAtomic(target, catalog.encoded(), "generation boundary catalog", policy);
return load(activationId); return load(activationId);
} }
} }
@@ -263,7 +269,7 @@ public final class GenerationBoundaryStore {
requireSafeDirectory(directory); requireSafeDirectory(directory);
} }
private static Path ensureChildDirectory(Path parent, String name) throws IOException { private Path ensureChildDirectory(Path parent, String name) throws IOException {
Path child = parent.resolve(name); Path child = parent.resolve(name);
if (Files.exists(child, LinkOption.NOFOLLOW_LINKS)) { if (Files.exists(child, LinkOption.NOFOLLOW_LINKS)) {
requireSafeDirectory(child); requireSafeDirectory(child);
@@ -275,7 +281,7 @@ public final class GenerationBoundaryStore {
requireSafeDirectory(child); requireSafeDirectory(child);
return child; return child;
} }
forceDirectory(parent); forceDirectory(parent, policy);
return child; return child;
} }
@@ -356,7 +362,8 @@ public final class GenerationBoundaryStore {
return withChecksum(bodyBytes.toByteArray()); return withChecksum(bodyBytes.toByteArray());
} }
private static void publishAtomic(Path target, byte[] encoded, String kind) throws IOException { private static void publishAtomic(Path target, byte[] encoded, String kind, EpochPolicy policy)
throws IOException {
Path directory = target.getParent(); Path directory = target.getParent();
Path temporary = Files.createTempFile(directory, ".boundary-", ".tmp"); Path temporary = Files.createTempFile(directory, ".boundary-", ".tmp");
try { try {
@@ -366,14 +373,16 @@ public final class GenerationBoundaryStore {
StandardOpenOption.TRUNCATE_EXISTING StandardOpenOption.TRUNCATE_EXISTING
)) { )) {
writeFully(channel, ByteBuffer.wrap(encoded)); writeFully(channel, ByteBuffer.wrap(encoded));
channel.force(true); if (policy.syncs()) {
channel.force(true);
}
} }
try { try {
Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE); Files.move(temporary, target, StandardCopyOption.ATOMIC_MOVE);
} catch (AtomicMoveNotSupportedException error) { } catch (AtomicMoveNotSupportedException error) {
throw new IOException("Generation boundary " + kind + " publication requires an atomic move", error); throw new IOException("Generation boundary " + kind + " publication requires an atomic move", error);
} }
forceDirectory(directory); forceDirectory(directory, policy);
} finally { } finally {
Files.deleteIfExists(temporary); Files.deleteIfExists(temporary);
} }
@@ -482,8 +491,8 @@ public final class GenerationBoundaryStore {
} }
} }
private static void forceDirectory(Path path) throws IOException { private static void forceDirectory(Path path, EpochPolicy policy) throws IOException {
if (File.separatorChar == '\\') { if (!policy.syncs() || File.separatorChar == '\\') {
return; return;
} }
try (FileChannel channel = FileChannel.open(path, StandardOpenOption.READ)) { try (FileChannel channel = FileChannel.open(path, StandardOpenOption.READ)) {
@@ -520,7 +529,7 @@ public final class GenerationBoundaryStore {
} }
} }
private PublishedCatalog publish(Path directory, long activationId) throws IOException { private PublishedCatalog publish(Path directory, long activationId, EpochPolicy policy) throws IOException {
if (masks.size() > MAX_REGION_COUNT) { if (masks.size() > MAX_REGION_COUNT) {
throw new IOException("Generation boundary exceeds the maximum region count"); throw new IOException("Generation boundary exceeds the maximum region count");
} }
@@ -528,7 +537,7 @@ public final class GenerationBoundaryStore {
sortRegionKeys(regionKeys); sortRegionKeys(regionKeys);
Long2ObjectOpenHashMap<String> shardHashes = new Long2ObjectOpenHashMap<>(regionKeys.length); Long2ObjectOpenHashMap<String> shardHashes = new Long2ObjectOpenHashMap<>(regionKeys.length);
for (long regionKey : regionKeys) { for (long regionKey : regionKeys) {
String hash = MaskShard.publish(directory, masks.get(regionKey)); String hash = MaskShard.publish(directory, masks.get(regionKey), policy);
shardHashes.put(regionKey, hash); shardHashes.put(regionKey, hash);
} }
byte[] identity = computeIdentity(activationId, chunkCount, regionKeys, shardHashes); byte[] identity = computeIdentity(activationId, chunkCount, regionKeys, shardHashes);
@@ -545,7 +554,7 @@ public final class GenerationBoundaryStore {
} }
private static final class MaskShard { private static final class MaskShard {
private static String publish(Path directory, byte[] mask) throws IOException { private static String publish(Path directory, byte[] mask, EpochPolicy policy) throws IOException {
byte[] encoded = encode(mask); byte[] encoded = encode(mask);
String hash = sha256(encoded); String hash = sha256(encoded);
Path target = directory.resolve(maskFileName(hash)); Path target = directory.resolve(maskFileName(hash));
@@ -555,7 +564,7 @@ public final class GenerationBoundaryStore {
return hash; return hash;
} }
try { try {
publishAtomic(target, encoded, "mask shard"); publishAtomic(target, encoded, "mask shard", policy);
} catch (FileAlreadyExistsException race) { } catch (FileAlreadyExistsException race) {
requireRegularFile(target, "Generation boundary mask"); requireRegularFile(target, "Generation boundary mask");
read(target, hash); read(target, hash);
@@ -69,7 +69,7 @@ public final class GenerationHistory {
this.store = Objects.requireNonNull(store, "store"); this.store = Objects.requireNonNull(store, "store");
this.ownership = Objects.requireNonNull(ownership, "ownership"); this.ownership = Objects.requireNonNull(ownership, "ownership");
this.kernels = Objects.requireNonNull(kernels, "kernels"); this.kernels = Objects.requireNonNull(kernels, "kernels");
this.boundaries = new GenerationBoundaryStore(paths.dimensionRoot()); this.boundaries = new GenerationBoundaryStore(paths.dimensionRoot(), this.packs.policy());
this.terrainSignatures = new TerrainBoundarySignatureStore(paths.dimensionRoot()); this.terrainSignatures = new TerrainBoundarySignatureStore(paths.dimensionRoot());
this.semantics = GenerationSemanticIndex.loadRequired(paths.dimensionRoot(), unpublished); this.semantics = GenerationSemanticIndex.loadRequired(paths.dimensionRoot(), unpublished);
this.savedBiomes = SavedBiomeStore.open(paths.dimensionRoot(), unpublished); this.savedBiomes = SavedBiomeStore.open(paths.dimensionRoot(), unpublished);
@@ -260,16 +260,23 @@ public final class GenerationRegistryContractFactory {
addPlatformDefinitions(definitions, BLOCK_REGISTRY, referenced.blockKeys(), requiredGenerationRegistry); addPlatformDefinitions(definitions, BLOCK_REGISTRY, referenced.blockKeys(), requiredGenerationRegistry);
addPlatformDefinitions(definitions, ENTITY_TYPE_REGISTRY, referenced.entityKeys(), requiredGenerationRegistry); addPlatformDefinitions(definitions, ENTITY_TYPE_REGISTRY, referenced.entityKeys(), requiredGenerationRegistry);
GenerationRegistryContract captured = contract(definitions, generatedSources, requiredGenerationRegistry).withBiomeTags(biomeTags); GenerationRegistryContract captured = contract(definitions, generatedSources, requiredGenerationRegistry).withBiomeTags(biomeTags);
String actualPackFingerprint = GenerationPackFingerprint.compute( if (!requiredPackFingerprint.equals(packFingerprintAfterCapture(requiredData, packRoot))) {
packRoot,
GenerationPackFingerprint.CURRENT_VERSION
);
if (!requiredPackFingerprint.equals(actualPackFingerprint)) {
throw new IOException("Iris generation registry capture rejected a changed pack."); throw new IOException("Iris generation registry capture rejected a changed pack.");
} }
return captured; return captured;
} }
/**
* A pack whose fingerprint the caller verified is immutable for the lifetime of its data, so it is not hashed
* again to detect edits made during the capture.
*/
private static String packFingerprintAfterCapture(IrisData data, Path packRoot) throws IOException {
if (data.hasCallerVerifiedGenerationPackFingerprint()) {
return data.generationPackFingerprint();
}
return GenerationPackFingerprint.compute(packRoot, GenerationPackFingerprint.CURRENT_VERSION);
}
public static CustomBiomeDefinition customBiomeDefinition( public static CustomBiomeDefinition customBiomeDefinition(
IrisData data, IrisData data,
IrisDimension dimension, IrisDimension dimension,