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.2still hitsOutOfMemoryErrorat6 GiBand12 GiBJava heap even after model compaction and virtual-thread parallelism throttling (peaking at11.98 GiBheap before crashing). Memory Saver lowers the minimum verified-Xmxcap to3 GiB(-Xmx3072M,-75%+vs12 GiBOOM), eliminates all live CPUStoredVertexDatainstances (-> 0), and cut single-pass digest CPU by19.24%in microbenchmarking. Note that-Xmx3072Mlimits Java heap only; total Windows Working Set / Private Commit stays around4.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:
- Unresolved Futures on Parse Failures: Native
BlockbenchModelLoaderlogs parse exceptions and returns without callingsetModelLoaded(), stranding0.3.xsharedCompletableFutureentries forever. - Inverted Cache Lookup Order:
0.3.xrestored text from the text cache and hashed it before checking the Blockbench source cache, paying I/O and allocation costs even on cache hits. - 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.
- Version-String-Only Dependency Checks: A modified MTR JAR sharing the exact
4.1.0-beta.2version string bypassed loader checks and riskedNoSuchMethodErroror 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.
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 viaLoadingModList.get().getModFileById("mtr"), and streams a full-file SHA-256 with a65,536-byte buffer. - Hard Abort Fix (
0.4.4 -> 0.4.5): Throwing a plainExceptioninonLoadcaused Mixin to log a warning and skip all Mixins while continuing startup. Since0.4.5, any mismatch throws Mixin’sMixinInitialisationErrorand halts startup cleanly with exit code1before vehicle registration begins.
2.2 Two-Level Single-Flight Cache & Bounded Concurrency (GenerationWorkCache)
Implemented in GenerationWorkCache.java, backing SharedBlockbenchCache.java and StreamedObjCache.java:
- L1 Path-Key Fast Path:
- Keys combine
(providerIdentity, modelId, textureId, flipV)via ResourceSourceKey.java usingSystem.identityHashCodeand==to distinguish packs and provider instances. - An L1 hit returns the existing
CompletableFutureimmediately, skipping disk reads, UTF-16 decoding, and SHA-256 hashing.
- Keys combine
- L2 Content Deduplication & Permit-Release Order:
SharedBlockbenchCachehashes the snapshot and formsContent(sha256Utf8Digest, textureId, flipV). If an owner already exists for that content key, the follower closes its snapshot channel and exitsReadAdmissioninsidetry (var owner = prepared.owner())before attaching to the owner future, preventing permit-hold deadlocks.StreamedObjCachebinds L2 toResourceSourceKeyintentionally because.objfiles resolve.mtland texture references relative to their path; identical.objtext at different paths can bind different materials.
- Bounded Queue, Native Tickets & Terminal Failure Handling:
- Uses a fair
Semaphore(workerCount + queueCapacity, true)(default2 + 64 = 66slots), boundedArrayBlockingQueue,MTR-memory-parsedaemon workers, andMTR-memory-timeout(300 s). Enqueued descriptors carry lightweightSupplier<Prepared<C, V>>objects without capturing raw text. - Each task increments
ModelLoaderBase::parseStartedunder lock and releases its permit +parseFinishedonly whenWork.release()runs upon actual native exit. A timed-out future whose non-interruptible native parser is still running therefore showspending == 0withoutstanding > 0. - Blockbench parsing uses
JsonParser.parseReader(...).getAsJsonObject()directly (rejecting empty or non-object JSON fallbacks) and verifies via ModelLoaderCompletionMixin.java that native code invokedsetModelLoaded()for the matching source before publishing;preserveLateFailureuses a visited-set BFS to avoid exception cycles.
- Uses a fair
- Atomic Generation Retirement & Key Release:
beginReload()marks the activeEpochretired = true, swaps in a newEpoch, clears indexes, and cancels pending futures under one lock;finishRegistration()clearsretainand removes completed index keys while facades hold their own model/display references.
2.3 Streaming Snapshots, Single-Pass Digest & Bounded LRU
- Scoped Snapshot Wrapping (SnapshotResourceProvider.java):
- ResourceTextReadMixin.java uses
@ModifyArgat the 5 audited officialResourceProvidersites (RailResource.<init>,CustomResourcesConverter.convertRails,convertObjects,CustomResourceLoader.lambda$reload$8,lambda$reload$10) to wrap NativeResourceSnapshots.java. Custom external providers andKeys.DEBUGfall back to originalprovider.get(id)behavior.
- ResourceTextReadMixin.java uses
- Single-Channel Snapshots &
engineering-055Single-Pass Digest (Utf16TextSnapshot.java & ResourceTextSnapshot.java):- Allocates
.utf16temporary files withCREATE_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 abruptRuntime.halt, the Windows kernel closes the last handle and deletes the file automatically. - Single-Pass Hashing: Earlier
0.4.8builds re-read the disk channel after writing to compute SHA-256;engineering-055wrapsInputStreamReaderin aFilterReaderinside 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 the65.26 MBBBModel benchmark). - Exact Encoding Parity: Above
4,096code units, fixed4,096-char /8,192-byte buffers withCodingErrorAction.REPLACEandCharBuffer.compact()carry split surrogate pairs across chunks, matchingString.getBytes(UTF_8)byte for byte. - Zero Whole-Input String Concatenation: BBModel reads via
JsonParser.parseReader(snapshot.reader()); OBJ and.mtlfiles stream through8 KiBReaderInputStream(snapshot.utf8Stream()) into nativeObjReader.readandMtlReader.read, closing the.objsnapshot before calling@Invoker("loadModel").
- Allocates
- Fair-Share Spill Workspace for Non-Model
readResource(TextWorkspace.java & SegmentedResourceText.java):- Callers still expecting
Stringenter ReadAdmission.java (default 2 concurrent) and claimshare = budget / readersfromTextWorkspace. - Once
4 * length > share,8,192-char in-memory segments spill intoUtf16TextSnapshot, segments are cleared, andshareis released before waiting in FIFO order for the exact4 * lengthrestoration budget—preventing mutual deadlock among concurrent large reads. StrictResourceText.java propagates real I/O and limit errors on existing resources.
- Callers still expecting
- Bounded Compressed Text LRU (BoundedTextCache.java):
- Default
96 MiB(100,663,296B, configured in CompressedResourceTextCache.java;v0.3.0usedmaxMemory / 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-blockingtryClaim(5 * length)and compress withDeflater.BEST_SPEED, aborting viaNoGainif compressed bytes>= value.length(). First readers keep the originalString; cache hits unpack under4 * lengthworkspace permits.
- Default
2.4 Lossless 36B Packed Vertices, Display Pruning & Shared JSON
- Lossless Chunked Vertices (PackedVertices.java & PackedModelGroupStore.java):
- Encodes each vertex as
36bytes (9 raw 32-bit ints viaFloat.floatToRawIntBitsforx, y, z,argb,u, v, nx, ny, nz), compressed withDeflater.BEST_SPEEDabove a1,024-vertex (36,864B) staging cap. appendTransformedreplays exact native(float)narrowing and arithmetic order (including-0.0fsemantics) alongside PackedModelGroupOperations.java for identicalboxesAABB bounds; PackedVertexEmitter.java unpacks directly intoNewOptimizedModelwithOverlayTexture.NO_OVERLAYandIGui.DEFAULT_LIGHT.
- Encodes each vertex as
- Display-Only Transform Retention (DisplayRetention.java & SharedBlockbenchLoader.java):
DisplaySelectionMixingathersPartType.DISPLAYnames duringModelPropertiescreation; the facade synchronizeswhenCompletepublication andselectDisplayspruning under one object lock regardless of arrival order.
- Shared Vehicle Config JSON (VehicleJsonCache.java):
- Shares non-empty
JsonObjecttrees per epoch by UTF-8 SHA-256 inside read admission (falling back to native on empty/error cases), relying on nativeJsonReadercopying top-level keys into per-vehicle maps while reading child nodes immutably.
- Shares non-empty
Note on Custom
Performance v6:src/targets/v6/retains a separate compile target for customPerformance v6(8bd419bd...) handling itsintARGB vertex color,ensureMutable(),builtModelscache, and V6LoaderLifecycleMixin.java close guard. Newv6validation is paused and0.4.8OBJ 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;
jstatand 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
v6target additionally carries target-specificPackedModelGroupMixinandV6LoaderLifecycleMixin.
Further Reading
- Runtime contract & review: Lock ordering, cancellation behavior with non-interruptible native parsers, workspace deadlock avoidance, and the
0.3.x -> 0.4.xengineering review. - Build, CI/CD & replay: Reproducible Gradle
8.14.3builds, repository layout, protected branch/tag workflows, and offline SHA-256 replay. - Experiment methodology & Stage records & hashes: Paired 48-JVM / 12-JVM protocols and full
v0.1.1–v0.4.9evidence tables.