Documentation

Technical principles

Deep dive into MTR 4.1.0-beta.2 memory bottlenecks, the four-layer runtime architecture, 7 JVM properties, and all 18 Mixins/Accessors.

MTR Memory Saver v0.4.9 (Mod ID: mtr_memory_sharing; package site.benli06 / site.benli06.mixin; historical 0.3.x package dev.abenli.mtrmemory) targets Minecraft 1.21.1 (Client) / Java 21 / NeoForge 21.1.265 / Official MTR 4.1.0-beta.2.

The Java runtime sources under src/ in v0.4.9 are identical to 0.4.8 (official-nf265 candidate 920c1f83...), which passed 20 / 20 consecutive full-pack F3+T reloads, while binding fresh v0.4.9 69-check packaged verification and isolated 3 GiB in-game captures (engineering-057).

Core Results & Scope Boundary: Across all 16 heavy test packs, unmodified Official MTR 4.1.0-beta.2 still hits OutOfMemoryError at 6 GiB and 12 GiB Java heap even after model compaction and virtual-thread parallelism throttling (peaking at 11.98 GiB heap before crashing). Memory Saver lowers the minimum verified -Xmx cap to 3 GiB (-Xmx3072M, -75%+ vs 12 GiB OOM), eliminates all live CPU StoredVertexData instances (-> 0), and cut single-pass digest CPU by 19.24% in microbenchmarking. Note that -Xmx3072M limits Java heap only; total Windows Working Set / Private Commit stays around 4.25–5.86 GiB, and full 48-JVM whole-client performance plus 2-hour route endurance remain open P1 gates (see Benchmarks & validation and Stage records & hashes).

Version Evolution Overview

Official MTR 4.1.0-beta.2 Alone (> 12 GiB OOM; 9.87 GiB live shallow heap before finishing)
  -> v0.1.1 (8 GiB baseline, 79.36M StoredVertexData)
    -> v0.2.0–v0.2.9 (36B packed mesh -> DISPLAY pruning -> JSON sharing -> segmented reader -> streamed SHA-256: 5 -> 4 -> 3.5 GiB)
      -> v0.3.0 (96 MiB bounded text LRU: first 3 GiB startup + F3+T reload on Official 4.1.0-beta.2)
        -> 0.4.0–0.4.8 (Exact binary gate + 2-level 2+64 scheduler + streamed BBModel/OBJ + single-pass digest: 20/20 reloads at 3 GiB)
          -> v0.4.9 (official-nf265 formal release: unchanged 0.4.8 runtime + 69 packaged checks + 3 GiB captures)

1. Background & Native Memory Bottlenecks

1.1 Five Native Loading & Heap Bottlenecks

Heap class histograms, JFR profiles, Windows OS counters, and OOM stack traces from unmodified and early baseline clients (archived in 2026-11-05 profiling) identify five distinct bottlenecks in vanilla MTR resource loading:

Bottleneck Native Behavior Measured Evidence Direct Impact
1. Duplicate Model Parsing Multiple liveries/consists invoke BlockbenchModelLoader and ObjModelLoader independently per vehicle 651 unique .bbmodel files triggered 4,608 parses in legacy 16 packs; JFR showed BlockbenchModelLoader.lambda$loadModel$5 at 4,091 / 6,457 startup and 4,187 / 6,064 reload samples Re-reads, parses, and builds identical source models repeatedly
2. Uncompressed CPU Vertices NewOptimizedModelGroup retains per-vertex StoredVertexData and nested java.awt.Color objects v0.1.1 histogram held 79,359,867 live StoredVertexData; vanilla 12 GiB OOM held 76.64M vertices (3.43 GiB) + 75.31M Color (2.24 GiB) Object headers and references far exceed raw float buffers and trigger heavy Full GCs
3. Non-Display Matrix Metadata Retains StoredMatrixTransformations for all model parts even though rendering only reads PartType.DISPLAY v0.2.0 histogram recorded 2,494,194 instances (~753 MiB shallow heap) Dead transformation arrays linger in tenured heap
4. Duplicate Vehicle Config JSON VehicleModel.<init> runs Gson separately for every vehicle’s identical property/position JSON v0.2.1 histogram measured 385,752,224 B (385.75 MB) in core MTR Gson objects Identical JSON DOM trees duplicated across hundreds of vehicles
5. Unbounded Text Cache & String Spikes RESOURCE_CACHE accumulates all text; IOUtils.toString, String.getBytes, and String.join allocate contiguous arrays 2,000,187,675 code units per reload (592,010,155 B even compressed); concurrent OBJ/BBModel reads Triggers OutOfMemoryError at 3 GiB on startup (v0.2.9) or repeated reloads (0.4.7 4th, initial 0.4.8 7th)

1.2 Why 0.3.x Was Refactored into 0.4.x

Although v0.3.0 cut startup heap to 3 GiB via the 96 MiB bounded LRU, engineering review (see Runtime contract & review) uncovered four structural defects requiring a clean scheduler and I/O redesign in 0.4.x:

  1. Unresolved Futures on Parse Failures: Native BlockbenchModelLoader logs parse exceptions and returns without calling setModelLoaded(), stranding 0.3.x shared CompletableFuture entries forever.
  2. Inverted Cache Lookup Order: 0.3.x restored text from the text cache and hashed it before checking the Blockbench source cache, paying I/O and allocation costs even on cache hits.
  3. Non-Atomic Reloads & Unbounded Queueing: Clearing maps and bumping epochs were not atomic under one lock, and unthrottled work queues could capture large strings early.
  4. Version-String-Only Dependency Checks: A modified MTR JAR sharing the exact 4.1.0-beta.2 version string bypassed loader checks and risked NoSuchMethodError or silent corruption at runtime.

1.3 Two 16-Pack Test Fixtures

Cross-version numbers span two distinct 16-pack test fixtures with different declaration counts and resource sizes:

Fixture Generation Applicable Versions Registration Scale Per-Epoch Parse Load Largest Referenced Input & Notes
Legacy 16-Pack Repair Fixture v0.1.1 – v0.3.0 2,541 vehicles (290 objects / 23 rails) 4,608 Blockbench requests / 651 unique parses Includes legacy 02a05_arknight.bbmodel (65,255,687 UTF-8 bytes); see v0.3.0 acceptance
MTR 4.1 Native-Catalogue 16 Packs 0.4.x Official (0.4.5–0.4.9) 1,092 declarations / 1,091 unique IDs 651 unique BBModel + 974 OBJ parses per epoch Largest BBModel 13,141,932 B; largest OBJ mtr:hxd3d/25t__doors_b351ad1ecabb.obj (102,035,449 bytes/code units, SHA-256 e43f1b6b...); legacy 65 MB BBModel is used for single-input microbenchmarks

2. Four-Layer Runtime Architecture

The 0.4.9 runtime operates across four decoupled layers—binary identity gating, two-level single-flight scheduling, streaming snapshots with a bounded text LRU, and lossless packed meshes with shared config JSON—while preserving native geometry, boxes AABB collision boxes, displays, and door logic verbatim.

MTR Memory Saver Four-Layer Runtime Architecture

2.1 Exact Binary Fingerprint Gate (CompatibilityPlugin / BinaryFingerprint)

  • Sources: CompatibilityPlugin.java, BinaryFingerprint.java.
  • Mechanism: During Mixin onLoad, reads the pinned MTR hash from embedded /mtr-memory-target.json, locates the on-disk JAR via LoadingModList.get().getModFileById("mtr"), and streams a full-file SHA-256 with a 65,536-byte buffer.
  • Hard Abort Fix (0.4.4 -> 0.4.5): Throwing a plain Exception in onLoad caused Mixin to log a warning and skip all Mixins while continuing startup. Since 0.4.5, any mismatch throws Mixin’s MixinInitialisationError and halts startup cleanly with exit code 1 before vehicle registration begins.

2.2 Two-Level Single-Flight Cache & Bounded Concurrency (GenerationWorkCache)

Implemented in GenerationWorkCache.java, backing SharedBlockbenchCache.java and StreamedObjCache.java:

  1. L1 Path-Key Fast Path:
    • Keys combine (providerIdentity, modelId, textureId, flipV) via ResourceSourceKey.java using System.identityHashCode and == to distinguish packs and provider instances.
    • An L1 hit returns the existing CompletableFuture immediately, skipping disk reads, UTF-16 decoding, and SHA-256 hashing.
  2. L2 Content Deduplication & Permit-Release Order:
    • SharedBlockbenchCache hashes the snapshot and forms Content(sha256Utf8Digest, textureId, flipV). If an owner already exists for that content key, the follower closes its snapshot channel and exits ReadAdmission inside try (var owner = prepared.owner()) before attaching to the owner future, preventing permit-hold deadlocks.
    • StreamedObjCache binds L2 to ResourceSourceKey intentionally because .obj files resolve .mtl and texture references relative to their path; identical .obj text at different paths can bind different materials.
  3. Bounded Queue, Native Tickets & Terminal Failure Handling:
    • Uses a fair Semaphore(workerCount + queueCapacity, true) (default 2 + 64 = 66 slots), bounded ArrayBlockingQueue, MTR-memory-parse daemon workers, and MTR-memory-timeout (300 s). Enqueued descriptors carry lightweight Supplier<Prepared<C, V>> objects without capturing raw text.
    • Each task increments ModelLoaderBase::parseStarted under lock and releases its permit + parseFinished only when Work.release() runs upon actual native exit. A timed-out future whose non-interruptible native parser is still running therefore shows pending == 0 with outstanding > 0.
    • Blockbench parsing uses JsonParser.parseReader(...).getAsJsonObject() directly (rejecting empty or non-object JSON fallbacks) and verifies via ModelLoaderCompletionMixin.java that native code invoked setModelLoaded() for the matching source before publishing; preserveLateFailure uses a visited-set BFS to avoid exception cycles.
  4. Atomic Generation Retirement & Key Release:
    • beginReload() marks the active Epoch retired = true, swaps in a new Epoch, clears indexes, and cancels pending futures under one lock; finishRegistration() clears retain and removes completed index keys while facades hold their own model/display references.

2.3 Streaming Snapshots, Single-Pass Digest & Bounded LRU

  1. Scoped Snapshot Wrapping (SnapshotResourceProvider.java):
    • ResourceTextReadMixin.java uses @ModifyArg at the 5 audited official ResourceProvider sites (RailResource.<init>, CustomResourcesConverter.convertRails, convertObjects, CustomResourceLoader.lambda$reload$8, lambda$reload$10) to wrap NativeResourceSnapshots.java. Custom external providers and Keys.DEBUG fall back to original provider.get(id) behavior.
  2. Single-Channel Snapshots & engineering-055 Single-Pass Digest (Utf16TextSnapshot.java & ResourceTextSnapshot.java):
    • Allocates .utf16 temporary files with CREATE_NEW | READ | WRITE | DELETE_ON_CLOSE (rw------- on POSIX), picking fresh random names on collision. Writing, workspace waiting, rewinding, and consumption share one handle; on abrupt Runtime.halt, the Windows kernel closes the last handle and deletes the file automatically.
    • Single-Pass Hashing: Earlier 0.4.8 builds re-read the disk channel after writing to compute SHA-256; engineering-055 wraps InputStreamReader in a FilterReader inside ResourceTextDigest.sha256(Reader) so length checks (admission.checkLength), big-endian UTF-16 disk writes, and UTF-8 SHA-256 hashing happen in one pass (-19.24% thread CPU and -19.37% wall time on the 65.26 MB BBModel benchmark).
    • Exact Encoding Parity: Above 4,096 code units, fixed 4,096-char / 8,192-byte buffers with CodingErrorAction.REPLACE and CharBuffer.compact() carry split surrogate pairs across chunks, matching String.getBytes(UTF_8) byte for byte.
    • Zero Whole-Input String Concatenation: BBModel reads via JsonParser.parseReader(snapshot.reader()); OBJ and .mtl files stream through 8 KiB ReaderInputStream (snapshot.utf8Stream()) into native ObjReader.read and MtlReader.read, closing the .obj snapshot before calling @Invoker("loadModel").
  3. Fair-Share Spill Workspace for Non-Model readResource (TextWorkspace.java & SegmentedResourceText.java):
    • Callers still expecting String enter ReadAdmission.java (default 2 concurrent) and claim share = budget / readers from TextWorkspace.
    • Once 4 * length > share, 8,192-char in-memory segments spill into Utf16TextSnapshot, segments are cleared, and share is released before waiting in FIFO order for the exact 4 * length restoration budget—preventing mutual deadlock among concurrent large reads. StrictResourceText.java propagates real I/O and limit errors on existing resources.
  4. Bounded Compressed Text LRU (BoundedTextCache.java):
    • Default 96 MiB (100,663,296 B, configured in CompressedResourceTextCache.java; v0.3.0 used maxMemory / 32).
    • Conservative weight: weight = 192 + 2 * key.length() + (packed != null ? packed.length : 2 * length). Uncompressed items exceeding total budget bypass caching; eligible items attempt non-blocking tryClaim(5 * length) and compress with Deflater.BEST_SPEED, aborting via NoGain if compressed bytes >= value.length(). First readers keep the original String; cache hits unpack under 4 * length workspace permits.

2.4 Lossless 36B Packed Vertices, Display Pruning & Shared JSON

  1. Lossless Chunked Vertices (PackedVertices.java & PackedModelGroupStore.java):
    • Encodes each vertex as 36 bytes (9 raw 32-bit ints via Float.floatToRawIntBits for x, y, z, argb, u, v, nx, ny, nz), compressed with Deflater.BEST_SPEED above a 1,024-vertex (36,864 B) staging cap.
    • appendTransformed replays exact native (float) narrowing and arithmetic order (including -0.0f semantics) alongside PackedModelGroupOperations.java for identical boxes AABB bounds; PackedVertexEmitter.java unpacks directly into NewOptimizedModel with OverlayTexture.NO_OVERLAY and IGui.DEFAULT_LIGHT.
  2. Display-Only Transform Retention (DisplayRetention.java & SharedBlockbenchLoader.java):
    • DisplaySelectionMixin gathers PartType.DISPLAY names during ModelProperties creation; the facade synchronizes whenComplete publication and selectDisplays pruning under one object lock regardless of arrival order.
  3. Shared Vehicle Config JSON (VehicleJsonCache.java):
    • Shares non-empty JsonObject trees per epoch by UTF-8 SHA-256 inside read admission (falling back to native on empty/error cases), relying on native JsonReader copying top-level keys into per-vehicle maps while reading child nodes immutably.

Note on Custom Performance v6: src/targets/v6/ retains a separate compile target for custom Performance v6 (8bd419bd...) handling its int ARGB vertex color, ensureMutable(), builtModels cache, and V6LoaderLifecycleMixin.java close guard. New v6 validation is paused and 0.4.8 OBJ streaming was not ported there.


3. Target Matrix, JVM Properties & Mixin Inventory

3.1 Build Target Matrix

Defined authoritatively in config/targets.json and gradle.properties:

Target Preset (-Ptarget=...) Pinned MTR Binary (Full SHA-256 in Stage records) NeoForge Current Status
official-nf265 (default & CI release target) Official 4.1.0-beta.2 (ff2b753d...) 21.1.265 v0.4.9 Formal Release (3d2a1407...): identical src/ runtime to 0.4.8 (20/20 reloads), 106 Java tests, 69 packaged checks, wrong-binary exit 1, 3 GiB captures; 48-JVM whole-client benchmark pending
official-nf248 Official 4.1.0-beta.2 (ff2b753d...) 21.1.248 Historical comparison target (excluded from 0.4.8 / 0.4.9 releases); 0.4.8 943b3d45... passed 20/20 reloads and 12-JVM Spark trial
v6-nf248 / v6-nf265 Custom Performance v6 (8bd419bd...) 21.1.248 / 21.1.265 Historical presets; new validation and releases paused

3.2 JVM System Properties & Accounting Boundaries

All subsystem limits are read once at initialization from -D system properties. Malformed, non-positive, or inconsistent values throw IllegalArgumentException immediately (see ReadAdmission.java and Runtime contract & review):

JVM System Property 3 GiB (-Xmx3072M) Default Constraints & Meaning
mtr.memory.readers 2 Concurrent read / unpack / module-parse scopes (>= 1, reentrant on same thread)
mtr.memory.parsers 2 GenerationWorkCache worker threads (>= 1)
mtr.memory.parseQueue 64 Extra lightweight descriptor slots (>= 1; total slots = parsers + parseQueue)
mtr.memory.parseTimeoutSeconds 300 Queue-admission and submitted-work timeout in seconds (>= 1)
mtr.memory.maxTextCodeUnits 201,326,592 (min(Integer.MAX_VALUE - 8, maxHeap / 16)) Strict per-resource UTF-16 code unit limit (0.4.5 used 100,663,296)
mtr.memory.textWorkspaceBytes 805,306,368 (max(maxHeap / 4, 4 * maxTextCodeUnits)) Shared transient payload budget; must satisfy >= 4 * maxTextCodeUnits
mtr.memory.textCacheBytes 100,663,296 (96 MiB; v0.3.0 used mtr.memory.resourceTextCacheBytes) Conservative admitted weight ceiling in BoundedTextCache (0 disables caching)

Baseline JVM flags used across 3 GiB client tests:

-Xms512M -Xmx3072M -XX:+UseG1GC

Memory Accounting Boundary: These budgets track admitted LRU weight, transient workspace reservations, and concurrency slots only. Caller-retained values, native Gson/OBJ graphs, uncollected garbage, OpenGL/driver VRAM, and Windows Working Set / Private Commit are outside these budgets. Never sum Java Heap Used, Working Set, Private Commit, and VRAM; jstat and OS polling observe lower bounds at sample points only.

3.3 Mixin & Accessor Inventory (18 Official Targets)

Expand: Complete list of all 18 Official Mixins & Accessors in v0.4.9 (13 common + 5 official)
Scope Mixin / Accessor Target MTR Class & Hook Responsibility
Common VehicleModelFactoryMixin VehicleModel.getModelLoaderBase (HEAD) Intercepts .bbmodel loads and returns per-consumer SharedBlockbenchCache.get facades
Common BlockbenchParseExecutorMixin BlockbenchModelLoader.loadModel (ExecutorService.submit) Executes parser Runnable inline when caller holds OWNED_PARSE; foreign callers keep native executor
Common ModelLoaderCompletionMixin ModelLoaderBase.setModelLoaded (RETURN) Reports native completion to OWNED_PARSE, distinguishing publication from caught exceptions
Common ModelLoaderAccess ModelLoaderBase accessors Exposes nameToNewOptimizedModelGroup and nameToRawModelDisplayParts
Common DisplaySelectionMixin VehicleModel.createModelSupplier Collects PartType.DISPLAY part names and triggers display pruning
Common DisplayPartAccess ModelPropertiesPartSchema Accesses part type and part name collections
Official PackedModelGroupMixin NewOptimizedModelGroup (add / merge / build) Replaces CPU vertex lists with PackedModelGroupStore and emits vertices on GPU build
Common VehicleJsonCacheMixin VehicleModel.<init> (Utilities.parseJson) Deduplicates non-empty Gson JsonObject trees by UTF-8 SHA-256
Common VehicleJsonEpochMixin CustomResourceLoader.reload (HEAD / RETURN) Clears vehicle JSON cache across reload generations
Common CompressedResourceTextMixin CustomResourceLoader.readResource & reload Binds RESOURCE_CACHE to CompressedResourceTextCache and logs reload bounds
Common SegmentedResourceTextMixin ResourceManagerHelper.lambda$readResource$1 (IOUtils.toString) Replaces IOUtils.toString with workspace-bounded segmented reader
Common ResourceReloadMixin CustomResourceLoader.reload (HEAD / RETURN) Coordinates generation transitions, workspace/LRU logging, and native collection cleanup
Common SourceLifetimeMixin CustomResourceLoader.reload (HEAD / RETURN) Calls SharedBlockbenchCache.beginReload() and finishRegistration()
Official ResourceTextReadMixin CustomResourceLoader.reload (5 ResourceProvider sites) & lambda$readResource$22 Wraps the 5 audited sites in NativeResourceSnapshots.wrap; propagates real read failures via StrictResourceText
Official ObjVehicleFactoryMixin VehicleModel.getModelLoaderBase (HEAD) Routes non-DEBUG snapshot-backed .obj loads to StreamedObjCache
Official ObjModelInputMixin ObjModelLoader Streams .obj / .mtl inputs and delegates grouping to native ObjSplitting.splitByGroups via @Invoker("loadModel")
Official ObjSourceLifetimeMixin CustomResourceLoader.reload (HEAD / RETURN) Manages StreamedObjCache reload generations
Official VertexColorMixin StoredVertexData.write (NEW java/awt/Color) Reuses Color.WHITE for (255, 255, 255, 255)

The paused v6 target additionally carries target-specific PackedModelGroupMixin and V6LoaderLifecycleMixin.

Further Reading