diff --git a/README.md b/README.md index 914723970..df85af41d 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Client-first performance research for Minecraft Java **26.3**, preserving vanill ## Play on your Mac -Download **horizon-mac-starter-0.5.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.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. 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. @@ -41,7 +41,7 @@ Press **F8** during gameplay to start a 120-second recording, or again to stop e 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. -The instance's `horizon-benchmarks/` folder receives JSON/CSV frame and integrated-server tick timings: average FPS, slowest-1%-average FPS, p95/p99 durations, stalls, JVM heap/GC, GPU/backend/driver and render settings. Frames include presentation/limiting waits and exclude menus/pauses/unfocused time. Tick `meanRate` is execution capacity, **not TPS**; observed tick counts are separate. Heap is **not process RSS or unified GPU memory**. +The instance's `horizon-benchmarks/` folder receives JSON/CSV frame and integrated-server tick timings: average FPS, slowest-1%-average FPS, p95/p99 durations, stalls, JVM heap/GC, sampled process RSS when available, GPU/backend/driver and render settings. Frames include presentation/limiting waits and exclude menus/pauses/unfocused time. Tick `meanRate` is execution capacity, **not TPS**; observed tick counts are separate. Resident process memory is sampled on a shared background thread only during recordings; it includes native resident pages, while heap measures JVM objects. Neither is a complete measurement of unified GPU memory. [Memory measurement details](docs/process-memory.md). ```sh python3 tools/compare_benchmarks.py baseline-frames.json optimized-frames.json --strict diff --git a/docs/playable-validation.md b/docs/playable-validation.md index d5135748f..57790bbf3 100644 --- a/docs/playable-validation.md +++ b/docs/playable-validation.md @@ -22,6 +22,22 @@ Version 0.2.0 targets Minecraft 26.3 / Fabric 0.19.5 / Java 25. This is an initi ## Interpretation limits +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 +120 successful RSS samples, a peak of about 2,643 MiB, and a last-sample age under +800 ms. The runtime JAR matches the release candidate byte-for-byte. After capture, +the sampler thread waits without further scheduled reads. Native-read tests also +pass on hosted Windows x64, Linux x64 and Apple Silicon macOS 26; unsupported +reader behavior preserves timing samples and omits unavailable RSS fields. +These numbers validate reporting in this particular software-rendered workload, +not a RAM reduction or a prediction of the user's Mac memory use. + +The 0.5.0 offline viewer passed Chromium checks using real frame/tick JSON and CSV +files, charts, exports, malformed inputs, kind mismatches, escaped profile labels, +and mobile layout. It is self-contained and has no network dependencies. Its game +runtime classes are identical to 0.4.0, apart from mod version metadata. + 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 diff --git a/docs/process-memory.md b/docs/process-memory.md new file mode 100644 index 000000000..9d6837672 --- /dev/null +++ b/docs/process-memory.md @@ -0,0 +1,44 @@ +# Measuring resident process memory + +Horizon Lab 0.6.0 records process RSS alongside JVM heap and nonheap pools. RSS +counts resident pages belonging to the Minecraft process, including native +allocations and mapped pages. It helps detect cases where reducing heap use +merely moves memory elsewhere. It is not unique physical-memory ownership or +a complete accounting of GPU allocations, shared pages, compressed memory, +swap, or Apple Silicon unified memory. Do not add heap to RSS: heap pages can +already be included in it. + +Minecraft 26.3 already ships OSHI 6.9.0 and JNA on both client and server. The +original mod uses those dependencies without embedding them. Native reader +initialization and refresh happen on a low-priority daemon thread, never on +the render or server-tick thread. One reader serves overlapping frame and +tick recordings. Reads run about once per second only while recordings are +active; the scheduler stops polling when the last recording finishes. Ordinary +gameplay without a benchmark performs no resident-memory reads. + +Reports include these optional schema-1 fields: + +| Field | Meaning | +| --- | --- | +| `process_rss_peak_sampled_bytes` | Largest successful resident-memory sample during this recording | +| `process_rss_last_sampled_bytes` | Last successful sample, which can precede recording completion | +| `process_rss_samples` | Number of successful samples delivered to this recording | +| `process_rss_sample_interval_ms` | Requested 1,000 ms interval; reads can take longer | +| `process_rss_last_sample_age_ms` | Time from the last successful sample to report completion | + +Unsupported or failed reads leave these fields absent if no sample succeeded; +zero is not used as a substitute. Frames and ticks continue recording. A read +that completes after a recording finishes is ignored. Sampled peaks can miss +brief spikes, and the initial read can be delayed by native-library startup. + +The offline viewer compares RSS separately from heap/nonheap and warns about +stale resident samples. Keep recording duration, workload and warm-up matched +when comparing peaks. Process CPU counters cover the whole process over the +recording wall time, including native work and the integrated server; they do +not identify which thread or mod caused CPU use. + +The native-read test exercises the real library, overlapping recordings, +background execution, idle cancellation and unavailable-reader behavior on +the build platform. This validates measurement availability, not an FPS or +RAM optimization result. Real game integration and platform results are +recorded in the release validation document after they finish. diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/HorizonLab.java b/mods/horizon-lab/src/main/java/dev/horizonlab/HorizonLab.java index 68fca6773..ffd88ed31 100644 --- a/mods/horizon-lab/src/main/java/dev/horizonlab/HorizonLab.java +++ b/mods/horizon-lab/src/main/java/dev/horizonlab/HorizonLab.java @@ -4,6 +4,8 @@ import com.mojang.brigadier.arguments.IntegerArgumentType; import com.mojang.brigadier.arguments.StringArgumentType; import dev.horizonlab.metrics.Recording; import dev.horizonlab.metrics.Reports; +import dev.horizonlab.metrics.ProcessMemoryMonitor; +import dev.horizonlab.metrics.ResidentMemory; import java.nio.file.Path; import java.util.Map; import net.fabricmc.api.ModInitializer; @@ -20,6 +22,7 @@ public final class HorizonLab implements ModInitializer { private static volatile Recording ticks; @Override public void onInitialize() { + ProcessMemoryMonitor.configure(new ResidentMemory()); CommandRegistrationCallback.EVENT.register((dispatcher, context, selection) -> dispatcher.register( Commands.literal("horizonserver") .requires(source -> source.permissions().hasPermission(Permissions.COMMANDS_ADMIN)) diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/metrics/ProcessMemoryMonitor.java b/mods/horizon-lab/src/main/java/dev/horizonlab/metrics/ProcessMemoryMonitor.java new file mode 100644 index 000000000..6f1e39039 --- /dev/null +++ b/mods/horizon-lab/src/main/java/dev/horizonlab/metrics/ProcessMemoryMonitor.java @@ -0,0 +1,53 @@ +package dev.horizonlab.metrics; + +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.function.LongSupplier; + +/** One background reader for this process, active only while recordings exist. */ +public final class ProcessMemoryMonitor { + private static final Set ACTIVE = ConcurrentHashMap.newKeySet(); + private static final ScheduledExecutorService EXECUTOR = Executors.newSingleThreadScheduledExecutor(task -> { + Thread thread = new Thread(task, "Horizon process memory"); + thread.setDaemon(true); + thread.setPriority(Thread.MIN_PRIORITY); + return thread; + }); + private static volatile LongSupplier reader; + private static ScheduledFuture polling; + + private ProcessMemoryMonitor() {} + + public static synchronized void configure(LongSupplier residentMemoryReader) { + if (!ACTIVE.isEmpty()) throw new IllegalStateException("Configure before starting recordings"); + reader = residentMemoryReader; + } + + static synchronized void track(Recording recording) { + if (reader == null) return; + ACTIVE.add(recording); + if (polling == null) polling = EXECUTOR.scheduleWithFixedDelay(ProcessMemoryMonitor::poll, 0, 1, TimeUnit.SECONDS); + } + + static synchronized void untrack(Recording recording) { + ACTIVE.remove(recording); + if (ACTIVE.isEmpty() && polling != null) { + polling.cancel(false); + polling = null; + } + } + + private static void poll() { + Recording[] recordings = ACTIVE.toArray(Recording[]::new); + if (recordings.length == 0) return; + long bytes; + try { bytes = reader.getAsLong(); } + catch (RuntimeException | LinkageError unavailable) { return; } + if (bytes <= 0) return; + for (Recording recording : recordings) recording.residentMemory(bytes); + } +} diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/metrics/Recording.java b/mods/horizon-lab/src/main/java/dev/horizonlab/metrics/Recording.java index 74ca6440a..efd7ab103 100644 --- a/mods/horizon-lab/src/main/java/dev/horizonlab/metrics/Recording.java +++ b/mods/horizon-lab/src/main/java/dev/horizonlab/metrics/Recording.java @@ -30,6 +30,11 @@ public final class Recording { private long peakHeap; private long peakNonHeap; private int resourceSamples; + private long residentEnd; + private long residentPeak; + private int residentSamples; + private long residentSampleNs; + private boolean finished; public Recording(String label, String kind, Path output, int seconds, Map context) { if (seconds < 1 || seconds > 600) throw new IllegalArgumentException("Duration must be 1..600 seconds"); @@ -44,10 +49,11 @@ public final class Recording { this.initialGcMs = gcMs(); this.initialCpuNs = operatingSystem == null ? -1 : operatingSystem.getProcessCpuTime(); sampleResources(startedNs); + ProcessMemoryMonitor.track(this); } public synchronized void add(long ns) { - if (ns <= 0) return; + if (ns <= 0 || finished) return; long now = System.nanoTime(); if (now >= nextResourceSampleNs) sampleResources(now); if (count == samples.length) { dropped++; return; } @@ -58,6 +64,8 @@ public final class Recording { public synchronized void players(int players) { peakPlayers = Math.max(players, peakPlayers); } public synchronized Snapshot finish() { + finished = true; + ProcessMemoryMonitor.untrack(this); sampleResources(System.nanoTime()); Map metadata = new LinkedHashMap<>(context); metadata.put("label", label); @@ -83,6 +91,13 @@ public final class Recording { metadata.put("nonheap_used_peak_sampled_bytes", peakNonHeap); metadata.put("resource_samples", resourceSamples); metadata.put("resource_sample_interval_ms", 1000); + if (residentSamples > 0) { + metadata.put("process_rss_last_sampled_bytes", residentEnd); + metadata.put("process_rss_peak_sampled_bytes", residentPeak); + metadata.put("process_rss_samples", residentSamples); + metadata.put("process_rss_sample_interval_ms", 1000); + metadata.put("process_rss_last_sample_age_ms", (System.nanoTime() - residentSampleNs) / 1e6); + } long endCpuNs = operatingSystem == null ? -1 : operatingSystem.getProcessCpuTime(); if (initialCpuNs >= 0 && endCpuNs >= initialCpuNs) { double cpuSeconds = (endCpuNs - initialCpuNs) / 1e9; @@ -94,6 +109,14 @@ public final class Recording { return new Snapshot(label, kind, output, Arrays.copyOf(samples, count), metadata); } + synchronized void residentMemory(long bytes) { + if (finished || bytes <= 0) return; + residentEnd = bytes; + residentPeak = Math.max(residentPeak, bytes); + residentSamples++; + residentSampleNs = System.nanoTime(); + } + private void sampleResources(long now) { peakHeap = Math.max(peakHeap, memory.getHeapMemoryUsage().getUsed()); peakNonHeap = Math.max(peakNonHeap, memory.getNonHeapMemoryUsage().getUsed()); diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/metrics/Reports.java b/mods/horizon-lab/src/main/java/dev/horizonlab/metrics/Reports.java index 743af6d05..b1c492c1b 100644 --- a/mods/horizon-lab/src/main/java/dev/horizonlab/metrics/Reports.java +++ b/mods/horizon-lab/src/main/java/dev/horizonlab/metrics/Reports.java @@ -30,7 +30,7 @@ public final class Reports { report.put("stats", stats); report.put("samples_file", csv.getFileName().toString()); report.put("note", snapshot.kind().equals("frames") - ? "Frame start intervals include frame limiting and presentation waits; menus, pauses and unfocused frames are excluded. Not GPU timings or process RSS." + ? "Frame start intervals include frame limiting and presentation waits; menus, pauses and unfocused frames are excluded. Not GPU timings. Process RSS, when available, is sampled separately." : "Tick execution durations exclude scheduler sleep. meanRate is execution capacity, not observed TPS."); Path json = snapshot.output().resolve(name + ".json"); Files.writeString(json, new GsonBuilder().setPrettyPrinting().create().toJson(report) + "\n"); diff --git a/mods/horizon-lab/src/main/java/dev/horizonlab/metrics/ResidentMemory.java b/mods/horizon-lab/src/main/java/dev/horizonlab/metrics/ResidentMemory.java new file mode 100644 index 000000000..f4c98b748 --- /dev/null +++ b/mods/horizon-lab/src/main/java/dev/horizonlab/metrics/ResidentMemory.java @@ -0,0 +1,20 @@ +package dev.horizonlab.metrics; + +import java.util.function.LongSupplier; +import oshi.SystemInfo; +import oshi.software.os.OSProcess; + +/** Uses Minecraft's existing OSHI dependency; initialization stays on the sampler thread. */ +public final class ResidentMemory implements LongSupplier { + private OSProcess process; + private boolean initialized; + + @Override public long getAsLong() { + if (!initialized) { + initialized = true; + var os = new SystemInfo().getOperatingSystem(); + process = os.getProcess(os.getProcessId()); + } + return process != null && process.updateAttributes() ? process.getResidentSetSize() : -1; + } +} diff --git a/mods/horizon-lab/src/main/resources/fabric.mod.json b/mods/horizon-lab/src/main/resources/fabric.mod.json index e2354e2fd..4fcd1306c 100644 --- a/mods/horizon-lab/src/main/resources/fabric.mod.json +++ b/mods/horizon-lab/src/main/resources/fabric.mod.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, "id": "horizonlab", - "version": "0.5.0", + "version": "0.6.0", "name": "Horizon Lab", "description": "Client frame pacing and server tick measurements for reproducible optimization experiments.", "authors": [ diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/metrics/MetricsTest.java b/mods/horizon-lab/src/test/java/dev/horizonlab/metrics/MetricsTest.java index 570af7235..87c82ce58 100644 --- a/mods/horizon-lab/src/test/java/dev/horizonlab/metrics/MetricsTest.java +++ b/mods/horizon-lab/src/test/java/dev/horizonlab/metrics/MetricsTest.java @@ -32,6 +32,20 @@ public final class MetricsTest { check((double) snapshot.metadata().get("process_cpu_seconds") >= 0, "CPU time is nonnegative"); } check(!snapshot.label().contains("/"), "safe report filename"); + check(!snapshot.metadata().containsKey("process_rss_peak_sampled_bytes"), "unavailable RSS is absent, not zero"); + Recording resident = new Recording("memory", "frames", Path.of("unused"), 10, Map.of()); + resident.residentMemory(-1); + resident.residentMemory(100); + resident.residentMemory(200); + resident.residentMemory(150); + resident.add(10_000_000); + var residentSnapshot = resident.finish(); + resident.residentMemory(999); + resident.add(10_000_000); + check(residentSnapshot.metadata().get("process_rss_last_sampled_bytes").equals(150L), "last RSS is not called end memory"); + check(residentSnapshot.metadata().get("process_rss_peak_sampled_bytes").equals(200L), "RSS peak can exceed last sample"); + check(residentSnapshot.metadata().get("process_rss_samples").equals(3), "invalid memory samples excluded"); + check(resident.finish().samples().length == 1, "late samples do not change a finished recording"); System.out.println("Metrics tests passed."); } diff --git a/mods/horizon-lab/src/test/java/dev/horizonlab/metrics/ResidentMemoryTest.java b/mods/horizon-lab/src/test/java/dev/horizonlab/metrics/ResidentMemoryTest.java new file mode 100644 index 000000000..01a623e73 --- /dev/null +++ b/mods/horizon-lab/src/test/java/dev/horizonlab/metrics/ResidentMemoryTest.java @@ -0,0 +1,59 @@ +package dev.horizonlab.metrics; + +import java.nio.file.Path; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +/** Real native reads on each CI platform; also checks idle and failure behavior. */ +public final class ResidentMemoryTest { + public static void main(String[] args) throws Exception { + ResidentMemory reader = new ResidentMemory(); + AtomicInteger calls = new AtomicInteger(); + CountDownLatch threeReads = new CountDownLatch(3); + Thread caller = Thread.currentThread(); + ProcessMemoryMonitor.configure(() -> { + if (Thread.currentThread() == caller) throw new AssertionError("Memory read on recording thread"); + long rss = reader.getAsLong(); + if (rss <= 0) throw new AssertionError("Native resident memory unavailable on this runner"); + calls.incrementAndGet(); + threeReads.countDown(); + return rss; + }); + try { + Thread.sleep(50); + if (calls.get() != 0) throw new AssertionError("Reader ran without a recording"); + Recording frames = new Recording("rss", "frames", Path.of("unused"), 10, Map.of()); + Recording ticks = new Recording("rss", "ticks", Path.of("unused"), 10, Map.of()); + // The third read starts after the second dispatch completed, so both recordings have data. + if (!threeReads.await(10, TimeUnit.SECONDS)) throw new AssertionError("Background reads did not complete"); + var frameReport = frames.finish(); + var tickReport = ticks.finish(); + for (var report : new Recording.Snapshot[]{frameReport, tickReport}) { + var metadata = report.metadata(); + long last = (long) metadata.get("process_rss_last_sampled_bytes"); + long peak = (long) metadata.get("process_rss_peak_sampled_bytes"); + if (last <= 0 || peak < last) throw new AssertionError("Invalid resident memory report"); + System.out.println(report.kind() + " RSS last=" + last + " peak=" + peak + " samples=" + metadata.get("process_rss_samples")); + } + int idleCalls = calls.get(); + Thread.sleep(1100); + if (calls.get() != idleCalls) throw new AssertionError("Reader kept polling after recordings finished"); + CountDownLatch failedRead = new CountDownLatch(1); + ProcessMemoryMonitor.configure(() -> { + failedRead.countDown(); + throw new IllegalStateException("Unsupported native reader"); + }); + Recording unavailable = new Recording("unsupported", "frames", Path.of("unused"), 10, Map.of()); + unavailable.add(1_000_000); + if (!failedRead.await(10, TimeUnit.SECONDS)) throw new AssertionError("Unavailable reader was not attempted"); + var unavailableReport = unavailable.finish(); + if (unavailableReport.samples().length != 1 || unavailableReport.metadata().containsKey("process_rss_peak_sampled_bytes")) + throw new AssertionError("Unavailable memory disrupted recording or was reported as zero"); + System.out.println("Background resident-memory checks passed."); + } finally { + ProcessMemoryMonitor.configure(null); + } + } +} diff --git a/packs/START-HERE.txt b/packs/START-HERE.txt index eb7dd71cc..d725541bc 100644 --- a/packs/START-HERE.txt +++ b/packs/START-HERE.txt @@ -73,7 +73,11 @@ MEASURE ON YOUR M2 PRO 4. Open Prism's instance Minecraft folder > horizon-benchmarks. Each run writes frames JSON/CSV and integrated-server ticks JSON/CSV. They include average FPS, slowest-1%-average FPS, p95/p99 frame durations, stalls, sampled peak JVM heap, - process CPU time and GC data. Heap is sampled once per second during gameplay; + process CPU time, process resident memory (RSS) when available, and GC data. + RSS reads run once per second on a shared background thread during recordings. + They include resident native pages; this is not a complete GPU/unified-memory + measurement. Last RSS is the last sample, not necessarily the finish time. + Heap is sampled once per second during gameplay; shorter peaks can be missed. CPU measurement spans the whole recording. Menus, pauses and unfocused frames are excluded. Tick execution time is not the observed TPS. JVM heap is not whole-process memory or unified GPU memory. diff --git a/packs/mods.lock.json b/packs/mods.lock.json index 7157a8c72..f81ae8dff 100644 --- a/packs/mods.lock.json +++ b/packs/mods.lock.json @@ -3,7 +3,7 @@ "minecraft": "26.3", "java_major": 25, "fabric_loader": "0.19.5", - "pack_version": "0.5.0", + "pack_version": "0.6.0", "projects": { "sodium": { "slug": "sodium", diff --git a/tools/Compare-Benchmarks.html b/tools/Compare-Benchmarks.html index 6ed2c25bf..1957b453f 100644 --- a/tools/Compare-Benchmarks.html +++ b/tools/Compare-Benchmarks.html @@ -26,7 +26,7 @@

-
No installation, account or network access is needed. Repeat at least three matched runs and test fresh terrain separately from a warm cache. JVM memory excludes some native and GPU allocations.
+
No installation, account or network access is needed. Repeat at least three matched runs and test fresh terrain separately from a warm cache. Heap/nonheap exclude native allocations. Process RSS is not a complete GPU/unified-memory measurement.