Documentation
Runtime contract & review
Concurrency invariants in GenerationWorkCache, cancellation semantics with non-interruptible native parsers, TextWorkspace spill rules, and the 0.3.x engineering review.
This page consolidates RUNTIME_DESIGN.md and ENGINEERING_REVIEW.md from the main repository, documenting the scheduling invariants, ownership guarantees, and design tradeoffs behind the 0.4.7–0.4.9 runtime.
1. Scheduling & Single-Flight Invariants (GenerationWorkCache)
GenerationWorkCache is a pure-Java, generation-scoped single-flight scheduling core:
- Two-Level Key Isolation:
- L1 path keys combine
(providerIdentity, modelId, textureId, flipV). An L1 hit returns itsCompletableFutureimmediately before reading files, unpacking cached text, or hashing source bytes. - L2 content keys are derived after an admitted worker streams and hashes a miss. For Blockbench models, identical alias-path inputs attach to the owner future, closing their own snapshot channel and releasing their read permit before waiting rather than holding a permit across another task’s completion.
- Enqueued preparation descriptors are lightweight
Supplierobjects that never capture raw source text.
- L1 path keys combine
- Backpressure, Timeouts & Retryable Failures:
- Default configuration uses
2worker threads (mtr.memory.parsers=2) and64extra outstanding queue slots (mtr.memory.parseQueue=64). Backpressure applies before registering another descriptor. - Both queue admission and submitted work share a
300-second timeout (mtr.memory.parseTimeoutSeconds=300). - Failures remove the path and content entries for that generation so subsequent requests can retry rather than pinning a dead future.
- Default configuration uses
- Atomic Generation Retirement & Key Release:
beginReload()retires the entire currentEpochunder a single lock, swaps in the replacementEpoch, cancels pending futures, and removes queued tasks.- Registration completion (
finishRegistration()) releases successful source keys (including results finishing later), while consumer facades retain their built models and display data independently.
2. Generation Retirement, Cancellation & Native Parsers
Every model, text, and vehicle-JSON call captures its resource generation before waiting for admission:
- Retirement Rechecks: Callers waiting during retirement are canceled before reading or entering the replacement generation—including callers queued behind native work that ignores interruption. Text hits and single-flight followers recheck their generation after restoring data so stale readers cannot pollute the new cache.
- Native Tickets (
parseStarted/parseFinished) & Inline Scope:- Every module task contributes one native
parseStarted/parseFinishedticket so MTR’sawaitParsingobserves module-queued work. BlockbenchParseExecutorMixinexecutes the native parserRunnableinline only when the calling thread owns the thread-localOWNED_PARSEscope; foreign MTR tasks retain their original executor while the native parser keeps its own native ticket.- Publication succeeds only after that
Runnablereturns andModelLoaderCompletionMixinobservessetModelLoaded()for the matching source. A caught native exception withoutsetModelLoaded()becomes a shared terminal failure. - Blockbench inputs stream directly into native
JsonParser.parseReader: malformed, truncated, or non-object JSON fails explicitly instead of inheriting an empty{}fallback.
- Every module task contributes one native
- Cancellation Cannot Interrupt Native Code:
- Canceling or timing out a future cannot force non-interruptible native parsing or disk I/O to stop.
- A running owner retains its admission permit and native ticket until actual exit. Diagnostics can therefore legitimately show
pending == 0alongsideoutstanding > 0, a distinction explicitly tested in headless suites. Daemon threads do not provide a process-isolation boundary.
3. Text Cache, Strict Reader & Spill Workspace Contracts
3.1 BoundedTextCache (96 MiB Bounded LRU)
- Uses a single synchronized LRU with eviction performed before insertion.
- Checks conservative uncompressed entry weight before attempting compression; oversized items bypass compression and caching altogether.
- Aborts compression via
NoGainwheneverDeflater.BEST_SPEEDoutput fails to beat compact String storage, retaining the rawString. - Claims a conservative
5 * lengthpayload bytes non-blockingly (tryClaim) during compression, or retains the uncompressed entry if the workspace is busy. - Preserves exact UTF-16 code units, including null characters and unpaired surrogates. First readers keep their original
Stringidentity; followers unpack under the sameReadAdmissionscope. Retired readers cannot populate replacement caches.
3.2 SegmentedResourceText & StrictResourceText
- Checks decoded size before storing each segment, failing explicitly at
maxTextCodeUnitswithout ever truncating oversized inputs. - On the official provider,
StrictResourceTextpropagates real open, read, close, size, and cancellation errors on existing resources rather than inheriting the native helper’s logged empty-String fallback. Valid empty files and the native missing-resourceOptional.empty()fallback remain distinct valid empty results (fixing a previously missing resource still requires a resource reload to retire that cache key).
3.3 TextWorkspace & DELETE_ON_CLOSE Channel Ownership
- Transient decoded payloads share a weighted
TextWorkspace: a reader claims a fair shareshare = budget / readers; if an input exceedsshare, collected8,192-char segments spill as exact UTF-16 code units into an owned temporary file, in-memory segments are cleared, andshareis released completely before waiting in FIFO order for the known4 * lengthrestoration budget. Two large concurrent reads can never deadlock holding partial workspace reservations. - Smaller inputs stay on the in-memory segmented path with zero disk files created.
- Each snapshot atomically opens one channel with
CREATE_NEW | READ | WRITE | DELETE_ON_CLOSEand keeps that single handle across writing, budget waiting, rewinding, and restoration—never reopening by path or scavenging files from prior processes.owner.close()deletes the file on success, failure, and cancellation; Windows also deletes it on abrupt process exit (Runtime.halt) when the kernel closes the handle. - Boundary: Tests verify real read/close/deletion errors and abrupt
Runtime.haltcleanup, but do not establish power-loss or real disk-full filesystem behavior.
4. Configuration Strictness & Local Budget Boundaries
- No Silent Fallback: All
-Dmtr.memory.*properties (listed in Technical principles) are read once at subsystem startup. Malformed, non-positive, or inconsistent settings (such astextWorkspaceBytes < 4 * maxTextCodeUnits) fail initialization immediately rather than silently disabling checks or substituting defaults. 3 GiBDefault Sizing: At-Xmx3072M,maxTextCodeUnitsdefaults to201,326,592andtextWorkspaceBytesdefaults to805,306,368bytes. The102,035,449-code-unithxd3d/25t__doors.objfits inside this shared budget while exceeding the initial two-reader fair share (402.65 MB), intentionally routing through an immutable disk snapshot independent of paths, character repertoire, orCompactStrings.- Local Budget vs. Process RAM: Four payload bytes per code unit cover segmented decoding plus final text sizing—not an accounting proof of all live JVM objects. Caller-retained values, fixed I/O buffers, object headers, unreachable garbage awaiting GC, native Gson/OBJ graphs, foreign native parsers, GPU VRAM, and OS Working Set sit outside the LRU budget. The mod does not advertise a whole-process RAM ceiling or guaranteed frame latency; raising
mtr.memory.parserscan boost throughput at the expense of higher peak live memory.
5. Engineering Review Retrospective (0.3.x -> 0.4.x)
The 2026-11-13 to 2026-11-14 engineering review (ENGINEERING_REVIEW.md) concluded that 0.3.x was a credible, carefully measured optimization experiment—proving 3 GiB launch viability—but not yet a maintainable general-purpose release until correctness, ownership, and artifact identity were closed. That review established the rule that correctness and ownership precede further heap reductions, driving six structural repairs:
| Original Engineering Gap | Implemented Change | Evidence & Remaining Boundary |
|---|---|---|
| Instance-bound builds & source substitution | Gradle 8.14.3 bootstrap, canonical src/main & src/targets/{official,v6} layouts, deterministic bundles |
0.4.0 class equivalence & byte-identical rebuild SHA-256; 0.4.9 exact product 3d2a1407... |
| Unbounded queued text & hanging failed loads | Descriptor admission, L1 path fast hits, inline parse scope, atomic failure/timeout/retirement cleanup | Adversarial lifecycle tests, 1,000-generation churn, 106 Java regressions |
| Cache budget applied after compression | Pre-compression oversized bypass, pre-insertion LRU eviction, bounded compression, decoded-size checks | Exact UTF-16, admission/eviction, and -Xmx64M streaming negative controls |
| Audits outside the independent repository | Native mesh/display/JSON audits, real-model runner, standalone JFR decoder, and optional probe JAR | Native reference audits pass; probes excluded from production bundles |
| Memory-only claims without paired timing | Frozen experiment plans, counterbalanced AB/BA, A/A noise controls, neutral observer (benchmark_sources.py / packaged_client.py) |
Source-lookup microbenchmarks & 12-JVM Spark trials completed; 48-JVM whole-client benchmark pending (Methodology) |
| Compatibility & version-only check ambiguity | Runtime full-file MTR JAR SHA-256 gate, exact loader ranges, deterministic manifest, MIT license | Same-version modified MTR exits with code 1 (0.4.5–0.4.9); Performance v6 paused |
Further Reading
- Technical principles: Four-layer architecture diagram, 7 JVM
-Dproperties, and all 18 Mixins/Accessors. - Experiment methodology: Independent JVM replicates, AB/BA and A/A thresholds, Spark profiling, and offline replay.
- Build, CI/CD & replay: Reproducible build manifests, protected branch rules, and headless regression commands.