Give every stage its own random stream derived from the invocation seed and stage id

Stages no longer share one RandomGenerator. StageContext.random() is the
running stage's own stream: java.util.Random seeded with
mix(mix(invocationSeed) ^ fnv1a64(utf8(stageId))), mix being the
SplitMix64 finalizer. Adding, removing or reordering modules, or how much
other stages draw, no longer changes a stage's draws. A block stage keeps
one stream across the blocks of its pass.

The host passes a long invocation seed to PlacementRunner.place and
ChunkRunner.generate instead of a RandomGenerator on the inputs;
InvocationContext loses random(), so stages cannot reach a shared stream.
ObjectGenerationContext keeps its own random() for geometry generators.
StageRandom documents the derivation, and a test pins it to values
computed from the specification.
This commit is contained in:
piexel committed 2026-10-05 21:34:19 +02:00
1 parent 4cb718f706
commit 307e488d1a
17 files changed
+293 -34

No files matched your search

@@ -1,14 +1,13 @@
package com.volmit.generation;
import com.volmit.resource.PackResources;
import java.util.random.RandomGenerator;
/** Host-owned invocation inputs. RNG and views must not be retained or used by detached tasks.
* The host derives streams from world seed, stable feature/occurrence identity and position;
* module discovery order must not affect them. Keeping legacy random behavior is adapter work.
/** Host-owned invocation inputs. Views must not be retained or used by detached tasks.
*
* <p>There is no shared random stream. A stage draws from {@link com.volmit.stage.StageContext#random()},
* a stream of its own, and an object generator from {@link com.volmit.object.ObjectGenerationContext#random()}.
*/
public interface InvocationContext {
long worldSeed();
PackResources resources();
RandomGenerator random();
}
@@ -77,6 +77,6 @@ final class ChunkInvocation implements ChunkStageContext {
@Override
public RandomGenerator random() {
return inputs.random();
return stages.random();
}
}
@@ -18,8 +18,11 @@ public final class ChunkRunner {
}
}
public void generate(GenerationContext inputs, ConfiguredSettings settings) {
var chunk = new ChunkInvocation(new StageInvocation(graph, settings), inputs);
/** Runs one chunk. The host derives {@code invocationSeed} from the world seed and the chunk
* position; each stage draws from its own stream of that seed ({@link StageRandom}).
*/
public void generate(GenerationContext inputs, long invocationSeed, ConfiguredSettings settings) {
var chunk = new ChunkInvocation(new StageInvocation(graph, invocationSeed, settings), inputs);
for (int position = 0; position < graph.size(); position++) {
chunk.stages().runInvocationStage(position, chunk);
}
@@ -4,7 +4,8 @@ import com.volmit.stage.Stage;
/** Execution data of one resolved stage. Indices are positions in the resolved order.
* readableStages/readablePositions are the transitive requirements whose outputs it may read.
* settingsSlot indexes the graph's distinct settings types, or is NO_SETTINGS.
* settingsSlot indexes the graph's distinct settings types, or is NO_SETTINGS. idHash keys the
* stage's random stream ({@link StageRandom}), computed once per pack load.
*/
record ExecutableStage(
Stage<?> stage,
@@ -12,7 +13,8 @@ record ExecutableStage(
int[] requirements,
Stage<?>[] readableStages,
int[] readablePositions,
int settingsSlot) {
int settingsSlot,
long idHash) {
static final int NO_SETTINGS = -1;
static final int NOT_READABLE = -1;
@@ -224,7 +224,8 @@ final class GraphResolver {
readable[index].stream().mapToObj(readablePosition -> nodes.get(order[readablePosition]).stage())
.toArray(Stage<?>[]::new),
readable[index].stream().toArray(),
settingsSlot(declaration, settingsTypes));
settingsSlot(declaration, settingsTypes),
StageRandom.idHash(declaration.stage().id()));
stages.add(new ResolvedStage(declaration.stage(), declaration.module(), declaration.settings(),
incomingEdges(node, position), absentSoftTargets.get(node)));
}
@@ -118,7 +118,7 @@ final class PlacementInvocation implements BlockStageContext {
@Override
public RandomGenerator random() {
return inputs.random();
return stages.random();
}
@Override
@@ -22,17 +22,20 @@ public final class PlacementRunner {
}
/** Takes ownership of a fresh edit and closes it on success, rejection or exception.
* The host prepares the edit area, the read-only inputs (with a dedicated RNG) and the
* settings configured for this placement. Stages never receive commit/close rights.
* The host prepares the edit area, the read-only inputs and the settings configured for this
* placement, and derives {@code invocationSeed} from the world seed and the placement's stable
* identity. Each stage draws from its own stream of that seed ({@link StageRandom}). Stages never
* receive commit/close rights.
*/
public PlacementOutcome place(
PlacementRequest request,
PlacementEdit edit,
PlacementContext inputs,
long invocationSeed,
ConfiguredSettings settings) {
Objects.requireNonNull(edit, "edit");
try (edit) {
var stages = new StageInvocation(graph, settings);
var stages = new StageInvocation(graph, invocationSeed, settings);
var access = PlacementViews.restrict(edit, edit.bounds());
var placement = new PlacementInvocation(stages, request, inputs, access);
runSegments(placement);
@@ -5,13 +5,15 @@ import com.volmit.stage.BlockStageContext;
import com.volmit.stage.Stage;
import java.util.Arrays;
import java.util.Objects;
import java.util.random.RandomGenerator;
import java.util.stream.IntStream;
/** Pipeline-independent state of one invocation: activation, settings and stage outputs, all
* indexed by resolved position. Activation is computed once up front in resolved order: a stage
* is active when its settings are configured (or it has no condition) and every stage it
* requires is active, so inactivity cascades to dependents. Cost is one pass over stages and
* requirement edges plus one settings lookup per distinct settings type.
/** Pipeline-independent state of one invocation: activation, settings, stage outputs and stage
* random streams, all indexed by resolved position. Activation is computed once up front in resolved
* order: a stage is active when its settings are configured (or it has no condition) and every
* stage it requires is active, so inactivity cascades to dependents. Cost is one pass over stages
* and requirement edges plus one settings lookup per distinct settings type. A stage's stream is
* created when it first draws and depends only on the invocation seed and the stage id.
*/
final class StageInvocation {
private static final Object PENDING = new Object();
@@ -21,14 +23,18 @@ final class StageInvocation {
private final Object[] settingsBySlot;
private final boolean[] active;
private final Object[] outputs;
private final long invocationSeed;
private final RandomGenerator[] streams;
private int current = NO_STAGE;
StageInvocation(ResolvedGraph graph, ConfiguredSettings settings) {
StageInvocation(ResolvedGraph graph, long invocationSeed, ConfiguredSettings settings) {
this.graph = graph;
settingsBySlot = lookUpSettings(graph, Objects.requireNonNull(settings, "settings"));
active = activation(graph, settingsBySlot);
outputs = new Object[graph.size()];
Arrays.fill(outputs, PENDING);
this.invocationSeed = invocationSeed;
streams = new RandomGenerator[graph.size()];
}
boolean isActive(int position) {
@@ -90,6 +96,17 @@ final class StageInvocation {
return (O) outputs[position];
}
/** The running stage's own stream. A block stage keeps one stream across every block of its pass. */
RandomGenerator random() {
if (current == NO_STAGE) {
throw new IllegalStateException("A stage's random stream is only available while the stage runs");
}
if (streams[current] == null) {
streams[current] = StageRandom.stream(invocationSeed, graph.executable(current).idHash());
}
return streams[current];
}
private ExecutableStage currentStage() {
if (current == NO_STAGE) {
throw new IllegalStateException("Stage outputs can only be read while a stage runs");
@@ -0,0 +1,62 @@
package com.volmit.host;
import com.volmit.resource.ResourceId;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.random.RandomGenerator;
/** Derives the random stream of one stage in one invocation from the invocation seed and the
* stage id alone. A stage's draws therefore never depend on which other modules or stages are
* installed, their order, or how much they draw.
*
* <p>The derivation is fixed so the same seed gives the same world on every machine and JDK:
* <ol>
* <li>{@code idHash} = 64-bit FNV-1a of the UTF-8 bytes of the stage id ({@code namespace:path});</li>
* <li>{@code streamSeed} = {@code mix(mix(invocationSeed) ^ idHash)}, where {@code mix} is the
* SplitMix64 finalizer (Stafford variant 13);</li>
* <li>the stream is {@code new java.util.Random(streamSeed)}.</li>
* </ol>
* {@code mix} is a bijection, so one stage gets a different stream for every invocation seed, and
* within one invocation stages with different id hashes get different streams.
*
* <p>{@link java.util.Random} is the only JDK generator whose algorithm the Java SE specification
* fixes for {@code nextInt()}, {@code nextInt(bound)}, {@code nextLong()}, {@code nextBoolean()},
* {@code nextFloat()}, {@code nextDouble()}, {@code nextGaussian()} and {@code nextBytes}.
* {@code SplittableRandom} and the named {@code RandomGeneratorFactory} algorithms promise identical
* sequences only within one program. The ranged methods {@code Random} inherits from
* {@link RandomGenerator}, such as {@code nextInt(origin, bound)} or {@code nextDouble(bound)}, and
* {@code nextExponential()} are not fixed by the specification.
*/
public final class StageRandom {
private static final long FNV_OFFSET_BASIS = 0xcbf29ce484222325L;
private static final long FNV_PRIME = 0x100000001b3L;
private static final int BYTE_MASK = 0xff;
private StageRandom() {}
/** The stream {@code stageId} draws from in the invocation with {@code invocationSeed}. */
public static RandomGenerator stream(long invocationSeed, ResourceId stageId) {
return stream(invocationSeed, idHash(stageId));
}
static RandomGenerator stream(long invocationSeed, long idHash) {
return new Random(mix(mix(invocationSeed) ^ idHash));
}
/** 64-bit FNV-1a over the UTF-8 bytes of the id. */
static long idHash(ResourceId stageId) {
long hash = FNV_OFFSET_BASIS;
for (byte value : stageId.toString().getBytes(StandardCharsets.UTF_8)) {
hash ^= value & BYTE_MASK;
hash *= FNV_PRIME;
}
return hash;
}
/** SplitMix64's finalizer: a bijection on 64-bit values with full avalanche. */
private static long mix(long value) {
value = (value ^ (value >>> 30)) * 0xbf58476d1ce4e5b9L;
value = (value ^ (value >>> 27)) * 0x94d049bb133111ebL;
return value ^ (value >>> 31);
}
}
@@ -1,8 +1,12 @@
package com.volmit.object;
import com.volmit.generation.InvocationContext;
import java.util.random.RandomGenerator;
/** Geometry-only invocation. The host chooses the variant seed and enforces size limits.
* Placement and terrain adaptation happen later; generators return reusable local geometry.
*/
public interface ObjectGenerationContext extends InvocationContext {}
public interface ObjectGenerationContext extends InvocationContext {
/** This generation's stream, seeded from the variant seed the host chose. Do not retain it. */
RandomGenerator random();
}
@@ -5,7 +5,7 @@ import com.volmit.placement.PlacementContext;
import com.volmit.placement.PlacementRequest;
/** One placement attempt. Writes go to a buffered edit committed only if no stage rejects
* and none throws. All stages of an attempt share its inputs, including the RNG, in resolved order.
* and none throws. All stages of an attempt share its inputs; each draws from its own random stream.
*/
public interface PlacementStageContext extends PlacementContext, StageContext {
PlacementRequest request();
@@ -1,7 +1,16 @@
package com.volmit.stage;
import java.util.random.RandomGenerator;
/** Per-invocation view handed to one stage body. Do not retain it after the body returns. */
public interface StageContext {
/** This stage's own random stream in this invocation. It is derived from the invocation's seed
* and this stage's id only, so installing, removing or reordering other modules and stages, or
* how much they draw, never changes what this stage draws. A block stage has one stream per
* placement, drawn across the blocks of its pass in block order. Do not retain it.
*/
RandomGenerator random();
/** The output the given stage produced in this invocation. Only stages the current stage
* transitively requires are readable; anything else throws IllegalStateException, as does
* reading a block stage's accumulator before its block pass has finished.
@@ -37,7 +37,7 @@ class ChunkPipelineTest {
private static Hunk<BlockState> generate(ConfiguredSettings settings) {
var blocks = new ArrayHunk<>(BlockState.class, SIZE, HEIGHT, SIZE, AIR);
runner().generate(TestContexts.generation(Map.of(BlockState.class, blocks)), settings);
runner().generate(TestContexts.generation(Map.of(BlockState.class, blocks)), TestContexts.SEED, settings);
return blocks;
}
@@ -10,6 +10,7 @@ import com.volmit.host.LoadedModules;
import com.volmit.host.PlacementRunner;
import com.volmit.host.ResolvedGraph;
import com.volmit.host.StageGraphBuilder;
import com.volmit.host.StageRandom;
import com.volmit.mantle.BlockBox;
import com.volmit.object.GeneratedObject;
import com.volmit.object.ObjectBlock;
@@ -110,14 +111,16 @@ class PlacementLifecyclePortTest {
private static MemoryEdit place(ResolvedGraph graph, ConfiguredSettings settings) {
var terrain = terrain();
var edit = new MemoryEdit(terrain);
var outcome = new PlacementRunner(graph).place(request(), edit, TestContexts.placement(terrain), settings);
var outcome = new PlacementRunner(graph).place(request(), edit, TestContexts.placement(terrain), TestContexts.SEED, settings);
assertTrue(outcome.isPlaced());
return edit;
}
/** World position of a local block after the seeded rotation and surface anchoring. */
/** World position of a local block after the seeded rotation and surface anchoring. The rotation
* is the first draw of the transforms stage's own stream.
*/
private static BlockPosition placed(int x, int y, int z) {
var transforms = new Transforms(new Random(TestContexts.SEED).nextInt(4));
var transforms = new Transforms(StageRandom.stream(TestContexts.SEED, PrepareModule.TRANSFORMS.id()).nextInt(4));
var rotated = transforms.rotate(new BlockPosition(x, y, z), new BlockPosition(0, 0, 0));
return rotated.add(SURFACE_ANCHOR);
}
@@ -78,7 +78,7 @@ class StageGraphTest {
}
private static PlacementOutcome place(ResolvedGraph graph, MemoryEdit edit, ConfiguredSettings settings) {
return new PlacementRunner(graph).place(twoBlockRequest(), edit, TestContexts.placement(), settings);
return new PlacementRunner(graph).place(twoBlockRequest(), edit, TestContexts.placement(), TestContexts.SEED, settings);
}
@Test
@@ -0,0 +1,162 @@
package com.volmit.host;
import com.volmit.IrisModule;
import com.volmit.ModuleInfo;
import com.volmit.block.BlockState;
import com.volmit.mantle.BlockBox;
import com.volmit.object.GeneratedObject;
import com.volmit.object.ObjectBlock;
import com.volmit.placement.PlacementRequest;
import com.volmit.resource.ResourceId;
import com.volmit.stage.Pipeline;
import com.volmit.stage.Stage;
import com.volmit.stage.StageContext;
import com.volmit.stage.StageGraph;
import com.volmit.support.MemoryEdit;
import com.volmit.support.TestContexts;
import com.volmit.support.TestTerrain;
import com.volmit.world.BlockPosition;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.random.RandomGenerator;
import java.util.stream.IntStream;
import static org.junit.jupiter.api.Assertions.*;
class StageRandomTest {
private static final BlockState STONE = new BlockState("minecraft:stone");
private static final int BLOCKS = 3;
private static final int BOUND = 1_000_000;
private static final int INVOCATION_DRAWS = 4;
private static final int NOISY_DRAWS = 37;
/** Every draw each stage made, by stage id, in the order it made them. */
private final Map<String, List<Long>> draws = new LinkedHashMap<>();
private static IrisModule module(String id, Consumer<StageGraph> install) {
return new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of(id, "Test module " + id, "1"); }
public void install(StageGraph graph) { install.accept(graph); }
};
}
private static ResolvedGraph resolve(Pipeline pipeline, IrisModule... modules) {
var builder = new StageGraphBuilder();
for (var module : modules) builder.install(DiscoveredModule.builtIn(module));
return builder.resolve(pipeline);
}
private static PlacementRequest request() {
var blocks = IntStream.range(0, BLOCKS).mapToObj(x -> new ObjectBlock(new BlockPosition(x, 0, 0), STONE)).toList();
var object = new GeneratedObject(new BlockBox(0, 0, 0, BLOCKS, 1, 1), new BlockPosition(0, 0, 0), blocks, List.of());
return new PlacementRequest(ResourceId.parse("test:attempt"), object, new BlockPosition(0, 10, 0));
}
private Map<String, List<Long>> place(ResolvedGraph graph, long invocationSeed) {
draws.clear();
var outcome = new PlacementRunner(graph).place(request(), new MemoryEdit(new TestTerrain((x, z) -> 5)),
TestContexts.placement(), invocationSeed, ConfiguredSettings.none());
assertTrue(outcome.isPlaced());
return Map.copyOf(draws);
}
private void draw(String stage, StageContext context, int count) {
var drawn = draws.computeIfAbsent(stage, ignored -> new ArrayList<>());
for (int index = 0; index < count; index++) drawn.add((long) context.random().nextInt(BOUND));
}
/** One invocation stage and one block stage that draw from their streams. */
private IrisModule drawingModule(String moduleId, int invocationDraws, int drawsPerBlock) {
var pick = moduleId + "/pick";
var scatter = moduleId + "/scatter";
return module(moduleId, graph -> {
graph.define(Stage.placement(pick)).run(context -> draw(pick, context, invocationDraws));
graph.define(Stage.placementBlock(scatter)).run(context -> draw(scatter, context, drawsPerBlock));
});
}
private static List<Long> firstDraws(long invocationSeed, String stageId, int count) {
var stream = StageRandom.stream(invocationSeed, ResourceId.parse(stageId));
return IntStream.range(0, count).mapToObj(ignored -> (long) stream.nextInt(BOUND)).toList();
}
@Test
void insertingAModuleThatDrawsLeavesOtherStagesDrawsUnchanged() {
var first = drawingModule("a:mod", INVOCATION_DRAWS, 1);
var inserted = drawingModule("b:mod", NOISY_DRAWS, NOISY_DRAWS);
var last = drawingModule("c:mod", INVOCATION_DRAWS, 1);
var without = place(resolve(Pipeline.PLACEMENT, first, last), TestContexts.SEED);
var with = resolve(Pipeline.PLACEMENT, first, inserted, last);
assertEquals(List.of("a:mod/pick", "b:mod/pick", "c:mod/pick", "a:mod/scatter", "b:mod/scatter", "c:mod/scatter"),
with.stages().stream().map(stage -> stage.stage().id().toString()).toList());
assertEquals(1, with.blockPasses().size(), "the inserted block stage interleaves with the others per block");
var withInserted = place(with, TestContexts.SEED);
for (var stage : List.of("a:mod/pick", "a:mod/scatter", "c:mod/pick", "c:mod/scatter")) {
assertEquals(without.get(stage), withInserted.get(stage), stage);
}
}
@Test
void sameStageInTheSameInvocationDrawsTheSameSequenceEveryRun() {
var graph = resolve(Pipeline.PLACEMENT, drawingModule("a:mod", INVOCATION_DRAWS, 1));
assertEquals(place(graph, TestContexts.SEED), place(graph, TestContexts.SEED));
assertNotEquals(place(graph, TestContexts.SEED), place(graph, TestContexts.SEED + 1));
assertEquals(firstDraws(TestContexts.SEED, "a:mod/pick", INVOCATION_DRAWS), place(graph, TestContexts.SEED).get("a:mod/pick"));
}
@Test
void blockStageDrawsOneStreamAcrossTheBlocksOfItsPass() {
var graph = resolve(Pipeline.PLACEMENT, drawingModule("a:mod", 0, 2));
assertEquals(firstDraws(TestContexts.SEED, "a:mod/scatter", 2 * BLOCKS), place(graph, TestContexts.SEED).get("a:mod/scatter"));
}
@Test
void differentStagesDrawFromDifferentStreams() {
var graph = resolve(Pipeline.PLACEMENT, drawingModule("a:mod", INVOCATION_DRAWS, 0), drawingModule("c:mod", INVOCATION_DRAWS, 0));
var drawn = place(graph, TestContexts.SEED);
assertNotEquals(drawn.get("a:mod/pick"), drawn.get("c:mod/pick"));
assertNotEquals(StageRandom.idHash(ResourceId.parse("a:mod/pick")), StageRandom.idHash(ResourceId.parse("c:mod/pick")));
}
@Test
void chunkStagesDrawFromTheirOwnStreams() {
var drawn = new ArrayList<Long>();
var graph = resolve(Pipeline.CHUNK, module("a:mod", stages -> stages.define(Stage.chunk("a:mod/ores"))
.run(context -> drawn.add((long) context.random().nextInt(BOUND)))));
new ChunkRunner(graph).generate(TestContexts.generation(Map.of()), TestContexts.SEED, ConfiguredSettings.none());
assertEquals(firstDraws(TestContexts.SEED, "a:mod/ores", 1), drawn);
}
@Test
void streamIsOnlyAvailableWhileItsStageRuns() {
var retained = new ArrayList<StageContext>();
var graph = resolve(Pipeline.PLACEMENT, module("a:mod", stages -> stages.define(Stage.placement("a:mod/keep")).run(retained::add)));
place(graph, TestContexts.SEED);
assertThrows(IllegalStateException.class, () -> retained.getFirst().random());
}
/** Pins the documented derivation with values computed outside Java from its specification, so a
* change to the derivation or to the JDK's Random fails here instead of silently changing worlds.
*/
@Test
void derivationMatchesItsSpecification() {
var stage = ResourceId.parse("iris:stilt/fill");
assertEquals(0xd11cde74d6a9508aL, StageRandom.idHash(stage), "64-bit FNV-1a of iris:stilt/fill");
RandomGenerator stream = StageRandom.stream(TestContexts.SEED, stage);
assertEquals(4203081479670090427L, stream.nextLong());
assertEquals(-978353470, stream.nextInt());
assertEquals(943449, stream.nextInt(BOUND));
}
}
@@ -10,8 +10,6 @@ import com.volmit.resource.PackResources;
import com.volmit.world.TerrainSampler;
import com.volmit.world.BlockView;
import java.util.Map;
import java.util.Random;
import java.util.random.RandomGenerator;
/** Tests needing no platform facilities fail loudly if code starts using one. */
public final class TestContexts {
@@ -21,12 +19,10 @@ public final class TestContexts {
public static GenerationContext generation(Map<Class<?>, Hunk<?>> hunks) {
return new GenerationContext() {
private final RandomGenerator random = new Random(SEED);
public int originX() { return 0; }
public int originY() { return -64; }
public int originZ() { return 0; }
public long worldSeed() { return SEED; }
public RandomGenerator random() { return random; }
public PackResources resources() { throw new AssertionError("Unused resources"); }
public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); }
public FeatureSettings settings() { throw new AssertionError("Unused settings"); }
@@ -46,9 +42,7 @@ public final class TestContexts {
public static PlacementContext placement(BlockView blocks) {
return new PlacementContext() {
private final RandomGenerator random = new Random(SEED);
public long worldSeed() { return SEED; }
public RandomGenerator random() { return random; }
public PackResources resources() { throw new AssertionError("Unused resources"); }
public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); }
public FeatureSettings settings() { throw new AssertionError("Unused settings"); }