Merge pull request #6 from ludovic111/distant-queue-wait

Avoid continuous retries during distant-terrain update debounce
This commit is contained in:
Ludovic Marie
2026-10-03 22:41:19 +02:00
committed by GitHub
20 changed files with 352 additions and 9 deletions
+3
View File
@@ -46,6 +46,8 @@ jobs:
run: python tools/build_pack.py
- name: Measure isolated worker pacing on this platform
run: python -c "from tools.build_mod import benchmark_workers; benchmark_workers()"
- name: Measure isolated debounce queue polling
run: python -c "from tools.build_mod import benchmark_debounce; benchmark_debounce()"
- name: Test pack integrity and comparisons
run: python -m unittest discover -s tests -v
- name: Upload original mod and pack manifests only
@@ -56,3 +58,4 @@ jobs:
dist/*.mrpack
dist/horizon-lab-*.jar
dist/worker-pacing-benchmark.txt
dist/debounce-queue-benchmark.txt
+6 -2
View File
@@ -6,7 +6,7 @@ Client-first performance research for Minecraft Java **26.3**, preserving vanill
## Play on your Mac
Download **horizon-mac-starter-0.6.0.zip** from [Releases](https://github.com/ludovic111/minecraft-optimization-lab/releases), extract it and open `Mac-Start.command`. It verifies and installs official universal Prism Launcher in `~/Applications` if needed, then opens the balanced pack import. Sign into Microsoft **inside Prism yourself**. This project needs no credentials.
Download **horizon-mac-starter-0.7.0.zip** from [Releases](https://github.com/ludovic111/minecraft-optimization-lab/releases), extract it and open `Mac-Start.command`. It verifies and installs official universal Prism Launcher in `~/Applications` if needed, then opens the balanced pack import. Sign into Microsoft **inside Prism yourself**. This project needs no credentials.
Use native **Java 25 ARM64**, maximum heap **6144 MiB**, minimum **512 MiB** on your 16 GB M2 Pro. Prism can download Java automatically. Start at 1280×800 or 1920×1200; full Retina resolution is a larger GPU workload. [START-HERE.txt](packs/START-HERE.txt) has details. The same `.mrpack` files import into Prism on Windows and Linux.
@@ -17,6 +17,8 @@ Use native **Java 25 ARM64**, maximum heap **6144 MiB**, minimum **512 MiB** on
| adaptive (experiment) | 12 | 128 | 6144 MiB |
| worker-pacing (experiment) | 12 | 128 | 6144 MiB |
| adaptive-pacing (experiment) | 12 | 128 | 6144 MiB |
| queue-wait (experimental) | 12 | 128 | 6144 MiB |
| adaptive-queue (experimental) | 12 | 128 | 6144 MiB |
| low-memory | 8 | none | 3072 MiB |
| far-distance | 12 | 256 | 8192 MiB, with sufficient physical RAM |
| cinematic | 12 | 128 | 6144 MiB |
@@ -26,6 +28,8 @@ Balanced combines [Sodium](https://modrinth.com/mod/sodium), [Lithium](https://m
Distant LOD is simplified terrain. Nearby blocks retain full detail. Initial generation costs CPU/disk/memory and needs warm-up. DH adjusts clouds, chunk fade and transparency to blend its renderer; assess appearance as well as speed. Shaders cost GPU time and have [Mac-specific limits](https://shaders.properties/current/reference/miscellaneous/macos/). Universal CPU/GPU support and exact vanilla equivalence remain validation goals. Simulation distance stays 12 in every profile; normal 20 TPS rules are retained.
The optional `queue-wait` pack yields during pending distant-terrain debounce retries; `adaptive-queue` combines it with the existing controllers. [Queue experiment and measurement limits](docs/debounce-queue.md).
## Measure on your hardware
The optional [adaptive terrain experiment](docs/adaptive-terrain.md) throttles distant
@@ -60,7 +64,7 @@ python3 tools/build_mod.py
python3 tools/build_release.py
```
Gitignored `dist/` contains nine packs, our original instrumentation JAR, client/server starter ZIPs and SHA256SUMS. [mods.lock.json](packs/mods.lock.json) pins mod versions, exact dependency closure, SHA-1/SHA-512 and source/license; [fabric.lock.json](packs/fabric.lock.json) pins loader/library SHA-256. Packs use the [Modrinth format](https://support.modrinth.com/en/articles/8802351-modrinth-modpack-format-mrpack). They embed only original project code; third-party mods, game and assets download from their publishers.
Gitignored `dist/` contains eleven packs, our original instrumentation JAR, client/server starter ZIPs and SHA256SUMS. [mods.lock.json](packs/mods.lock.json) pins mod versions, exact dependency closure, SHA-1/SHA-512 and source/license; [fabric.lock.json](packs/fabric.lock.json) pins loader/library SHA-256. Packs use the [Modrinth format](https://support.modrinth.com/en/articles/8802351-modrinth-modpack-format-mrpack). They embed only original project code; third-party mods, game and assets download from their publishers.
The server starter uses Lithium/FerriteCore and `/horizonserver bench <label> <seconds>`. [Server instructions](docs/server-quickstart.txt) cover setup and a baseline. Files are prepared before you accept Minecraft's EULA locally. A 50-active-player workload remains to be measured.
@@ -0,0 +1,14 @@
Java openjdk 25.0.4.1 2026-08-18 LTS
Platform Darwin 25.6.0 arm64; logical CPUs 3
mode=upstream size=1 polls=2050320 worker_cpu_ms=218.517 wall_ms=250.000 worker_allocated_bytes=65610240
mode=wait size=1 polls=24 worker_cpu_ms=1.116 wall_ms=250.103 worker_allocated_bytes=768
mode=upstream size=1 polls=2641880 worker_cpu_ms=247.157 wall_ms=250.000 worker_allocated_bytes=84540160
mode=wait size=1 polls=26 worker_cpu_ms=0.873 wall_ms=258.012 worker_allocated_bytes=832
mode=upstream size=1 polls=2502067 worker_cpu_ms=248.481 wall_ms=250.000 worker_allocated_bytes=80066144
mode=wait size=1 polls=22 worker_cpu_ms=0.693 wall_ms=252.426 worker_allocated_bytes=704
mode=upstream size=64 polls=1073260 worker_cpu_ms=249.930 wall_ms=250.000 worker_allocated_bytes=34344320
mode=wait size=64 polls=21 worker_cpu_ms=0.624 wall_ms=251.431 worker_allocated_bytes=672
mode=upstream size=64 polls=1117775 worker_cpu_ms=248.519 wall_ms=250.000 worker_allocated_bytes=35768800
mode=wait size=64 polls=66 worker_cpu_ms=1.172 wall_ms=252.401 worker_allocated_bytes=2112
mode=upstream size=64 polls=1017233 worker_cpu_ms=248.550 wall_ms=250.000 worker_allocated_bytes=32551456
mode=wait size=64 polls=74 worker_cpu_ms=1.154 wall_ms=250.207 worker_allocated_bytes=2368
@@ -0,0 +1,14 @@
Java openjdk 25.0.4.1 2026-08-18 LTS
Platform Linux 6.17.0-1022-azure x86_64; logical CPUs 4
mode=upstream size=1 polls=3147912 worker_cpu_ms=248.446 wall_ms=250.000 worker_allocated_bytes=100733184
mode=wait size=1 polls=234 worker_cpu_ms=3.085 wall_ms=250.068 worker_allocated_bytes=7488
mode=upstream size=1 polls=3108002 worker_cpu_ms=249.985 wall_ms=250.000 worker_allocated_bytes=99456064
mode=wait size=1 polls=235 worker_cpu_ms=2.960 wall_ms=250.088 worker_allocated_bytes=7520
mode=upstream size=1 polls=3073051 worker_cpu_ms=248.404 wall_ms=250.000 worker_allocated_bytes=98337632
mode=wait size=1 polls=235 worker_cpu_ms=2.904 wall_ms=250.067 worker_allocated_bytes=7520
mode=upstream size=64 polls=999765 worker_cpu_ms=248.680 wall_ms=250.000 worker_allocated_bytes=31992480
mode=wait size=64 polls=235 worker_cpu_ms=2.887 wall_ms=250.067 worker_allocated_bytes=7520
mode=upstream size=64 polls=999096 worker_cpu_ms=250.000 wall_ms=250.000 worker_allocated_bytes=31971072
mode=wait size=64 polls=234 worker_cpu_ms=2.890 wall_ms=250.068 worker_allocated_bytes=7488
mode=upstream size=64 polls=992373 worker_cpu_ms=249.987 wall_ms=250.000 worker_allocated_bytes=31755936
mode=wait size=64 polls=234 worker_cpu_ms=2.891 wall_ms=250.068 worker_allocated_bytes=7488
@@ -0,0 +1,14 @@
Java openjdk 25.0.4.1 2026-08-18 LTS
Platform Windows 2025Server AMD64; logical CPUs 4
mode=upstream size=1 polls=3016566 worker_cpu_ms=234.375 wall_ms=250.000 worker_allocated_bytes=96530112
mode=wait size=1 polls=173 worker_cpu_ms=0.000 wall_ms=250.006 worker_allocated_bytes=5536
mode=upstream size=1 polls=2991508 worker_cpu_ms=250.000 wall_ms=250.000 worker_allocated_bytes=95728256
mode=wait size=1 polls=175 worker_cpu_ms=0.000 wall_ms=250.856 worker_allocated_bytes=5600
mode=upstream size=1 polls=2979343 worker_cpu_ms=250.000 wall_ms=250.000 worker_allocated_bytes=95338976
mode=wait size=1 polls=171 worker_cpu_ms=0.000 wall_ms=251.306 worker_allocated_bytes=5472
mode=upstream size=64 polls=1001664 worker_cpu_ms=250.000 wall_ms=250.000 worker_allocated_bytes=32053248
mode=wait size=64 polls=168 worker_cpu_ms=0.000 wall_ms=250.695 worker_allocated_bytes=5376
mode=upstream size=64 polls=1001600 worker_cpu_ms=250.000 wall_ms=250.000 worker_allocated_bytes=32051200
mode=wait size=64 polls=166 worker_cpu_ms=0.000 wall_ms=250.593 worker_allocated_bytes=5312
mode=upstream size=64 polls=988856 worker_cpu_ms=234.375 wall_ms=250.000 worker_allocated_bytes=31643392
mode=wait size=64 polls=171 worker_cpu_ms=0.000 wall_ms=250.557 worker_allocated_bytes=5472
+83
View File
@@ -0,0 +1,83 @@
# Debounce queue experiment
The local profile showed substantial allocation on the distant-terrain chunk
update queue thread. Direct per-thread allocation counters confirmed activity
there; sampled stacks repeatedly entered player-position reads and queue
reinsertion. Inspection of the pinned DH 3.3.4 bytecode explains a mechanism:
an update younger than its existing 250 ms debounce deadline is removed and
reinserted, while the outer queue loop sleeps only when both queues are empty.
A nonempty pending queue can therefore retry continuously before it can do work.
The optional `queue-wait` profile keeps balanced graphics, distances, simulation
settings, mods and worker budgets. Its original hook performs the existing
debounce reinsertion, then requests a wait of up to 1 ms, bounded by the remaining
deadline, if no preprocessing work is pending. It only waits on the queue worker,
never a caller such as the render thread. Incoming queued work unparks a debounce
wait; the original empty-queue sleep remains unchanged. OS scheduling determines
when the worker resumes.
The same update object, priority queue, debounce timestamp, overload policy,
executor dispatch and normal simulation remain in use. Executor-unavailable and
rejected-dispatch retries are outside this hook.
`adaptive-queue` combines this hook with the existing adaptive terrain budget
and precise worker pacing. Use `queue-wait` versus `m2-balanced` to isolate the
queue change, and `adaptive-queue` versus `adaptive-pacing` to evaluate the
combination. Each profile explicitly enables only its requested experiments.
Set `enabled=false` in `config/horizon-queue-wait.properties` and restart to
disable the queue hook. It is disabled by default and requires exact DH 3.3.4.
Requested waits are not hard latency bounds: operating-system timers can
overshoot, and arrival/worker scheduling affect responsiveness. Parking leaves
the interruption flag intact, so the existing shutdown loop still handles it.
New arrival wakeups reduce the chance of delaying useful preprocessing, but
real terrain completion, block-change visibility and platform behavior need
evaluation alongside CPU, allocations and frame pacing.
## Isolated measurement
Run `python -c "from tools.build_mod import benchmark_debounce; benchmark_debounce()"`
after building the mod. It uses the actual publisher's `ChunkPosQueue`, with
synthetic entries and a 250 ms pending-debounce interval. The upstream mode
repeatedly pops and reinserts the nearest update; the waiting mode inserts the
same bounded-wait policy between retries. Warm-ups precede three alternating
trials at one and 64 queued entries. Each trial checks update identity, nearest
priority and queue count, then reports wall time, worker CPU and worker allocation.
This benchmark isolates redundant polling; it does not simulate game chunk
lighting, rendering, network traffic or terrain completion. Thread CPU counters
can be coarse, particularly on Windows, so a zero reading is below measurement
resolution, not proof of zero CPU cost. Allocation counts are cumulative bytes
allocated during the interval, not retained heap or process memory. Hardware,
timer behavior and workload can change results. The CI publishes raw output
for Linux, Windows and Apple Silicon macOS. No game-FPS claim follows from this
microbenchmark alone.
## Hosted results, 3 October 2026
Raw output is checked in under
[`benchmarks/debounce-queue-2026-10-03`](../benchmarks/debounce-queue-2026-10-03/).
The tables show medians of three trials. Allocations and CPU refer only to this
synthetic queue polling interval, not the entire game. The macOS runner is hosted
Apple Silicon with three logical CPUs; it is not the user's M2 Pro.
| Platform / queued entries | Upstream allocation | Waiting allocation | Upstream worker CPU | Waiting worker CPU |
| --- | ---: | ---: | ---: | ---: |
| macOS ARM64 / 1 | 80,066,144 B | 768 B | 247.157 ms | 0.873 ms |
| macOS ARM64 / 64 | 34,344,320 B | 2,112 B | 248.550 ms | 1.154 ms |
| Linux x64 / 1 | 99,456,064 B | 7,520 B | 248.446 ms | 2.960 ms |
| Linux x64 / 64 | 31,971,072 B | 7,488 B | 249.987 ms | 2.890 ms |
| Windows x64 / 1 | 95,728,256 B | 5,536 B | 250.000 ms | Below counter resolution |
| Windows x64 / 64 | 32,051,200 B | 5,376 B | 250.000 ms | Below counter resolution |
Each upstream interval lasted about 250 ms. Waiting medians were 250.068 ms on
Linux, 250.593–250.856 ms on Windows, and 251.431–252.426 ms on macOS. One macOS
trial lasted 258.012 ms, demonstrating timer overshoot. These are interval-ending
times; they are not measurements of a real block change reaching the screen.
The real 0.7.0 adaptive-queue demo world renders and records with the hook enabled.
Thread inspection reached the injected debounce parking path. A 120-second run
wrote 643 frame intervals and 2,408 server ticks with matching CSV counts/means,
and 119–120 RSS samples. Distant-terrain data continued updating; game worlds and
DH databases closed cleanly. A separate 60-second profile confirmed allocation
counter activity on the queue thread. Its workload/cache state differs from the
earlier profile, so those profiles are not a numerical before/after comparison.
+12
View File
@@ -22,6 +22,18 @@ Version 0.2.0 targets Minecraft 26.3 / Fabric 0.19.5 / Java 25. This is an initi
## Interpretation limits
The 0.7.0 optional debounce queue hook initializes and renders with the combined
adaptive/pacing controls. The exact candidate JAR wrote 643 frame intervals and
2,408 server-tick samples over 120 seconds; CSV counts and means match the reports,
which capture all three controls as enabled and include resident-memory samples.
Thread inspection reached the injected debounce parking path, DH terrain data
continued updating, and worlds/databases/workers closed cleanly. The actual
publisher queue microbenchmark passes identity/priority/count checks on Linux,
Windows and Apple Silicon macOS; its raw results and timing overshoot are documented
in [the queue experiment](debounce-queue.md). These are separate from game-FPS,
block-update-latency or RAM-reduction claims. All eleven pack overrides retain
simulation distance 12 and explicitly set the intended experimental flags.
The 0.6.0 resident-memory sampler ran in the actual adaptive-pacing demo world.
A 120-second recording produced 370 frame intervals and 2,407 server-tick samples;
both CSV counts and mean durations match their JSON summaries. Each report has
@@ -0,0 +1,14 @@
package dev.horizonlab.budget;
/** Wait only while an unchanged debounce deadline blocks progress. */
public final class DebounceWait {
public static final long MAX_WAIT_NS = 1_000_000L;
private DebounceWait() {}
public static long delay(long now, long firstQueued, long debounce, boolean preprocessingPending) {
if (preprocessingPending || debounce <= 0) return 0;
long age = now - firstQueued;
if (age < 0 || age >= debounce) return 0;
return Math.min(MAX_WAIT_NS, debounce - age);
}
}
@@ -92,6 +92,7 @@ public final class HorizonClient implements ClientModInitializer {
context.put("profile", profile);
context.put("adaptive_budget_enabled", terrainBudget != null);
context.put("precise_worker_pacing", dev.horizonlab.mixin.HorizonMixinPlugin.workerPacingEnabled());
context.put("debounce_queue_wait", dev.horizonlab.mixin.HorizonMixinPlugin.debounceWaitEnabled());
context.put("adaptive_target_fps", targetFps);
context.put("render_distance", client.options.renderDistance().get());
context.put("simulation_distance", client.options.simulationDistance().get());
@@ -0,0 +1,52 @@
package dev.horizonlab.mixin;
import com.seibel.distanthorizons.core.api.internal.chunkUpdating.ChunkPosQueue;
import com.seibel.distanthorizons.core.api.internal.chunkUpdating.ChunkUpdateData;
import com.seibel.distanthorizons.core.api.internal.chunkUpdating.ChunkUpdateQueueManager;
import com.seibel.distanthorizons.core.pos.DhChunkPos;
import dev.horizonlab.budget.DebounceWait;
import java.util.concurrent.locks.LockSupport;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Pseudo;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Pseudo
@Mixin(targets = "com.seibel.distanthorizons.core.api.internal.chunkUpdating.ChunkUpdateQueueManager", remap = false)
public abstract class DhDebounceWaitMixin {
@Shadow @Final public ChunkPosQueue preUpdateQueue;
@Unique private volatile Thread horizonQueueWorker;
@Inject(method = "runQueueingLoop", at = @At("HEAD"), remap = false)
private void horizonRememberWorker(CallbackInfo callback) {
horizonQueueWorker = Thread.currentThread();
}
@Inject(method = "runQueueingLoop", at = @At("RETURN"), remap = false)
private void horizonReleaseWorker(CallbackInfo callback) {
horizonQueueWorker = null;
}
// Ordinal zero is specifically the debounce retry. Executor rejection retries remain unchanged.
@Redirect(method = "tryDispatchReadyChunkUpdate", at = @At(value = "INVOKE",
target = "Lcom/seibel/distanthorizons/core/api/internal/chunkUpdating/ChunkPosQueue;addItem(Lcom/seibel/distanthorizons/core/pos/DhChunkPos;Lcom/seibel/distanthorizons/core/api/internal/chunkUpdating/ChunkUpdateData;)V",
ordinal = 0), require = 1, allow = 1, remap = false)
private void horizonWaitForDebounce(ChunkPosQueue queue, DhChunkPos position, ChunkUpdateData update) {
queue.addItem(position, update);
if (Thread.currentThread() != horizonQueueWorker) return;
long delay = DebounceWait.delay(System.nanoTime(), update.firstQueuedNanoTime,
ChunkUpdateQueueManager.UPDATE_DEBOUNCE_NANOS, !preUpdateQueue.isEmpty());
if (delay > 0) LockSupport.parkNanos(this, delay);
}
@Inject(method = "addItemToQueue", at = @At("RETURN"), remap = false)
private void horizonWakeForNewWork(CallbackInfo callback) {
Thread worker = horizonQueueWorker;
if (worker != null && worker != Thread.currentThread()) LockSupport.unpark(worker);
}
}
@@ -10,9 +10,10 @@ import org.slf4j.LoggerFactory;
import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
/** The internal worker hook is opt-in and limited to the inspected, pinned DH version. */
/** Internal hooks are opt-in and limited to the inspected, pinned DH version. */
public final class HorizonMixinPlugin implements IMixinConfigPlugin {
private static boolean workerPacing;
private static boolean debounceWait;
@Override public void onLoad(String mixinPackage) {
var loader = FabricLoader.getInstance();
@@ -31,11 +32,29 @@ public final class HorizonMixinPlugin implements IMixinConfigPlugin {
} catch (Exception error) {
LoggerFactory.getLogger("horizonlab").warn("Worker pacing disabled: invalid configuration", error);
}
try {
Properties properties = new Properties();
var queueFile = loader.getConfigDir().resolve("horizon-queue-wait.properties");
if (Files.exists(queueFile)) {
try (var reader = Files.newBufferedReader(queueFile)) { properties.load(reader); }
}
boolean requested = Boolean.parseBoolean(properties.getProperty("enabled", "false"));
boolean supported = loader.getModContainer("distanthorizons")
.map(mod -> mod.getMetadata().getVersion().getFriendlyString().equals("3.3.4")).orElse(false);
debounceWait = requested && supported;
if (requested) LoggerFactory.getLogger("horizonlab").info(
"DH debounce queue wait: {} (requires pinned DH 3.3.4)", debounceWait ? "enabled" : "unavailable");
} catch (Exception error) {
LoggerFactory.getLogger("horizonlab").warn("Debounce queue wait disabled: invalid configuration", error);
}
}
public static boolean workerPacingEnabled() { return workerPacing; }
public static boolean debounceWaitEnabled() { return debounceWait; }
@Override public boolean shouldApplyMixin(String targetClassName, String mixinClassName) {
return !mixinClassName.endsWith("DhWorkerPacingMixin") || workerPacing;
if (mixinClassName.endsWith("DhWorkerPacingMixin")) return workerPacing;
if (mixinClassName.endsWith("DhDebounceWaitMixin")) return debounceWait;
return true;
}
@Override public String getRefMapperConfig() { return null; }
@Override public List<String> getMixins() { return null; }
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "horizonlab",
"version": "0.6.0",
"version": "0.7.0",
"name": "Horizon Lab",
"description": "Client frame pacing and server tick measurements for reproducible optimization experiments.",
"authors": [
@@ -4,6 +4,6 @@
"plugin": "dev.horizonlab.mixin.HorizonMixinPlugin",
"compatibilityLevel": "JAVA_25",
"mixins": ["ServerTickMixin"],
"client": ["FrameMixin", "DhWorkerPacingMixin"],
"client": ["FrameMixin", "DhWorkerPacingMixin", "DhDebounceWaitMixin"],
"injectors": {"defaultRequire": 1}
}
@@ -0,0 +1,50 @@
package dev.horizonlab.budget;
import com.seibel.distanthorizons.core.api.internal.chunkUpdating.ChunkPosQueue;
import com.seibel.distanthorizons.core.api.internal.chunkUpdating.ChunkUpdateData;
import com.seibel.distanthorizons.core.pos.DhChunkPos;
import java.lang.management.ManagementFactory;
import java.util.concurrent.locks.LockSupport;
/** Measures the actual upstream queue during a synthetic pending-debounce interval, not game FPS. */
public final class DebounceQueueBenchmark {
private static void run(boolean waiting, int size, boolean report) {
ChunkPosQueue queue = new ChunkPosQueue();
DhChunkPos closest = new DhChunkPos(0, 0);
ChunkUpdateData closestData = null;
for (int i = 0; i < size; i++) {
ChunkUpdateData update = new ChunkUpdateData(null, null);
if (i == 0) closestData = update;
queue.addItem(new DhChunkPos(i, 0), update);
}
var threads = (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
long id = Thread.currentThread().threadId();
long allocated = threads.getThreadAllocatedBytes(id), cpu = threads.getCurrentThreadCpuTime();
long start = System.nanoTime(), debounce = 250_000_000L, loops = 0;
while (System.nanoTime() - start < debounce) {
ChunkUpdateData update = queue.popClosest();
if (update != closestData) throw new AssertionError("Queue priority or data changed");
queue.addItem(closest, update);
loops++;
if (waiting) {
long delay = DebounceWait.delay(System.nanoTime(), start, debounce, false);
if (delay > 0) LockSupport.parkNanos(delay);
}
}
long elapsed = System.nanoTime() - start;
cpu = threads.getCurrentThreadCpuTime() - cpu;
allocated = threads.getThreadAllocatedBytes(id) - allocated;
if (queue.getQueuedCount() != size || queue.popClosest() != closestData)
throw new AssertionError("Pending queue data changed");
if (report) System.out.printf(java.util.Locale.ROOT,
"mode=%s size=%d polls=%d worker_cpu_ms=%.3f wall_ms=%.3f worker_allocated_bytes=%d%n",
waiting ? "wait" : "upstream", size, loops, cpu / 1e6, elapsed / 1e6, allocated);
}
public static void main(String[] args) {
for (int size : new int[]{1, 64}) {
for (int i = 0; i < 2; i++) { run(false, size, false); run(true, size, false); }
for (int i = 0; i < 3; i++) { run(false, size, true); run(true, size, true); }
}
}
}
@@ -0,0 +1,30 @@
package dev.horizonlab.budget;
public final class DebounceWaitTest {
public static void main(String[] args) {
long debounce = 250_000_000L;
check(DebounceWait.delay(0, 0, debounce, false) == 1_000_000L, "bounded wait for a fresh update");
check(DebounceWait.delay(249_900_000L, 0, debounce, false) == 100_000L, "remaining deadline limits wait");
check(DebounceWait.delay(debounce, 0, debounce, false) == 0, "ready update is not delayed");
check(DebounceWait.delay(debounce + 1, 0, debounce, false) == 0, "overdue update is not delayed");
check(DebounceWait.delay(1, 0, debounce, true) == 0, "pending preprocessing is not delayed");
check(DebounceWait.delay(0, 1, debounce, false) == 0, "future timestamp does not create a wait");
check(DebounceWait.delay(0, 0, 0, false) == 0, "disabled debounce is not delayed");
long wrapped = Long.MAX_VALUE - 500_000L;
check(DebounceWait.delay(wrapped + 1_000_000L, wrapped, debounce, false) == 1_000_000L, "monotonic timer wrap");
long now = 0;
int waits = 0;
while (now < debounce) {
long wait = DebounceWait.delay(now, 0, debounce, false);
check(wait > 0 && wait <= DebounceWait.MAX_WAIT_NS && now + wait <= debounce, "deadline unchanged");
now += wait;
waits++;
}
check(now == debounce && waits == 250, "debounce deadline is reached without extending it");
System.out.println("Debounce wait policy tests passed.");
}
private static void check(boolean condition, String message) {
if (!condition) throw new AssertionError(message);
}
}
+8
View File
@@ -42,6 +42,14 @@ PROFILES
Compare against balanced on your Mac; no actual M2 graphics result is established.
Disable the timer in config/horizon-worker-pacing.properties (enabled=false),
then restart. /horizon adaptive off changes only the adaptive controller.
- queue-wait: same balanced settings, with a short wait instead of continuous
retries while a DH update is still inside its existing 250 ms debounce period.
Incoming work wakes the queue worker. OS timers can overshoot the requested
1 ms maximum wait; evaluate terrain update latency as well as CPU/FPS.
- adaptive-queue: combines queue-wait with adaptive terrain and precise pacing.
For an isolated comparison use queue-wait versus m2-balanced. For the combined
controls use adaptive-queue versus adaptive-pacing. Disable the queue hook in
config/horizon-queue-wait.properties (enabled=false), then restart.
- low-memory: 8 full-detail chunks, no LOD. Set maximum memory 3072 MiB.
For a matched comparison set both instances to the same render distance.
- far-distance: 12 full-detail plus 256 LOD chunks. Start with 8192 MiB ONLY on
+1 -1
View File
@@ -3,7 +3,7 @@
"minecraft": "26.3",
"java_major": 25,
"fabric_loader": "0.19.5",
"pack_version": "0.6.0",
"pack_version": "0.7.0",
"projects": {
"sodium": {
"slug": "sodium",
+1 -1
View File
@@ -94,7 +94,7 @@ function renderDetails(side){
const entry=state[side],target=$(side+'Details');target.replaceChildren();
if(!entry)return;
const r=entry.report,fields=[['Profile',r.profile||r.label||'Unlabeled'],['Recording',format(r.elapsed_seconds)+' s · '+format(r.stats.count)+' samples'],['Platform',[r.os,r.architecture].filter(Boolean).join(' ')||'Not captured']];
if(r.kind==='frames')fields.push(['Graphics',[r.gpu,r.graphics_backend].filter(Boolean).join(' · ')||'Not captured'],['Window',number(r.framebuffer_width)?r.framebuffer_width+' × '+r.framebuffer_height:'Not captured'],['Experiments','Adaptive: '+(r.adaptive_budget_enabled?'on':'off')+' · precise pacing: '+(r.precise_worker_pacing?'on':'off')]);
if(r.kind==='frames')fields.push(['Graphics',[r.gpu,r.graphics_backend].filter(Boolean).join(' · ')||'Not captured'],['Window',number(r.framebuffer_width)?r.framebuffer_width+' × '+r.framebuffer_height:'Not captured'],['Experiments','Adaptive: '+(r.adaptive_budget_enabled?'on':'off')+' · precise pacing: '+(r.precise_worker_pacing?'on':'off')+' · queue wait: '+(r.debounce_queue_wait?'on':'off')]);
for(const [label,value]of fields)target.append(text('dt',label),text('dd',value));
}
async function loadFiles(side,files){
+21
View File
@@ -37,6 +37,10 @@ def test_metrics():
SOURCE / "test/java/dev/horizonlab/budget/WorkerPacerTest.java"]
subprocess.run(["javac", "--release", "25", "-d", str(destination), *map(str, worker_sources)], check=True)
subprocess.run(["java", "-cp", str(destination), "dev.horizonlab.budget.WorkerPacerTest"], check=True)
debounce_sources = [SOURCE / "main/java/dev/horizonlab/budget/DebounceWait.java",
SOURCE / "test/java/dev/horizonlab/budget/DebounceWaitTest.java"]
subprocess.run(["javac", "--release", "25", "-d", str(destination), *map(str, debounce_sources)], check=True)
subprocess.run(["java", "-cp", str(destination), "dev.horizonlab.budget.DebounceWaitTest"], check=True)
def build():
@@ -116,6 +120,23 @@ def benchmark_workers():
print(output.read_text(), end="")
def benchmark_debounce():
arguments = [json.loads(line) for line in (BUILD / "javac.args").read_text().splitlines()]
classpath = os.pathsep.join([str(BUILD / "classes"), arguments[arguments.index("-classpath") + 1]])
tests = BUILD / "debounce-benchmark"
tests.mkdir(parents=True, exist_ok=True)
subprocess.run(["javac", "--release", "25", "-proc:none", "-cp", classpath,
"-d", str(tests), str(SOURCE / "test/java/dev/horizonlab/budget/DebounceQueueBenchmark.java")], check=True)
output = ROOT / "dist/debounce-queue-benchmark.txt"
with output.open("w", encoding="utf-8") as report:
report.write(f"Java {subprocess.check_output(['java', '--version'], text=True).splitlines()[0]}\n")
report.write(f"Platform {platform.system()} {platform.release()} {platform.machine()}; logical CPUs {os.cpu_count()}\n")
report.flush()
subprocess.run(["java", "-cp", os.pathsep.join([str(tests), classpath]),
"dev.horizonlab.budget.DebounceQueueBenchmark"], stdout=report, check=True)
print(output.read_text(), end="")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--test-only", action="store_true")
+5 -1
View File
@@ -21,6 +21,8 @@ PROFILES = {
"adaptive": {"title": "Adaptive terrain experiment", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144, "adaptive": True},
"worker-pacing": {"title": "Precise worker pacing experiment", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144, "pacing": True},
"adaptive-pacing": {"title": "Adaptive precise pacing experiment", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144, "adaptive": True, "pacing": True},
"queue-wait": {"title": "Debounce queue wait experiment", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144, "queue_wait": True},
"adaptive-queue": {"title": "Adaptive pacing and queue wait experiment", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144, "adaptive": True, "pacing": True, "queue_wait": True},
"low-memory": {"title": "Low memory", "mods": CORE, "render": 8, "lod": 0, "heap": 3072},
"far-distance": {"title": "Far distance", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 256, "heap": 8192},
"cinematic": {"title": "Cinematic (optional)", "mods": CORE + ["distanthorizons", "iris", "complementary-reimagined"], "render": 12, "lod": 128, "heap": 6144},
@@ -73,12 +75,14 @@ def overrides(profile_name, mod_bytes):
files = {f"mods/horizon-lab-{read_lock()['pack_version']}.jar": mod_bytes,
"config/horizon-profile.txt": (profile_name + "\n").encode(),
"options.txt": options(profile).encode()}
experiment = profile_name in ["adaptive", "worker-pacing", "adaptive-pacing"]
experiment = any(profile.get(key, False) for key in ["adaptive", "pacing", "queue_wait"])
config = ROOT / "packs/config" / f"{'m2-balanced' if experiment else profile_name}.toml"
files["config/horizon-adaptive.properties"] = (
f"enabled={str(profile.get('adaptive', False)).lower()}\ntargetFps=60\n").encode()
files["config/horizon-worker-pacing.properties"] = (
f"enabled={str(profile.get('pacing', False)).lower()}\n").encode()
files["config/horizon-queue-wait.properties"] = (
f"enabled={str(profile.get('queue_wait', False)).lower()}\n").encode()
if profile["lod"]:
if not config.exists():
raise FileNotFoundError(f"Missing verified DH profile config: {config}")