Merge pull request #3 from ludovic111/precise-terrain-pacing

Respect short-job terrain worker budgets with precise pacing
This commit is contained in:
Ludovic Marie
2026-10-03 21:34:12 +02:00
committed by GitHub
19 changed files with 441 additions and 6 deletions
+3
View File
@@ -44,6 +44,8 @@ jobs:
run: python tools/build_mod.py
- name: Build pinned portable packs
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: Test pack integrity and comparisons
run: python -m unittest discover -s tests -v
- name: Upload original mod and pack manifests only
@@ -53,3 +55,4 @@ jobs:
path: |
dist/*.mrpack
dist/horizon-lab-*.jar
dist/worker-pacing-benchmark.txt
+8 -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.2.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.3.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.
@@ -15,6 +15,8 @@ Use native **Java 25 ARM64**, maximum heap **6144 MiB**, minimum **512 MiB** on
| baseline | 12 | none | 6144 MiB |
| m2-balanced | 12 | 128 | 6144 MiB |
| adaptive (experiment) | 12 | 128 | 6144 MiB |
| worker-pacing (experiment) | 12 | 128 | 6144 MiB |
| adaptive-pacing (experiment) | 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 |
@@ -31,6 +33,10 @@ terrain background work when frames slow down or heap pressure rises, keeping th
balanced profile's view distances and simulation settings. It remains opt-in until
real hardware demonstrates a benefit.
The additional [precise worker pacing experiment](docs/worker-pacing.md) makes short
terrain tasks respect their duty-cycle budget and avoids boxed worker timestamps.
It changes generation speed and CPU use, so it stays separate from balanced.
Press **F8** during gameplay to start a 120-second recording, or again to stop early. Rebind in Controls if needed. This also works with restricted chat accounts. Alternatively: `/horizon bench <label> 120`, `/horizon stop`, `/horizon status`.
Use separate identical world copies and the same camera route, resolution, render/simulation distance, heap, VSync and FPS limit. Warm up, then alternate at least three baseline/optimized runs. Test fresh chunk exploration separately. For everyday play cap FPS or enable VSync to reduce power usage.
@@ -52,7 +58,7 @@ python3 tools/build_mod.py
python3 tools/build_release.py
```
Gitignored `dist/` contains seven 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 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.
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
upstream requested ratio 0.500; 50000 tasks of 10000 ns; worker CPU/wall 0.346; 1643.771 ms; worker allocation 1403064 bytes
precise requested ratio 0.500; 50000 tasks of 10000 ns; worker CPU/wall 0.514; 1061.526 ms; worker allocation 15456 bytes
upstream requested ratio 0.050; 50000 tasks of 10000 ns; worker CPU/wall 0.466; 1238.603 ms; worker allocation 1449704 bytes
precise requested ratio 0.050; 50000 tasks of 10000 ns; worker CPU/wall 0.063; 11385.730 ms; worker allocation 204024 bytes
upstream requested ratio 0.500; 50000 tasks of 10000 ns; worker CPU/wall 0.703; 785.293 ms; worker allocation 1417064 bytes
precise requested ratio 0.500; 50000 tasks of 10000 ns; worker CPU/wall 0.509; 1097.416 ms; worker allocation 14496 bytes
upstream requested ratio 0.050; 50000 tasks of 10000 ns; worker CPU/wall 0.431; 1293.360 ms; worker allocation 1529184 bytes
precise requested ratio 0.050; 50000 tasks of 10000 ns; worker CPU/wall 0.065; 10727.658 ms; worker allocation 198104 bytes
upstream requested ratio 0.500; 50000 tasks of 10000 ns; worker CPU/wall 0.620; 896.747 ms; worker allocation 1490864 bytes
precise requested ratio 0.500; 50000 tasks of 10000 ns; worker CPU/wall 0.518; 1062.565 ms; worker allocation 13096 bytes
upstream requested ratio 0.050; 50000 tasks of 10000 ns; worker CPU/wall 0.605; 975.086 ms; worker allocation 1450064 bytes
precise requested ratio 0.050; 50000 tasks of 10000 ns; worker CPU/wall 0.060; 11976.557 ms; worker allocation 196840 bytes
@@ -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
upstream requested ratio 0.500; 50000 tasks of 10000 ns; worker CPU/wall 1.000; 578.014 ms; worker allocation 1450616 bytes
precise requested ratio 0.500; 50000 tasks of 10000 ns; worker CPU/wall 0.525; 1041.454 ms; worker allocation 64976 bytes
upstream requested ratio 0.050; 50000 tasks of 10000 ns; worker CPU/wall 0.976; 591.683 ms; worker allocation 1451744 bytes
precise requested ratio 0.050; 50000 tasks of 10000 ns; worker CPU/wall 0.076; 10349.493 ms; worker allocation 145264 bytes
upstream requested ratio 0.500; 50000 tasks of 10000 ns; worker CPU/wall 1.000; 577.632 ms; worker allocation 1451096 bytes
precise requested ratio 0.500; 50000 tasks of 10000 ns; worker CPU/wall 0.523; 1043.863 ms; worker allocation 65120 bytes
upstream requested ratio 0.050; 50000 tasks of 10000 ns; worker CPU/wall 0.977; 591.337 ms; worker allocation 1410264 bytes
precise requested ratio 0.050; 50000 tasks of 10000 ns; worker CPU/wall 0.076; 10334.845 ms; worker allocation 124264 bytes
upstream requested ratio 0.500; 50000 tasks of 10000 ns; worker CPU/wall 0.987; 583.777 ms; worker allocation 1490096 bytes
precise requested ratio 0.500; 50000 tasks of 10000 ns; worker CPU/wall 0.524; 1038.102 ms; worker allocation 64656 bytes
upstream requested ratio 0.050; 50000 tasks of 10000 ns; worker CPU/wall 0.952; 606.495 ms; worker allocation 1408464 bytes
precise requested ratio 0.050; 50000 tasks of 10000 ns; worker CPU/wall 0.076; 10346.209 ms; worker allocation 165856 bytes
@@ -0,0 +1,14 @@
Java openjdk 25.0.4.1 2026-08-18 LTS
Platform Windows 2025Server AMD64; logical CPUs 4
upstream requested ratio 0.500; 50000 tasks of 10000 ns; worker CPU/wall 0.952; 557.784 ms; worker allocation 1491496 bytes
precise requested ratio 0.500; 50000 tasks of 10000 ns; worker CPU/wall 0.556; 1038.982 ms; worker allocation 17776 bytes
upstream requested ratio 0.050; 50000 tasks of 10000 ns; worker CPU/wall 0.852; 623.419 ms; worker allocation 1410384 bytes
precise requested ratio 0.050; 50000 tasks of 10000 ns; worker CPU/wall 0.078; 10247.387 ms; worker allocation 214896 bytes
upstream requested ratio 0.500; 50000 tasks of 10000 ns; worker CPU/wall 0.998; 548.088 ms; worker allocation 1489616 bytes
precise requested ratio 0.500; 50000 tasks of 10000 ns; worker CPU/wall 0.574; 1034.032 ms; worker allocation 15096 bytes
upstream requested ratio 0.050; 50000 tasks of 10000 ns; worker CPU/wall 0.867; 630.903 ms; worker allocation 1449664 bytes
precise requested ratio 0.050; 50000 tasks of 10000 ns; worker CPU/wall 0.078; 10266.232 ms; worker allocation 214904 bytes
upstream requested ratio 0.500; 50000 tasks of 10000 ns; worker CPU/wall 0.996; 549.301 ms; worker allocation 1448456 bytes
precise requested ratio 0.500; 50000 tasks of 10000 ns; worker CPU/wall 0.452; 1036.321 ms; worker allocation 13776 bytes
upstream requested ratio 0.050; 50000 tasks of 10000 ns; worker CPU/wall 0.971; 563.129 ms; worker allocation 1409664 bytes
precise requested ratio 0.050; 50000 tasks of 10000 ns; worker CPU/wall 0.100; 10276.324 ms; worker allocation 214744 bytes
+10
View File
@@ -22,6 +22,16 @@ Version 0.2.0 targets Minecraft 26.3 / Fabric 0.19.5 / Java 25. This is an initi
## Interpretation limits
The 0.4.0 worker-pacing hook also renders the demo world with the complete mod stack.
Both pacing and adaptive controls are captured as enabled in the final build's
120-second frame report. It produced 359 frame intervals and 2,401 integrated-server
tick samples, verified against raw CSV counts and heap/resource fields. The DH database
received terrain-data updates during this run. The earlier hook build saved/quitted
and closed its databases/workers cleanly. Hosted executor benchmarks pass on Linux,
Windows and Apple Silicon macOS; [their results](worker-pacing.md) remain separate
from game-performance claims. The revised policy tests include 1 ms and 15 ms timer
overshoot and bounded credit after long stalls.
The 0.3.0 adaptive profile rendered the actual demo world and applied live DH duty-cycle
changes from 0.5 down to 0.05 under software-renderer frame pressure. Opening the pause
menu released the override and reported an effective ratio of 0.5 again. A separate
+93
View File
@@ -0,0 +1,93 @@
# Precise distant-terrain worker pacing
The optional `worker-pacing` and `adaptive-pacing` profiles change the timer used by
Distant Horizons background workers. Both keep balanced's 12 full-detail chunks,
128-chunk distant radius, two workers, normal simulation and graphics configuration.
Balanced's timer remains unchanged. `adaptive-pacing` also enables the frame/heap
pressure controller; `worker-pacing` uses the fixed user-configured duty cycle.
The pinned DH 3.3.4 executor measures task duration, calculates a proportional wait,
then converts nanoseconds to whole milliseconds before sleeping. A task that requests
less than a millisecond of waiting reaches `sleep(0)`. Its effect depends on JVM,
operating system and scheduling contention. The configured duty cycle therefore may
not describe what short tasks actually receive. The timestamp is also boxed into a
`Long` per task. Profiling established the boxing site, but did not establish it as
the game's primary allocation cost.
The original Horizon hook accumulates fractional waits until at least 250 microseconds
are due, then sleeps with nanosecond precision. Measured timer overshoot earns credit
against later waits, capped at 50 milliseconds to bound recovery after a long stall.
Primitive state is allocated once per worker rather than boxing
each timestamp. Changes to the duty-cycle setting discard stale debt; an idle worker
also discards it. Interruption during sleep releases debt with the upstream hook's
interruption behavior. The runnable, queues, result, exception and execution order
are unchanged. The inspected direct superclass hooks are no-ops.
This changes background completion time: a worker that previously exceeded a 5%
budget can now take longer to finish the same jobs while leaving more CPU time for
the foreground. On some systems the old zero-duration sleep instead overthrottles
work. Neither less background CPU nor a correct timer guarantees higher game FPS.
OS timer precision and scheduler overhead can still shift actual CPU duty cycle.
The hook is disabled by default and applies only to the exact inspected DH 3.3.4
version. Enable with `config/horizon-worker-pacing.properties`:
```properties
enabled=true
```
Restart the game after changing this property. `/horizon adaptive off` changes the
adaptive controller, not this timer. Frame reports capture `precise_worker_pacing`.
Reproduce the isolated executor benchmark:
```sh
python3 tools/build_mod.py --benchmark-workers
```
`dist/worker-pacing-benchmark.txt` records three runs per mode and requested budget,
using 50,000 jobs with a nominal ten-microsecond workload after warm-up. It compares
the actual upstream executor with a subclass using the original pacing routine.
Worker CPU time and allocation counters exclude allocations on the producer thread.
This is a timer/allocation microbenchmark, not Minecraft FPS, player TPS or a full
terrain generation benchmark. Hosted Linux, macOS and Windows runs produce their
own artifacts; contention and warm-up can change the results.
The first 2,000-job Windows runs exposed CPU-counter quantization: a single worker
could appear above one core or at zero CPU during a very short interval. Those
figures are not reliable CPU-duty results. The longer workload provides a larger
measurement window; counters and scheduling still have finite precision.
Deterministic tests simulate multiple job sizes, timer overshoot, configuration
changes, idle time and invalid ratios. Native game validation must also check terrain
progress, frame/tick capture and clean shutdown. On the M2 Pro, compare balanced,
worker-pacing and adaptive-pacing with identical cold and warm worlds. Record distant
terrain completion times alongside foreground performance and CPU use.
## Hosted executor measurements
[Raw platform results](../benchmarks/worker-pacing-2026-10-03/) came from
[CI run 37147381649](https://github.com/ludovic111/minecraft-optimization-lab/actions/runs/37147381649),
using the 50,000-job workload and the revised overshoot credit. Median worker CPU
seconds per elapsed second across three runs were:
| Platform | Requested budget | Upstream | Precise |
| --- | ---: | ---: | ---: |
| macOS ARM64 | 0.50 | 0.620 | 0.514 |
| macOS ARM64 | 0.05 | 0.466 | 0.063 |
| Linux x64 | 0.50 | 1.000 | 0.524 |
| Linux x64 | 0.05 | 0.976 | 0.076 |
| Windows x64 | 0.50 | 0.996 | 0.556 |
| Windows x64 | 0.05 | 0.867 | 0.078 |
These are isolated worker ratios, not game CPU reductions or FPS gains. The macOS
runner exposes three logical CPUs and is not the user's M2 Pro. At the 0.05 setting,
processing the fixed workload takes roughly 10–11 seconds with the precise timer;
many upstream runs finish in under two seconds because the requested delay is not
being applied consistently. Lower background activity costs completion time.
Actual CPU ratios exceed the nominal task-time ratio because executor/sleep overhead
also consumes CPU. OS preemption and counter precision affect each run.
Median worker allocation per job at the 0.50 setting fell from approximately 28–30
bytes to 0.3–1.3 bytes on these runners. This supports removal of the per-job boxed
timestamp; it does not establish a significant whole-game heap reduction.
@@ -0,0 +1,36 @@
package dev.horizonlab.budget;
/** Per-worker primitive state; amortizes short waits without discarding fractional milliseconds. */
public final class WorkerPacer {
public static final long QUANTUM_NS = 250_000;
public static final long MAX_CREDIT_NS = 50_000_000;
private long started;
private long completed;
private double debtNs;
private double previousRatio = 1;
public void begin(long now) {
if (completed != 0 && now - completed > 1_000_000_000L) debtNs = 0;
started = now;
}
public long finish(long now, double ratio) {
long workNs = Math.max(0, now - started);
completed = now;
if (ratio != previousRatio) debtNs = 0;
previousRatio = ratio;
if (!Double.isFinite(ratio) || ratio <= 0 || ratio >= 1) {
debtNs = 0;
return 0;
}
debtNs += workNs * (1.0 / ratio - 1.0);
return debtNs < QUANTUM_NS ? 0 : (long) Math.min(debtNs, Long.MAX_VALUE / 4.0);
}
public void pauseCompleted(long now) {
debtNs = Math.max(-MAX_CREDIT_NS, debtNs - Math.max(0, now - completed));
completed = now;
}
public void interrupted(long now) { debtNs = 0; completed = now; }
}
@@ -91,6 +91,7 @@ public final class HorizonClient implements ClientModInitializer {
context.put("minecraft", "26.3");
context.put("profile", profile);
context.put("adaptive_budget_enabled", terrainBudget != null);
context.put("precise_worker_pacing", dev.horizonlab.mixin.HorizonMixinPlugin.workerPacingEnabled());
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,42 @@
package dev.horizonlab.mixin;
import com.seibel.distanthorizons.core.config.types.ConfigEntry;
import dev.horizonlab.budget.WorkerPacer;
import java.util.concurrent.TimeUnit;
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.callback.CallbackInfo;
@Pseudo
@Mixin(targets = "com.seibel.distanthorizons.core.util.threading.RateLimitedThreadPoolExecutor", remap = false)
public abstract class DhWorkerPacingMixin {
@Shadow @Final public ConfigEntry<Double> runTimeRatioConfig;
@Unique private final ThreadLocal<WorkerPacer> horizonPacing = ThreadLocal.withInitial(WorkerPacer::new);
// The inspected superclass's hooks are no-ops. Neither hook changes the runnable or task queue.
@Inject(method = "beforeExecute", at = @At("HEAD"), cancellable = true, remap = false)
private void horizonBeforeTask(Thread thread, Runnable task, CallbackInfo callback) {
horizonPacing.get().begin(System.nanoTime());
callback.cancel();
}
@Inject(method = "afterExecute", at = @At("HEAD"), cancellable = true, remap = false)
private void horizonAfterTask(Runnable task, Throwable error, CallbackInfo callback) {
WorkerPacer pacing = horizonPacing.get();
long delay = pacing.finish(System.nanoTime(), runTimeRatioConfig.get());
if (delay > 0) {
try {
TimeUnit.NANOSECONDS.sleep(delay);
pacing.pauseCompleted(System.nanoTime());
} catch (InterruptedException interrupted) {
pacing.interrupted(System.nanoTime());
}
}
callback.cancel();
}
}
@@ -0,0 +1,45 @@
package dev.horizonlab.mixin;
import java.nio.file.Files;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import net.fabricmc.loader.api.FabricLoader;
import org.objectweb.asm.tree.ClassNode;
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. */
public final class HorizonMixinPlugin implements IMixinConfigPlugin {
private static boolean workerPacing;
@Override public void onLoad(String mixinPackage) {
var loader = FabricLoader.getInstance();
var file = loader.getConfigDir().resolve("horizon-worker-pacing.properties");
try {
Properties properties = new Properties();
if (Files.exists(file)) {
try (var reader = Files.newBufferedReader(file)) { 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);
workerPacing = requested && supported;
if (requested) LoggerFactory.getLogger("horizonlab").info(
"Precise DH worker pacing: {} (requires pinned DH 3.3.4)", workerPacing ? "enabled" : "unavailable");
} catch (Exception error) {
LoggerFactory.getLogger("horizonlab").warn("Worker pacing disabled: invalid configuration", error);
}
}
public static boolean workerPacingEnabled() { return workerPacing; }
@Override public boolean shouldApplyMixin(String targetClassName, String mixinClassName) {
return !mixinClassName.endsWith("DhWorkerPacingMixin") || workerPacing;
}
@Override public String getRefMapperConfig() { return null; }
@Override public List<String> getMixins() { return null; }
@Override public void acceptTargets(Set<String> mine, Set<String> others) {}
@Override public void preApply(String name, ClassNode node, String mixin, IMixinInfo info) {}
@Override public void postApply(String name, ClassNode node, String mixin, IMixinInfo info) {}
}
@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"id": "horizonlab",
"version": "0.3.0",
"version": "0.4.0",
"name": "Horizon Lab",
"description": "Client frame pacing and server tick measurements for reproducible optimization experiments.",
"authors": [
@@ -1,8 +1,9 @@
{
"required": true,
"package": "dev.horizonlab.mixin",
"plugin": "dev.horizonlab.mixin.HorizonMixinPlugin",
"compatibilityLevel": "JAVA_25",
"mixins": ["ServerTickMixin"],
"client": ["FrameMixin"],
"client": ["FrameMixin", "DhWorkerPacingMixin"],
"injectors": {"defaultRequire": 1}
}
@@ -0,0 +1,48 @@
package dev.horizonlab.budget;
public final class WorkerPacerTest {
private static void check(boolean value, String reason) { if (!value) throw new AssertionError(reason); }
public static void main(String[] args) {
for (double ratio : new double[]{0.01, 0.05, 0.1, 0.5, 0.9, 1}) {
for (long work : new long[]{100, 10_000, 1_000_000, 100_000_000}) {
for (long overshoot : new long[]{80_000, 1_000_000, 15_000_000}) {
WorkerPacer pacer = new WorkerPacer();
long now = 1;
long active = 0;
long slept = 0;
for (int i = 0; i < 1000; i++) {
pacer.begin(now);
now += work;
active += work;
long delay = pacer.finish(now, ratio);
check(delay == 0 || delay >= WorkerPacer.QUANTUM_NS, "Small waits are batched");
if (delay != 0) {
// Simulate timer overshoot; future tasks must receive credit for it.
delay += overshoot;
now += delay;
slept += delay;
pacer.pauseCompleted(now);
}
}
double expectedSleep = active * (1.0 / ratio - 1);
check(Math.abs(slept - expectedSleep) <= WorkerPacer.QUANTUM_NS + overshoot + 1,
"Duty cycle retained across job sizes and timer overshoot: " + ratio + "/" + work);
}
}
}
WorkerPacer pacer = new WorkerPacer();
pacer.begin(1); pacer.finish(10_001, 0.5);
pacer.begin(20_001);
check(pacer.finish(30_001, 1) == 0, "A full-duty configuration discards old delay debt");
for (double invalid : new double[]{0, -1, Double.NaN, Double.POSITIVE_INFINITY}) {
pacer.begin(40_001);
check(pacer.finish(50_001, invalid) == 0, "Invalid ratios cannot cause unbounded waits");
}
pacer.begin(60_001); pacer.finish(70_001, 0.5);
pacer.begin(2_000_070_001L);
check(pacer.finish(2_000_080_001L, 0.5) == 0, "Idle workers discard stale delay debt");
pacer.interrupted(2_000_080_001L);
System.out.println("Worker pacing tests passed");
}
}
@@ -0,0 +1,64 @@
package dev.horizonlab.budget;
import com.seibel.distanthorizons.core.util.threading.RateLimitedThreadPoolExecutor;
import java.lang.management.ManagementFactory;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;
public class WorkerPacingBenchmark {
static class PrecisePool extends RateLimitedThreadPoolExecutor {
final ThreadLocal<dev.horizonlab.budget.WorkerPacer> pacing =
ThreadLocal.withInitial(dev.horizonlab.budget.WorkerPacer::new);
PrecisePool(java.util.concurrent.ThreadFactory factory) { super(1, factory, new LinkedBlockingQueue<>()); }
@Override protected void beforeExecute(Thread thread, Runnable job) { pacing.get().begin(System.nanoTime()); }
@Override protected void afterExecute(Runnable job, Throwable error) {
var state = pacing.get();
long wait = state.finish(System.nanoTime(), runTimeRatioConfig.get());
if (wait > 0) {
try { TimeUnit.NANOSECONDS.sleep(wait); state.pauseCompleted(System.nanoTime()); }
catch (InterruptedException interrupted) { state.interrupted(System.nanoTime()); }
}
}
}
public static void main(String[] args) throws Exception {
Class.forName("com.seibel.distanthorizons.core.config.eventHandlers.presets.ThreadPresetConfigEventHandler");
AtomicReference<Thread> worker = new AtomicReference<>();
java.util.concurrent.ThreadFactory factory = runnable -> {
Thread thread = new Thread(runnable, "Horizon probe worker"); worker.set(thread); return thread;
};
boolean precise = args.length > 3 && args[3].equals("precise");
var pool = precise ? new PrecisePool(factory) : new RateLimitedThreadPoolExecutor(1, factory, new LinkedBlockingQueue<>());
double ratio = Double.parseDouble(args[0]);
pool.runTimeRatioConfig.setApiValue(ratio, "Horizon probe");
pool.prestartAllCoreThreads();
CountDownLatch warmed = new CountDownLatch(500);
for (int i = 0; i < 500; i++) pool.execute(warmed::countDown);
warmed.await();
var bean = (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
long id = worker.get().threadId();
long initialCpu = bean.getThreadCpuTime(id);
long initialAllocation = bean.getThreadAllocatedBytes(id);
int tasks = args.length > 2 ? Integer.parseInt(args[2]) : 10_000;
long workNs = args.length > 1 ? Long.parseLong(args[1]) : 10_000;
CountDownLatch done = new CountDownLatch(tasks);
Runnable job = () -> {
long end = System.nanoTime() + workNs;
while (System.nanoTime() < end) Thread.onSpinWait();
done.countDown();
};
long started = System.nanoTime();
for (int i = 0; i < tasks; i++) pool.execute(job);
done.await();
long elapsed = System.nanoTime() - started;
long endCpu = bean.getThreadCpuTime(id);
long endAllocation = bean.getThreadAllocatedBytes(id);
long cpu = initialCpu < 0 || endCpu < initialCpu ? -1 : endCpu - initialCpu;
long allocated = initialAllocation < 0 || endAllocation < initialAllocation ? -1 : endAllocation - initialAllocation;
pool.shutdown(); pool.awaitTermination(10, TimeUnit.SECONDS);
String cpuResult = cpu < 0 ? "unavailable" : String.format(java.util.Locale.ROOT, "%.3f", cpu / (double) elapsed);
System.out.printf(java.util.Locale.ROOT,
"%s requested ratio %.3f; %d tasks of %d ns; worker CPU/wall %s; %.3f ms; worker allocation %s bytes%n",
precise ? "precise" : "upstream", ratio, tasks, workNs, cpuResult, elapsed / 1e6,
allocated < 0 ? "unavailable" : Long.toString(allocated));
}
}
+8
View File
@@ -34,6 +34,14 @@ PROFILES
heap usage exceeds 85%, then recovers gradually. Distant terrain can take longer
to appear. It does not reduce your view distance or change normal simulation.
This is a heuristic, not proof that background work caused a slow frame.
- worker-pacing: same balanced configuration, with an experimental precise worker
timer for pinned DH 3.3.4. It accumulates tiny sleep durations instead of rounding
each one down to milliseconds, and avoids per-task timestamp boxing. This can
substantially change background CPU and distant-generation completion times.
- adaptive-pacing: combines the adaptive controller with that precise worker timer.
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.
- 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.3.0",
"pack_version": "0.4.0",
"projects": {
"sodium": {
"slug": "sodium",
+31
View File
@@ -4,6 +4,7 @@
import argparse
import json
import os
import platform
from pathlib import Path
import shutil
import subprocess
@@ -32,6 +33,10 @@ def test_metrics():
SOURCE / "test/java/dev/horizonlab/budget/TerrainBudgetTest.java"]
subprocess.run(["javac", "--release", "25", "-d", str(destination), *map(str, budget_sources)], check=True)
subprocess.run(["java", "-cp", str(destination), "dev.horizonlab.budget.TerrainBudgetTest"], check=True)
worker_sources = [SOURCE / "main/java/dev/horizonlab/budget/WorkerPacer.java",
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)
def build():
@@ -87,10 +92,36 @@ def build():
return output
def benchmark_workers():
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 / "worker-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/WorkerPacingBenchmark.java")], check=True)
output = ROOT / "dist/worker-pacing-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()
for repeat in range(3):
for ratio in ["0.5", "0.05"]:
for mode in ["upstream", "precise"]:
subprocess.run(["java", "-cp", os.pathsep.join([str(tests), classpath]),
"dev.horizonlab.budget.WorkerPacingBenchmark", ratio, "10000", "50000", mode],
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")
parser.add_argument("--benchmark-workers", action="store_true", help="Measure tiny-job executor pacing; not Minecraft FPS")
args = parser.parse_args()
if args.test_only and args.benchmark_workers:
parser.error("--benchmark-workers requires the compiled mod; omit --test-only")
test_metrics()
if not args.test_only:
build()
if args.benchmark_workers:
benchmark_workers()
+6 -1
View File
@@ -19,6 +19,8 @@ PROFILES = {
"baseline": {"title": "Vanilla baseline", "mods": ["fabric-api"], "render": 12, "lod": 0, "heap": 6144},
"m2-balanced": {"title": "M2 Pro balanced", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144},
"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},
"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},
@@ -71,9 +73,12 @@ 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()}
config = ROOT / "packs/config" / f"{'m2-balanced' if profile_name == 'adaptive' else profile_name}.toml"
experiment = profile_name in ["adaptive", "worker-pacing", "adaptive-pacing"]
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()
if profile["lod"]:
if not config.exists():
raise FileNotFoundError(f"Missing verified DH profile config: {config}")