leafanvil-ADR-005: Dual-Mode -javaagent Direct Section Bridge, Tier 1 Streaming NBT & Pool Concurrency, LeafGen Zero-Re-Encode Pass-Through & Paper/Folia Netty LCA_NET_V1 Pipeline¶
- Status: Accepted
- Date: 2026-11-13
- Scope:
:anvil-api(io.github.dailystruggle.anvil,io.github.dailystruggle.anvil.stream),:resource:LeafAnvil(leafanvil-common,leafanvil-paper,leafanvil-fabric,leafanvil-neoforge,leafanvil-plugin,leafanvil-net), &:resource:LeafGen(leafgen-common,leafgen-plugin) - Related ADRs & Specs:
leafanvil-ADR-001,leafanvil-ADR-002,leafanvil-ADR-003,leafanvil-ADR-004,leafgen-ADR-001,leafgen-ADR-002,leafshard-ADR-002,anvil-api-ADR-002,anvil-api-ADR-003,ADR-115,ADR-126,LCA-ICD-1.0(api/anvil-api/docs/ICD.md)
Context¶
Across :anvil-api, LeafAnvil, LeafAnvil-Net, and LeafGen, .lca (LCA-ICD-1.0, anvil-api-ADR-003) serves as a unified binary representation for GPU worldgen output (leafgen-ADR-002), live server memory (leafanvil-ADR-002), Copy-on-Write (CoW) region disk archives (leafanvil-ADR-001), and negotiated client/inter-server network streaming (leafanvil-ADR-003).
However, inspecting the runtime boundaries across Paper, Folia, Fabric, and NeoForge exposes four concrete CPU, concurrency, classloader, and wire-framing bottlenecks that prevent end-to-end zero-recompression symmetry on JVM servers:
1. Bottleneck A — :anvil-api Intermediate Map Allocation & LcaBoundedSlabPool Coarse Monitor (:anvil-api)¶
- Heap-Tree Materialization on Chunk Save (
LcaRegionFileStorage#encodeChunkNbtForRegionSlab): - Today,
LcaRegionFileStorage#encodeChunkNbtForRegionSlabparses uncompressed binary Mojang NBT viaNbt.readRootCompound(byte[]), materializing an intermediate heap tree ofLinkedHashMap<String, Object>,ArrayList, boxed primitives,long[], andbyte[](~60–120 KiBper chunk save) beforeLcaSectionCodecencodes the.lcaChunkFrame. - Simultaneously,
NmsRegionStorageInterceptor.LcaPreEncodingOutputStreamandonWriteByteBufferallocate intermediatebyte[]copies prior toLcaLiveArchive#commitPreEncodedChunkCoW. - Coarse Monitor Over Synchronous L2 Disk I/O (
LcaBoundedSlabPool): LcaBoundedSlabPool(io.github.dailystruggle.anvil.stream.LcaBoundedSlabPool) synchronizes every public entry point onthis. BecausegetChunkSlabEntryandspillToL2Diskexecute synchronousFiles.readAllBytesandFiles.writewhile holdingthis, a single L2 disk reload or spill blocks all concurrent L1 in-memory LRU cache hits acrossLeafMap,LeafShard, andLeafAnvil-Networker threads.
2. Bottleneck B — Paper/Folia SerializableChunkData NBT Round-Trip & Missing Non-Player Mutation Hooks¶
- JVM Byte-Stream Boundary vs. Direct
SectionFrameHydration: - Because a standard Paper/Folia plugin cannot add fields or rewrite methods inside already-loaded NMS classes (
LevelChunkSection,PalettedContainer,SerializableChunkDataon1.21.4+/26.1+, orChunkSerializeron1.20.4–1.21.1),NmsRegionStorageInterceptorhooks at theRegionFilestream/buffer boundary via generated subclasses ($$LeafAnvilRfBridge,$$LeafAnvilCacheBridge). - Consequently, every chunk save and load on Paper/Folia—and currently on Fabric/NeoForge because
MixinSerializableChunkDatais not yet wired—constructs and parses full MojangCompoundTag/LongArrayTag/ByteArrayTagtrees (~40–90 KiB/chunk) across 98,304 voxels, whereasPumpkinMC's RustLcaChunkBridge(leafanvil-ADR-004) hydrates chunk sections directly fromSectionFrameslices. - Incomplete Mutation Capture on Paper/Folia (
PaperLeafAnvilPlugin): - On Fabric and NeoForge,
MixinLevelChunkSectionandMixinPalettedContainerimplementLcaSectionBridgeand record everysetBlockStatemutation inline in $O(1)$ (~1–2 ns) intoLcaSectionBacking'sdirtyOverlay(((pos12 + 1) << 19) | stateId19). - Without a bytecode transformer on Paper/Folia,
PaperLeafAnvilPluginfalls back to BukkitBlockBreakEventandBlockPlaceEvent, missing all non-player world mutations (pistons, explosions, fluid flow, tree/crop growth, redstone state changes, and plugin/NMS edits such asWorldEdit).
3. Bottleneck C — LeafGen Stage K3 GPU .lca Re-Encoding Waste & Cross-ClassLoader Isolation¶
- Discarding GPU-Synthesized
.lcaFrames on Paper/Folia Save: - Under
leafgen-ADR-002,OpenClWorldgenBridge(Stage K3) andLeafGenChunkStatusInterceptorsynthesize canonical256 B-aligned.lcaframes directly in pinnedCL_MEM_ALLOC_HOST_PTRDMA memory. - Without a direct section carrier on Paper/Folia
LevelChunkSection, unloading or autosaving a GPU-generated chunk causes vanillaSerializableChunkDatato walk all 24LevelChunkSections on CPU, expand them intoCompoundTagbinary NBT, and forceLcaRegionFileStorageto re-encode the.lcaslab from scratch—discarding the.lcaframe already computed by the GPU. - Paperclip & Isolated
PluginClassLoaderRelocation Asymmetry: - When
-javaagent:plugins/LeafAnvil.jarlaunches on Paper/Folia,Premain-Classexecutes onAppClassLoaderbefore Paperclip unpacks the Minecraft server (ServerClassLoader) ororg.bukkit.*. - Later at plugin boot,
LeafAnvil-<version>.jarloads inPluginClassLoader Awith:anvil-apirelocated via Shadow (io.github.dailystruggle$\to$net.leaf.anvil.shaded.io.github.dailystruggle), whereasLeafGen-<version>.jarloads inPluginClassLoader Bwith:anvil-apiunrelocated (io.github.dailystruggle.anvil). SharingLcaSectionBackingorLcaSectionBridgedirectly acrossServerClassLoader,PluginClassLoader A, andPluginClassLoader Bwould triggerNoClassDefFoundError,LinkageError, orClassCastException.
4. Bottleneck D — Paper/Folia 32,760 B Bukkit Plugin-Messaging Cap & Unwired ODCT / MTCF Transport¶
PaperLeafAnvilPlugincurrently sketchesLCA_NET_V1delivery over BukkitPlayer#sendPluginMessage, which enforcesMAX_PLUGIN_MESSAGE_BYTES = 32_760, incurs extra channel framing overhead, and cannot suppress outbound vanillaClientboundLevelChunkWithLightPackettransmission on negotiated connections.- Meanwhile, the
500 kbpslow-bandwidth primitives (LcaOrderlessDictTableODCT,LcaMultiTargetConsolidatorMTCF, andLcaPacketDifferentialProfilerfromleafanvil-ADR-003Section 7) require direct Netty pipeline integration to frame arbitrary-sized chunk batches, suppress duplicate vanilla chunk/delta packets, and preserveClientboundChunkBatchStartPacket/ServerboundChunkBatchReceivedPacketRTT congestion pacing.
Decision¶
We standardize a Dual-Mode Single-Artifact Architecture (LeafAnvil-<version>.jar) backed by an Unshaded JDK-Only AppClassLoader Agent Bridge (net.leaf.anvil.agent) and execute four coordinated engineering workstreams across :anvil-api, LeafAnvil, LeafGen, and LeafAnvil-Net:
graph LR
subgraph GPU_Worldgen["PluginClassLoader B: LeafGen (unshaded anvil-api)"]
K3["OpenClWorldgenBridge Stage K3 DMA (.lca frame)"]
end
subgraph App_CL["AppClassLoader: net.leaf.anvil.agent (Unshaded, JDK-Only)"]
Agent["LeafAnvilPremain + LcaAgentSectionCarrier + LeafAnvilAgentBootstrap"]
end
subgraph Server_CL["ServerClassLoader: NMS / Moonrise"]
LCS["LevelChunkSection + PalettedContainer"]
SCD["SerializableChunkData / ChunkSerializer"]
Netty["Connection Netty Pipeline"]
end
subgraph LeafAnvil_CL["PluginClassLoader A: LeafAnvil (shaded anvil-api)"]
Codec["LcaStreamingNbtEncoder + Direct Section Hydrator"]
Pool["LcaBoundedSlabPool (64-Way Lock-Striped L2)"]
Store["LcaRegionFileStorage (r.rx.rz.lca)"]
Wire["PaperLcaNettyChannelHandler (ODCT + MTCF)"]
end
K3 -->|"Mount clean .lca baseFrame"| Agent
LCS <-->|"O(1) dirtyOverlay + baseFrame"| Agent
SCD <-->|"Tier 2 bypass CompoundTag"| Agent
Agent <-->|"Zero-LinkageError MethodHandles"| Codec
Codec <--> Pool
Codec <--> Store
Agent -->|"Immutable slice + atomic overlay"| Wire
Wire -->|"Suppress vanilla chunk pkt / emit LCA_NET_V1"| Netty
1. Dual-Mode Single-JAR Contract & JDK-Only AppClassLoader Agent Bridge (net.leaf.anvil.agent)¶
- Single Multi-Loader Artifact with Optional
-javaagentActivation: :resource:LeafAnvil:leafanvil-pluginshall packageLeafAnvil-<version>.jarwithMETA-INF/MANIFEST.MFattributesPremain-Class: net.leaf.anvil.agent.LeafAnvilPremain,Can-Redefine-Classes: false, andCan-Retransform-Classes: falsealongsidepaper-plugin.yml,plugin.yml,fabric.mod.json, andMETA-INF/neoforge.mods.toml.- Zero-Flag Drop-In Mode (
plugins/LeafAnvil.jaronly): Shared-hosting operators without JVM startup-flag access retain full drop-in compatibility viaNmsRegionStorageInterceptor, accelerated byLcaStreamingNbtEncoder(Workstream 1), lock-stripedLcaBoundedSlabPool(Workstream 1), andPaperLcaNettyChannelHandler(Workstream 4). - Opt-In Agent Mode (
-javaagent:plugins/LeafAnvil.jar+plugins/LeafAnvil.jaron Paper/Folia): Dedicated server andLeafShardoperators enable load-time bytecode transformation (LeafAnvilSectionClassTransformer) before NMS classes initialize, unlockingLcaAgentSectionCarrierinlinesetBlockStatetracking,SerializableChunkData/ChunkSerializerdirect.lcaChunkFramebridging, andLeafGenStage K3 zero-re-encode pass-through. - Strict JDK-Only
AppClassLoaderIsolation Invariant (net.leaf.anvil.agent): - Every type inside
net.leaf.anvil.agent(LeafAnvilPremain,LcaAgentSectionCarrier,LeafAnvilAgentBootstrap,LeafAnvilSectionClassTransformer) shall import exclusively JDK bootstrap/platform types (byte[],int[],long,java.nio.ByteBuffer,java.lang.invoke.MethodHandle,java.lang.instrument.*). net.leaf.anvil.agentshall contain zero references toorg.bukkit.*,io.papermc.*,net.minecraft.*,net.leaf.anvil.common.*,net.leaf.anvil.paper.*, orio.github.dailystruggle.*. This guaranteespremainnever triggersNoClassDefFoundErrorbefore Paperclip unpacks the server JAR and never causesAppClassLoaderto prematurely load plugin classes ahead of Paper's child-firstPaperPluginClassLoader.:resource:LeafAnvil:leafanvil-plugin/build.gradleshall keepnet/leaf/anvil/agent/**unrelocated while continuing to relocateio.github.dailystruggletonet.leaf.anvil.shaded.io.github.dailystruggle. BecauseServerClassLoader,LeafAnvil'sPluginClassLoader, andLeafGen'sPluginClassLoaderall delegatenet.leaf.anvil.agent.*upward toAppClassLoader, all three classloaders shareLcaAgentSectionCarrierandLeafAnvilAgentBootstrapwith zeroLinkageErrororClassCastException:
package net.leaf.anvil.agent;
import java.lang.instrument.Instrumentation;
import java.lang.invoke.MethodHandle;
public final class LeafAnvilPremain {
public static void premain(String agentArgs, Instrumentation inst);
public static boolean isAgentActive();
}
public interface LcaAgentSectionCarrier {
byte[] leafanvil$getBaseFrame();
void leafanvil$mountBaseFrame(byte[] baseFrame, int uniformStateId, int dataVersion, long secDed64);
int leafanvil$recordBlockMutation(int pos12, int stateId19, long currentTick);
int leafanvil$getDirtyCount();
long leafanvil$getDirtyOctantMask64();
int[] leafanvil$snapshotDirtyOverlay();
void leafanvil$clearDirtyAfterCompaction(byte[] newBaseFrame, long newSecDed64);
}
public final class LeafAnvilAgentBootstrap {
public static void registerChunkCodecHooks(
MethodHandle directChunkSerializeHook, // (Object serverLevel, Object chunkAccess) -> byte[] lcaFrameOrNull
MethodHandle directChunkHydrateHook, // (Object serverLevel, long chunkPos, byte[] lcaFrame) -> Object serializableDataOrNull
MethodHandle sectionMutationListener // (Object section, int pos12, int prevStateId, int newStateId) -> void
);
}
2. Workstream 1 — :anvil-api Universal Zero-Flag Codec & Slab-Pool Concurrency (:anvil-api)¶
- Single-Pass Binary NBT Visitor (
LcaStreamingNbtEncoder): - Introduce
LcaStreamingNbtEncoderin:anvil-api(io.github.dailystruggle.anvil) and wire it intoLcaRegionFileStorage#encodeChunkNbtForRegionSlab. LcaStreamingNbtEncodershall parse uncompressed binary Mojang NBT (byte[]orByteBuffer) in a single forward pass directly intoLcaSectionCodec.ScratchArenabuffers (yzxPaletteIdx,packedBlockLongs,skyLightNibbles,blkLightNibbles), supporting both legacy (DataVersion < 5006:"Name"/"Properties") and modern (DataVersion >= 5006:"id"/"properties",ADR-113) block-state palette schemas while slicing non-voxel residual compounds (block_entities,block_ticks,fluid_ticks,structures,BukkitValuesPDC) verbatim intoresidualNbtPayloadwithout allocatingLinkedHashMap<String, Object>orArrayListtrees.NmsRegionStorageInterceptor.LcaPreEncodingOutputStreamandonWriteByteBuffershall pass zero-copyByteBufferslices directly toLcaRegionFileStorage, eliminating duplicatetoByteArray()andnew byte[payloadLen]copies.- Lock-Striped L1 / L2 Separation in
LcaBoundedSlabPool: - Refactor
LcaBoundedSlabPool(io.github.dailystruggle.anvil.stream.LcaBoundedSlabPool) to separate the short, non-blocking L1LinkedHashMapLRU metadata critical section from a 64-way region-coordinate striped L2 disk lock array (Object[64]indexed via golden-ratio(rx, rz)mixing so diagonal and axis-aligned regions disperse evenly across all 64 stripes). - Synchronous L2
Files.readAllBytesandFiles.writeoperations during disk spills and cold reloads shall execute strictly under the region stripe lock—never while holding the global L1 map lock—so L1 RAM cache hits remain non-blocking across concurrent threads.
3. Workstream 2 — Load-Time Section/Chunk Transformation & Fabric/NeoForge MixinSerializableChunkData Parity¶
- Paper/Folia Load-Time Transformation (
LeafAnvilSectionClassTransformer): - When
LeafAnvilPremain#isAgentActive()istrue,LeafAnvilSectionClassTransformershall inspect class loads matching NMSLevelChunkSection,PalettedContainer,SerializableChunkData(1.21.4+/26.1+), andChunkSerializer(1.20.4–1.21.1) using raw JVM classfile / JDK ClassFile structural descriptor matching:LevelChunkSection&PalettedContainer: ImplementLcaAgentSectionCarrier, inject backing fields (byte[] baseFrame,int uniformStateId,int dataVersion,long baselineSecDed64,int dirtyCount,long dirtyOctantMask64,int[] dirtyOverlay), and record everysetBlockStatewrite in $O(1)$ using the packed 32-bit sentinel word((pos12 + 1) << 19) | (stateId19 & 0x7FFFF)(leafanvil-ADR-002). Section-local coordinates shall be strictly masked via(x & 15, y & 15, z & 15)before computingpos12, and hooks shall run after (or mirror)LevelChunkSection's scalar count updates (nonEmptyBlockCount,tickingBlockCount,tickingFluidCount) and Moonrise'sIBlockDataList(SimpleRandomTickList) synchronizer (LcaInMemoryChunkCoordinator).SerializableChunkData&ChunkSerializer: InvokeLeafAnvilAgentBootstrap's volatileMethodHandlehooks (directChunkSerializeHook,directChunkHydrateHook) once registered byPaperLeafAnvilPlugin#onEnable. WhenchunkDataVersion == currentDataVersion, voxel sections extract and hydrate directly betweenLevelChunkSection(PalettedContainer+DataLayer/ StarlightSWMRNibbleArray) and.lcaChunkFrames via cachedBlock.BLOCK_STATE_REGISTRY$\leftrightarrow$.lcadictIdint[]lookup tables, serializing only sparse non-voxel residual tags (block_entities,block_ticks,fluid_ticks,structures,BukkitValues) to NBT.
- Per-Class Structural Fail-Safe (
REQ-RTP-S-004): If an unrecognized server fork alters expected field or method descriptors on a target class,LeafAnvilSectionClassTransformershall returnnull(unmodified bytecode) for that class, emit a single structuredWARNINGdiagnostic (S-004), and leaveNmsRegionStorageInterceptor+LcaStreamingNbtEncoderactive as the lossless fallback. - Fabric & NeoForge Tier 2 Parity (
MixinSerializableChunkData): :resource:LeafAnvil:leafanvil-fabricand:resource:LeafAnvil:leafanvil-neoforgeshall addMixinSerializableChunkData(andMixinChunkSerializerwhere applicable in target version subprojects), registered in their respectiveleafanvil.mixins.jsondescriptors, sharing the exact common direct-hydration and direct-extraction helper inleafanvil-commonwithout requiring-javaagenton Mixin-native loaders.
4. Workstream 3 — LeafGen Stage K3 GPU .lca Zero-Re-Encode Pass-Through (:leafgen-common & :leafanvil-common)¶
- Cross-ClassLoader GPU
baseFrameMounting (LeafGenChunkStatusInterceptor): - When
OpenClWorldgenBridge(Stage K3,leafgen-ADR-002) completes a GPU chunk synthesis batch in pinned DMA memory,LeafGenChunkStatusInterceptorshall detect whether each populatedLevelChunkSectionimplementsLcaAgentSectionCarrier(Paper/Folia-javaagentviaAppClassLoader) orLcaSectionBridge(Fabric/NeoForge Mixins) and mount the GPU-emitted.lcabaseFrameslice,uniformStateId,DataVersion, andbaselineSecDed64directly onto the section withdirtyCount = 0. - Zero-Re-Encode Flush & Selective Dirty-Section Splice:
- When flushing a chunk to
LcaRegionFileStorageor slicing outbound wire batches forLeafAnvil-Net/LeafShard:- Clean GPU Chunk (
dirtyCount == 0across all sections andchunkDataVersion == currentDataVersion): Commit or transmit the mounted.lcaChunkFrame/SectionFrameslices verbatim—zeroCompoundTagconstruction, zeroNbtIobyte stream, and zero CPU 98,304-voxel re-scan. - Partially Mutated Chunk (
dirtyCount > 0on $k$ sections): Compact/re-encode only the $k$ sections with non-zerodirtyCount(O(R + D)stream-merge orChunkPatchTail0x4000perleafanvil-ADR-002) and splice the remaining $24 - k$ clean GPUSectionFramebyte slices verbatim.
- Clean GPU Chunk (
5. Workstream 4 — Paper/Folia Netty ChannelDuplexHandler & ODCT / MTCF Wire Pipeline (:leafanvil-paper & :leafanvil-common)¶
- Protocol-Boundary Interception (
PaperLcaNettyChannelHandler): - Inject
PaperLcaNettyChannelHandler(io.netty.channel.ChannelDuplexHandler) into each player's NettyConnection.channel.pipeline()(positioned before vanilla packet compression/encoding) on both commercialLeafAnviland MITLeafAnvil-Net(leafanvil-ADR-003). - For sessions that have completed the
leafanvil:chunk_stream_handshake:- Intercept and suppress outbound vanilla
ClientboundLevelChunkWithLightPacket,ClientboundSectionBlocksUpdatePacket, andClientboundBlockUpdatePacket, replacing them with framedLCA_NET_V1payloads without BukkitsendPluginMessage's32,760 Bceiling. - Preserve vanilla
ClientboundChunkBatchStartPacket,ClientboundChunkBatchFinishedPacket, andServerboundChunkBatchReceivedPacketflow-control tokens so Minecraft's native client RTT congestion window continues pacing chunk delivery smoothly. - Pass unnegotiated vanilla client connections through untouched with zero shared-state contention.
- Intercept and suppress outbound vanilla
- Folia Thread-Safety (
F-001..F-003) &ODCT/MTCFIntegration: PaperLcaNettyChannelHandlerrunning on Netty event-loop threads shall never invoke synchronousServerLevelchunk loads (REQ-RTP-S-005) or mutate Folia region-ownedLevelChunkSectionstate (F-001..F-003); it shall read exclusively immutablebaseFramebyte slices and atomicdirtyOverlaysnapshots exported viaLcaAgentSectionCarrier/LcaInMemoryChunkCoordinator.- Wire
LcaOrderlessDictTable(ODCT,0x4F444354),LcaMultiTargetConsolidator(MTCF,0x4D544346), andLcaPacketDifferentialProfilerintoLcaWireStreamProtocolsoCAP_ORDERLESS_DICT_AND_MULTICAST(1 << 5) sessions receive Chebyshev-spiral-prioritized, orderless-dictionary-compressed.lcaframes and4-bytedirtyOverlaydeltas within configured upload budgets (max-server-upload-kbps). - When
LeafAnvilPremain#isAgentActive()(Paper/Folia) orLcaSectionBridgeMixins (Fabric/NeoForge) are active, source live block deltas directly from inline section mutation hooks and disable redundant BukkitBlockBreakEvent/BlockPlaceEventlisteners.
Alternatives Considered¶
1. Unrelocated Shared :anvil-api SPI on AppClassLoader¶
- Proposal: Exclude all of
io.github.dailystruggle.anvil.*andLcaSectionBridgefrom Shadow relocation soAppClassLoader,LeafAnvil, andLeafGenshareLcaSectionBackinginstances directly. - Why Rejected: Placing
:anvil-apionAppClassLoaderforces every co-installed Leaf plugin (LeafRTP,LeafMap,LeafGen,LeafShard,LeafAnvil) onto a single JVM-wide:anvil-apibinary version when-javaagentis present, breaking independent rolling plugin upgrades (ADR-126) and risking subtle version-skewNoSuchMethodErrors across plugins. Keeping only a tiny, stable, zero-dependencynet.leaf.anvil.agentJDK-type carrier onAppClassLoaderpreserves full Shadow isolation for each plugin's internal:anvil-apiclasses.
2. Runtime Self-Attach (VirtualMachine.attach) + retransformClasses with Striped Weak Side-Map¶
- Proposal: Dynamically self-attach during
JavaPlugin#onLoadusingInstrumentation#retransformClassesand store per-section backing state in a weak identity map (WeakHashMap/ stripedConcurrentHashMapkeyed bySystem.identityHashCode(section)) becauseretransformClassesforbids adding instance fields. - Why Rejected: JDK 21+ emits loud dynamic-agent warnings and future JDKs restrict dynamic self-attach unless
-XX:+EnableDynamicAgentLoadingis passed anyway (negating the "zero startup flag" benefit). Worse, replacing a direct object field load onLevelChunkSectionwith an identity-hash + weak-reference map lookup on everysetBlockState/getBlockStateadds pointer-chasing cache misses directly on the hot tick thread across240,000+live sections.
3. Mandatory -javaagent Only (Dropping NmsRegionStorageInterceptor) or Separate LeafAnvil-Agent.jar¶
- Proposal: Require
-javaagenton Paper/Folia or ship a secondLeafAnvil-Agent-<version>.jarartifact. - Why Rejected: Locked-down shared Minecraft panels frequently disallow custom JVM startup flags, and shipping two separate JARs invites version mismatches between
plugins/LeafAnvil.jarand-javaagent:LeafAnvil-Agent.jar. EmbeddingPremain-Classinside the singleLeafAnvil-<version>.jarwhile keepingNmsRegionStorageInterceptor+LcaStreamingNbtEncoderas the zero-flag baseline serves both shared-panel users and dedicatedLeafShardclusters from one artifact.
Consequences¶
Positive Consequences¶
- Eliminates the JVM Mojang-NBT Voxel Tax: Cuts temporary heap allocations on chunk load/save by
~85%–95%under Tier 2 (-javaagenton Paper/Folia andMixinSerializableChunkDataon Fabric/NeoForge) and removes~60–120 KiB/chunk ofLinkedHashMapNBT tree allocations even in zero-flag Tier 1 plugin mode (LcaStreamingNbtEncoder). - True End-to-End GPU $\to$ Disk & Wire Zero-Recompression:
LeafGenStage K3.lcaframes synthesized in pinned GPU DMA memory flow straight ontoLevelChunkSection,LcaLiveArchivedisk slabs, andLeafAnvil-Net/LeafShardsockets without CPU re-encoding on untouched sections. - 100% World Mutation Fidelity & Protocol-Level Streaming on Paper/Folia: Inline
LevelChunkSectionbytecode hooks capture pistons, explosions, fluids, redstone, and NMS edits in $O(1)$ (~1–2 ns), whilePaperLcaNettyChannelHandlerlifts the32,760 BBukkit plugin-messaging limit and suppresses redundant vanilla chunk packets. - Non-Blocking Concurrent L1 Slab Reads: Lock-striping L2 disk I/O in
LcaBoundedSlabPoolkeeps L1 RAM hits wait-free with respect to concurrent cold-region disk spills and reads.
Trade-offs & Required Safety Invariants¶
- Zero Main/Region-Thread Chunk I/O (
REQ-RTP-S-005) & Folia Region Ownership (F-001..F-003): NeitherLeafAnvilAgentBootstraphooks norPaperLcaNettyChannelHandlershall trigger synchronous chunk loads on the main thread, Folia region threads, or Netty event-loop threads; cross-thread wire reads shall access only immutablebaseFramearrays and atomicdirtyOverlaysnapshots. - Zero Silent Failure Swallowing (
REQ-RTP-S-004): Bytecode descriptor mismatches inLeafAnvilSectionClassTransformerand malformed frames inLcaStreamingNbtEncoder/PaperLcaNettyChannelHandlershall never fail silently—unrecognized class layouts log a structuredWARNINGand fall back cleanly toNmsRegionStorageInterceptor, while storage/syndrome corruption fails closed (IOException/UncheckedIOException) or triggersCBIT/SEC-DEDrecovery. - Chunk Ticket & Pipeline Resource Hygiene (
REQ-RTP-S-002): Direct hydration and Netty batch streaming paths shall not acquire or hold extra chunk tickets beyond vanillaChunkMap/PlayerChunkSenderlifecycle bounds, releasing all NettyByteBufreference counts on every normal and exceptional exit path. - AST Hypergraph & Traceability (
Rule D-010,ADR-115): All new and modified Tier 1/2 classes (LcaStreamingNbtEncoder,LcaBoundedSlabPool,LeafAnvilPremain,LcaAgentSectionCarrier,LeafAnvilAgentBootstrap,LeafAnvilSectionClassTransformer,PaperLcaNettyChannelHandler) shall carry capability Javadoc summaries with@governedBy leafanvil-ADR-005and applicable@tracetags.
Verification & Proof Contract¶
Implementations governed by leafanvil-ADR-005 shall satisfy Gates 1–4 (VERIFICATION_GATES.md) across four deterministic test suites:
- Workstream 1 (
LcaStreamingNbtEncoderTest&LcaBoundedSlabPoolConcurrencyTestin:anvil-api): - Bit-exact
.lcaencode/decode parity betweenLcaStreamingNbtEncoderand the legacyNbt.readRootCompoundreference path acrossDataVersion < 5006("Name") andDataVersion >= 5006("id") fixtures, uniform + non-uniform sections, and residualBukkitValues/ block-entity NBT payloads. - Multi-threaded contention proof parking an L2 disk spill/reload on a slow/latched filesystem path while asserting concurrent L1 cache hits on other regions complete without blocking.
- Workstream 2 (
LeafAnvilSectionClassTransformerTest&MixinSerializableChunkDataRound-Trip Suite in:resource:LeafAnvil): - Multi-classloader harness loading
net.leaf.anvil.agent.*in a parentClassLoader, transforming NMS-shapedLevelChunkSectionandSerializableChunkDatain a childServerClassLoader, and invokingLeafAnvilAgentBootstrapMethodHandlehooks from two siblingPluginClassLoaders (one relocated, one unrelocated) with zeroLinkageErrororNoClassDefFoundError(including pre-Paperclip boot simulation whereorg.bukkit.*is absent). - Verification of
(x & 15, y & 15, z & 15)negative-$Y$ coordinate masking, Moonrise random-tick list parity, and automatic fallback toNmsRegionStorageInterceptorwhen target descriptors are altered. - Workstream 3 (
LeafGenZeroReencodePassThroughTestacross:resource:LeafGen&:resource:LeafAnvil): - Mounting a
LeafGenStage K3.lcaframe ontoLcaAgentSectionCarrier, mutating 1 voxel in 1 section (dirtyCount = 1), flushing toLcaRegionFileStorage, and asserting bit-identical preservation of the 23 untouched section byte slices alongside exact decoded voxel parity for the mutated section. - Workstream 4 (
PaperLcaNettyChannelHandlerTestin:resource:LeafAnvil:leafanvil-paper/:leafanvil-common): - Netty
EmbeddedChannelproof verifying untouched vanilla packet pass-through on unnegotiated channels, vanilla chunk/delta packet suppression on negotiatedLCA_NET_V1channels,> 32,760 Bchunk-batch framing,LcaOrderlessDictTable(ODCT) out-of-order decode parity withSEC-DED-64verification, andLcaMultiTargetConsolidator(MTCF)500 kbps(350 kbpsusable) tick-budget enforcement with zero leakedByteBufreference counts.