Modern Apps git

← Modern-Apps.git

voxels: chunk sync crosses JNI as bytes, not JSON numbers

Commit
0dbde9a5cc7c73d7422f900b0778495d47a780af
Author
Vayun Mathur <[email protected]>
When
2026-11-21 22:38 UTC (14 days ago)
Parents
7249b24
Outbound chunks serialised every byte as a JSON number
through the Rust->Kotlin drain (~3.6x bloat, ~3.6ms of
format/parse per 128KiB chunk). A versioned binary frame
(VXB1) now carries chunk payloads raw across JNI as a
ByteArray - one memcpy. The signed op strings are rebuilt
byte-identically on the Kotlin side (golden-frame tests pin
both sides), so persisted PendingOps and the relay wire
format are untouched; inbound signed JSON is unchanged by
design (the string IS the signed format).

Verified: cargo 253 pass incl. byte-equality round-trips at
0/1/128KiB and corrupt-frame rejection; voxels suite + detekt
pass; pending-ops replay proven verbatim.

Diff

games/voxels/src/main/java/com/vayunmathur/games/voxels/network/MultiplayerPump.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/MultiplayerPump.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/MultiplayerPump.ktindex 43fa6eaadb..74ccbd0416 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/MultiplayerPump.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/MultiplayerPump.kt@@ -16,7 +16,6 @@ import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch-import org.json.JSONArray import org.json.JSONObject import java.util.Collections import java.util.concurrent.ConcurrentHashMap@@ -189,16 +188,23 @@ class MultiplayerPump private constructor(     // drops them — the next tick (e.g. after reconnect) replays them in order. Presence stays     // ephemeral/best-effort: a dropped transform is superseded by the next one.     private suspend fun flushOutbound() {-        val out = try { VoxelsNative.netDrainOutbound() } catch (_: Exception) { "[]" }+        // Binary local drain (OutboundFrame): chunk payloads arrive as raw+        // bytes, no JSONArray of numbers. Signed-op strings are reconstructed+        // byte-identically before signing, so persistence/relay are unchanged.+        val raw = try { VoxelsNative.netDrainOutboundBin() } catch (_: Exception) { ByteArray(0) }         try {-            val arr = JSONArray(out)             val ops = ArrayList<String>()-            for (i in 0 until arr.length()) {-                val o = arr.getJSONObject(i)-                if (o.optString("type") == "PlayerTransform") {-                    VoxelsSync.sendPresence(channel, key, JSONObject().put("from", myId).put("m", o).toString())-                } else {-                    ops.add(signed(o.toString()))+            for (msg in OutboundFrame.decode(raw)) {+                when (msg) {+                    is OutboundFrame.Msg.TransformJson ->+                        VoxelsSync.sendPresence(+                            channel, key,+                            JSONObject().put("from", myId).put("m", JSONObject(msg.text)).toString()+                        )+                    is OutboundFrame.Msg.Chunk -> ops.add(signed(msg.toOpsJson()))+                    // Non-chunk ops keep the old JSONObject re-serialisation,+                    // so their signed strings are exactly as before.+                    is OutboundFrame.Msg.SignedJson -> ops.add(signed(JSONObject(msg.text).toString()))                 }             }             // Always flush (even with no new ops) so persisted ops replay on reconnect.
games/voxels/src/main/java/com/vayunmathur/games/voxels/network/OutboundFrame.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/OutboundFrame.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/OutboundFrame.ktnew file mode 100644index 0000000000..271a6f71c7--- /dev/null+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/network/OutboundFrame.kt@@ -0,0 +1,145 @@+package com.vayunmathur.games.voxels.network++/**+ * Decoder for the binary Rust -> Kotlin outbound frame (`net_bin.rs`, JNI+ * `netDrainOutboundBin`) — the local representation that replaced draining+ * outbound `NetMsg`s as one JSON string.+ *+ * Why: a `ChunkData` payload is a raw VOX3 chunk (tens of KiB). As JSON every+ * byte became a number (`[0,255,...]`, ~3-4 bytes/byte), crossed JNI as a+ * String, and was parsed back number-by-number by `JSONArray` in the pump,+ * only to be re-serialised for signing. In this frame chunk payloads are raw+ * bytes; small variants keep their single-message serde JSON text.+ *+ * Scope boundary (do not cross): this frame is ONLY the local JNI leg. It is+ * never persisted, signed or sent to the relay. [Chunk.toOpsJson] reconstructs+ * the exact legacy signed-op JSON — `{"type":"ChunkData","dim":...,"data":[..]}`+ * with unsigned decimal bytes, in serde field order — so the strings that+ * [MultiplayerPump] signs, `PendingOps` persists/replays and `VoxelsSync`+ * AES-encrypts into `AppendMsg` payloads stay byte-identical, and older peers+ * keep parsing them. The inbound leg likewise stays a JSON string: the string+ * pushed to Rust is the already-verified signed `ops` payload itself.+ *+ * Frame (little-endian): `"VXB1"`, u32 count, then per message a kind byte:+ * 0 = signed JSON (u32 len + JSON), 1 = ChunkData (dim u8, cx i32, cz i32,+ * u32 len + raw bytes), 2 = PlayerTransform JSON (u32 len + JSON).+ */+object OutboundFrame {+    private const val KIND_JSON = 0+    private const val KIND_CHUNK = 1+    private const val KIND_TRANSFORM = 2+    private const val MAGIC_SIZE = 4+    private const val COUNT_SIZE = 4+    private const val CHUNK_HEADER_SIZE = 13 // dim + cx + cz + len+    private const val BYTE_MASK = 0xFF+    private const val BITS_PER_BYTE = 8+    private const val INT_BYTES = 4++    /** One drained outbound message, chunk payloads still binary. */+    sealed interface Msg {+        /** A world op to sign + relay: [text] is its single-message JSON. */+        data class SignedJson(val text: String) : Msg++        /** An ephemeral player transform: [text] is its single-message JSON. */+        data class TransformJson(val text: String) : Msg++        /** A full chunk: raw VOX3 [data], reconstructed to JSON only for signing. */+        class Chunk(val dim: Int, val cx: Int, val cz: Int, val data: ByteArray) : Msg {+            /**+             * The legacy signed-op JSON for this chunk, byte-identical to what+             * the old JSON drain + `JSONObject.toString()` produced: serde field+             * order, unsigned decimal bytes, no spaces.+             */+            fun toOpsJson(): String {+                val sb = StringBuilder(HEADER_ESTIMATE + data.size * CHARS_PER_BYTE)+                sb.append("{\"type\":\"ChunkData\",\"dim\":").append(dim)+                    .append(",\"cx\":").append(cx)+                    .append(",\"cz\":").append(cz)+                    .append(",\"data\":[")+                for (i in data.indices) {+                    if (i > 0) sb.append(',')+                    sb.append(data[i].toInt() and BYTE_MASK)+                }+                return sb.append("]}").toString()+            }++            override fun equals(other: Any?): Boolean =+                other is Chunk && dim == other.dim && cx == other.cx && cz == other.cz &&+                    data.contentEquals(other.data)++            override fun hashCode(): Int =+                HASH_SEED * (HASH_SEED * (HASH_SEED * dim + cx) + cz) + data.contentHashCode()++            private companion object {+                const val HEADER_ESTIMATE = 64+                const val CHARS_PER_BYTE = 4+                const val HASH_SEED = 31+            }+        }+    }++    /** Decodes a frame; any truncation/corruption/trailing bytes reads as empty (never throws). */+    fun decode(bytes: ByteArray): List<Msg> {+        val reader = Reader(bytes)+        val count = reader.headerCount() ?: return emptyList()+        val out = ArrayList<Msg>(count)+        var ok = true+        repeat(count) { if (ok) reader.msg()?.let { out += it } ?: run { ok = false } }+        return if (ok && reader.atEnd()) out else emptyList()+    }++    /** Bounds-checked little-endian cursor; every failure is null, never an exception. */+    private class Reader(private val bytes: ByteArray) {+        private var off = 0++        fun atEnd(): Boolean = off == bytes.size++        /** Validates the magic and returns the message count, or null if this is not a frame. */+        fun headerCount(): Int? {+            if (bytes.size < MAGIC_SIZE + COUNT_SIZE) return null+            if (!MAGIC.indices.all { bytes[it] == MAGIC[it] }) return null+            off = MAGIC_SIZE+            val count = int() ?: return null+            // Each message costs at least its kind byte, so count cannot exceed the rest.+            return count.takeIf { it >= 0 && it <= bytes.size - off }+        }++        fun msg(): Msg? = when (u8()) {+            KIND_CHUNK -> chunk()+            KIND_JSON -> int()?.let { len -> text(len)?.let { Msg.SignedJson(it) } }+            KIND_TRANSFORM -> int()?.let { len -> text(len)?.let { Msg.TransformJson(it) } }+            else -> null+        }++        private fun chunk(): Msg? {+            if (bytes.size - off < CHUNK_HEADER_SIZE) return null+            val dim = u8()+            val cx = int()+            val cz = int()+            val len = int()+            val data = len?.let { take(it) }+            return if (dim == null || cx == null || cz == null) null+            else data?.let { Msg.Chunk(dim, cx, cz, it) }+        }++        private fun text(len: Int): String? = take(len)?.decodeToString()++        private fun take(len: Int): ByteArray? =+            if (len < 0 || len > bytes.size - off) null+            else bytes.copyOfRange(off, off + len).also { off += len }++        private fun u8(): Int? =+            if (off >= bytes.size) null else (bytes[off++].toInt() and BYTE_MASK)++        private fun int(): Int? {+            val raw = take(INT_BYTES) ?: return null+            return (0 until INT_BYTES).fold(0) { acc, i ->+                acc or ((raw[i].toInt() and BYTE_MASK) shl (BITS_PER_BYTE * i))+            }+        }++        private companion object {+            val MAGIC = byteArrayOf('V'.code.toByte(), 'X'.code.toByte(), 'B'.code.toByte(), '1'.code.toByte())+        }+    }+}
games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/VoxelsNative.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/VoxelsNative.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/VoxelsNative.ktindex 9d4b6566df..ceea4db921 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/VoxelsNative.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/platform/VoxelsNative.kt@@ -87,6 +87,10 @@ object VoxelsNative {     external fun netPushInbound(json: String): Boolean     // Rust -> Kotlin: pull queued outbound NetMsgs as a JSON array to encrypt + relay.     external fun netDrainOutbound(): String+    // Rust -> Kotlin (preferred): same queue as a binary frame (see OutboundFrame) —+    // ChunkData payloads cross as raw bytes, not JSON number arrays. Local leg only:+    // the signed/relay format reconstructed from it is byte-identical to the JSON leg.+    external fun netDrainOutboundBin(): ByteArray     // Remote players for the HUD/avatars: [{device,x,y,z,yaw}].     external fun getPeersJson(): String     // Client → host: ask for the currently-open chest's contents (host replies with ContainerSync).
games/voxels/src/main/rust/src/lib_jni_net.rs
diff --git a/games/voxels/src/main/rust/src/lib_jni_net.rs b/games/voxels/src/main/rust/src/lib_jni_net.rsindex f85e4b1624..a84b42272d 100644--- a/games/voxels/src/main/rust/src/lib_jni_net.rs+++ b/games/voxels/src/main/rust/src/lib_jni_net.rs@@ -77,6 +77,25 @@ pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_netDr     .resolve::<jni::errors::LogErrorAndDefault>() } +/// JNI bridge for `VoxelsNative#netDrainOutboundBin`: drains queued outbound+/// multiplayer messages as a binary frame (see net_bin.rs) — chunk payloads+/// cross as raw bytes instead of JSON numbers. Local representation only;+/// Kotlin reconstructs the legacy signed-op JSON before signing/persisting.+/// Returns null on failure, mirroring the byte-array-out pattern used by the+/// e2ee-p2p JNI bridge (`byte_array_from_slice`).+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_games_voxels_util_VoxelsNative_netDrainOutboundBin<'l>(+    mut env: EnvUnowned<'l>, _class: JClass<'l>,+) -> jni::sys::jbyteArray {+    env.with_env(|env| -> jni::errors::Result<jni::sys::jbyteArray> {+        match env.byte_array_from_slice(&crate::net::drain_outbound_bin()) {+            Ok(a) => Ok(a.into_raw()),+            Err(_) => Ok(std::ptr::null_mut()),+        }+    })+    .resolve::<jni::errors::LogErrorAndDefault>()+}+ /// JNI bridge for `VoxelsNative#getPeersJson`: returns the known multiplayer /// peers as a JSON string. #[no_mangle]
games/voxels/src/main/rust/src/net.rs
diff --git a/games/voxels/src/main/rust/src/net.rs b/games/voxels/src/main/rust/src/net.rsindex 16fba9f070..4851487fcb 100644--- a/games/voxels/src/main/rust/src/net.rs+++ b/games/voxels/src/main/rust/src/net.rs@@ -441,6 +441,7 @@ pub fn apply_inbound(state: &mut EngineState) { }  include!("net_part1.rs");+include!("net_bin.rs"); #[cfg(test)] #[path = "net_tests.rs"] mod net_tests;
games/voxels/src/main/rust/src/net_bin.rs
diff --git a/games/voxels/src/main/rust/src/net_bin.rs b/games/voxels/src/main/rust/src/net_bin.rsnew file mode 100644index 0000000000..41e3868cac--- /dev/null+++ b/games/voxels/src/main/rust/src/net_bin.rs@@ -0,0 +1,178 @@+// Binary local transport for outbound `NetMsg`s (Rust -> Kotlin over JNI only).+//+// Why this exists: `ChunkData.data` is a raw VOX3 chunk (tens of KiB). Through+// `drain_outbound_json` serde_json renders every byte as a JSON number, so the+// JNI string is ~3-4x the chunk and Kotlin then pays a `JSONArray` parse of+// every number, only to re-serialise the same numbers for signing. This frame+// carries chunk payloads as raw bytes instead. All other variants are small+// and keep riding as their (single-message) serde JSON text.+//+// This is ONLY the local Rust<->Kotlin representation. It is never persisted,+// signed, encrypted or sent to the relay: Kotlin reconstructs the exact legacy+// signed-op JSON for a chunk (`OutboundFrame.chunkOpsJson`) before signing, so+// `SignedOp{author,sig,ops}` strings, `PendingOps` persistence/replay and the+// encrypted `AppendMsg` relay payloads stay byte-identical. Inbound keeps the+// JSON string leg for the same reason: the string Kotlin pushes is the signed+// `ops` payload itself, already verified verbatim.+//+// Frame (all integers little-endian):+//   "VXB1" u32 count, then per message:+//     kind u8: 0 = signed JSON, 1 = ChunkData, 2 = PlayerTransform JSON+//     kind 0/2: u32 json_len, json bytes (serde_json of the single NetMsg)+//     kind 1: dim u8, cx i32, cz i32, u32 data_len, raw chunk bytes++const BIN_MAGIC: &[u8; 4] = b"VXB1";+const KIND_JSON: u8 = 0;+const KIND_CHUNK: u8 = 1;+const KIND_TRANSFORM: u8 = 2;++/// Encodes a batch for the binary JNI drain. See the frame spec above.+pub fn encode_outbound_bin(msgs: &[NetMsg]) -> Vec<u8> {+    let mut out = Vec::new();+    out.extend_from_slice(BIN_MAGIC);+    out.extend_from_slice(&(msgs.len() as u32).to_le_bytes());+    for msg in msgs {+        match msg {+            NetMsg::ChunkData { dim, cx, cz, data } => {+                out.push(KIND_CHUNK);+                out.push(*dim);+                out.extend_from_slice(&cx.to_le_bytes());+                out.extend_from_slice(&cz.to_le_bytes());+                out.extend_from_slice(&(data.len() as u32).to_le_bytes());+                out.extend_from_slice(data);+            }+            other => {+                out.push(if matches!(other, NetMsg::PlayerTransform { .. }) { KIND_TRANSFORM } else { KIND_JSON });+                let json = serde_json::to_string(other).unwrap_or_else(|_| "{}".to_string());+                out.extend_from_slice(&(json.len() as u32).to_le_bytes());+                out.extend_from_slice(json.as_bytes());+            }+        }+    }+    out+}++/// Rust -> Kotlin: pull all queued outbound messages as a binary frame.+/// The JSON drain stays for tests/fallback; production Kotlin uses this.+pub fn drain_outbound_bin() -> Vec<u8> {+    let taken: Vec<NetMsg> = outbox().lock().map(|mut q| std::mem::take(&mut *q)).unwrap_or_default();+    encode_outbound_bin(&taken)+}++fn take<'a>(bytes: &'a [u8], off: &mut usize, len: usize) -> Option<&'a [u8]> {+    let end = off.checked_add(len)?;+    let slice = bytes.get(*off..end)?;+    *off = end;+    Some(slice)+}+fn take_u32(bytes: &[u8], off: &mut usize) -> Option<u32> {+    Some(u32::from_le_bytes(take(bytes, off, 4)?.try_into().ok()?))+}+fn take_i32(bytes: &[u8], off: &mut usize) -> Option<i32> {+    Some(i32::from_le_bytes(take(bytes, off, 4)?.try_into().ok()?))+}++/// Decodes a binary frame back into messages. `None` on any truncation or+/// corruption (never panics); used by tests to pin the frame format — the+/// production decoder is Kotlin's `OutboundFrame`.+pub fn decode_outbound_bin(bytes: &[u8]) -> Option<Vec<NetMsg>> {+    let mut off = 0usize;+    if take(bytes, &mut off, 4)? != BIN_MAGIC { return None; }+    let count = take_u32(bytes, &mut off)? as usize;+    // Each message costs at least one kind byte; reject absurd counts early.+    if count > bytes.len() { return None; }+    let mut msgs = Vec::with_capacity(count);+    for _ in 0..count {+        let kind = *take(bytes, &mut off, 1)?.first()?;+        match kind {+            KIND_CHUNK => {+                let dim = *take(bytes, &mut off, 1)?.first()?;+                let cx = take_i32(bytes, &mut off)?;+                let cz = take_i32(bytes, &mut off)?;+                let len = take_u32(bytes, &mut off)? as usize;+                let data = take(bytes, &mut off, len)?.to_vec();+                msgs.push(NetMsg::ChunkData { dim, cx, cz, data });+            }+            KIND_JSON | KIND_TRANSFORM => {+                let len = take_u32(bytes, &mut off)? as usize;+                let text = std::str::from_utf8(take(bytes, &mut off, len)?).ok()?;+                let msg: NetMsg = serde_json::from_str(text).ok()?;+                if (kind == KIND_TRANSFORM) != matches!(msg, NetMsg::PlayerTransform { .. }) { return None; }+                msgs.push(msg);+            }+            _ => return None,+        }+    }+    if off != bytes.len() { return None; }+    Some(msgs)+}++#[cfg(test)]+mod bin_tests {+    use super::*;++    fn chunk_msg(data: Vec<u8>) -> NetMsg {+        NetMsg::ChunkData { dim: 1, cx: -2, cz: 3, data }+    }++    #[test]+    fn binary_frame_round_trips_chunk_bytes_at_all_sizes() {+        for data in [Vec::new(), vec![0xAB], (0..128 * 1024).map(|i| (i % 251) as u8).collect::<Vec<u8>>()] {+            let msgs = vec![chunk_msg(data.clone())];+            let bin = encode_outbound_bin(&msgs);+            // Binary framing is ~1 byte/byte plus a fixed header, never ~3.+            assert!(bin.len() < data.len() + 64, "{} bytes ballooned to {}", data.len(), bin.len());+            let back = decode_outbound_bin(&bin).expect("frame must decode");+            match &back[..] {+                [NetMsg::ChunkData { dim: 1, cx: -2, cz: 3, data: got }] => assert_eq!(got, &data),+                other => panic!("wrong decode: {other:?}"),+            }+            // The legacy signed-op JSON for the same message is unchanged.+            let json = serde_json::to_string(&chunk_msg(data.clone())).unwrap();+            let parsed: NetMsg = serde_json::from_str(&json).unwrap();+            match parsed {+                NetMsg::ChunkData { data: got, .. } => assert_eq!(got, data),+                other => panic!("JSON leg changed: {other:?}"),+            }+        }+    }++    #[test]+    fn binary_frame_pins_golden_bytes_and_size_win() {+        // Golden frame for ChunkData{dim:1,cx:-2,cz:3,data:[0,255]}: pins the+        // cross-language format Kotlin's OutboundFrame decodes.+        let bin = encode_outbound_bin(&[chunk_msg(vec![0, 255])]);+        let golden: &[u8] = b"VXB1\x01\x00\x00\x00\x01\x01\xfe\xff\xff\xff\x03\x00\x00\x00\x02\x00\x00\x00\x00\xff";+        assert_eq!(bin, golden);+        let json = serde_json::to_string(&[chunk_msg(vec![0, 255])]).unwrap();+        assert_eq!(json, r#"[{"type":"ChunkData","dim":1,"cx":-2,"cz":3,"data":[0,255]}]"#);++        // Size effect on a realistic full chunk payload.+        let data: Vec<u8> = (0..128 * 1024).map(|i| (i % 256) as u8).collect();+        let bin_len = encode_outbound_bin(&[chunk_msg(data.clone())]).len();+        let json_len = serde_json::to_string(&[chunk_msg(data)]).unwrap().len();+        assert!(bin_len < json_len / 3, "binary {bin_len} vs JSON {json_len}");+    }++    #[test]+    fn binary_frame_keeps_other_variants_as_json_and_rejects_garbage() {+        let player = PlayerDto { pos: Vec3::new(1.0, 2.0, 3.0), vel: Vec3::ZERO, yaw: 0.5, pitch: -0.2, on_ground: true, sneaking: false, gliding: false, health: 20.0 };+        let msgs = vec![+            NetMsg::PlayerTransform { device: "d1".into(), player },+            NetMsg::BlockEdit { dim: 0, x: 3, y: 64, z: -7, id: 12, meta: 5 },+            NetMsg::Join { device: "d1".into(), name: "Bob".into() },+        ];+        let back = decode_outbound_bin(&encode_outbound_bin(&msgs)).expect("frame must decode");+        assert_eq!(back.len(), 3);+        assert!(matches!(back[0], NetMsg::PlayerTransform { .. }));+        assert!(matches!(back[1], NetMsg::BlockEdit { x: 3, .. }));+        // Non-chunk JSON payloads are byte-identical to the legacy serde text.+        assert_eq!(serde_json::to_string(&back[1]).unwrap(), serde_json::to_string(&msgs[1]).unwrap());++        assert!(decode_outbound_bin(b"").is_none());+        assert!(decode_outbound_bin(b"NOPE").is_none());+        let good = encode_outbound_bin(&[chunk_msg(vec![1, 2, 3])]);+        assert!(decode_outbound_bin(&good[..good.len() - 1]).is_none(), "truncation must fail");+        assert!(decode_outbound_bin(&good[..4]).is_none());+    }+}
games/voxels/src/test/java/com/vayunmathur/games/voxels/network/OutboundFrameTest.kt
diff --git a/games/voxels/src/test/java/com/vayunmathur/games/voxels/network/OutboundFrameTest.kt b/games/voxels/src/test/java/com/vayunmathur/games/voxels/network/OutboundFrameTest.ktnew file mode 100644index 0000000000..4a2b48d78e--- /dev/null+++ b/games/voxels/src/test/java/com/vayunmathur/games/voxels/network/OutboundFrameTest.kt@@ -0,0 +1,116 @@+package com.vayunmathur.games.voxels.network++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking++/**+ * Binary Rust -> Kotlin outbound frame ([OutboundFrame]): chunk payloads+ * cross JNI as raw bytes, and the signed-op JSON reconstructed from them is+ * byte-identical to the legacy JSON-number representation, so signed ops,+ * PendingOps persistence/replay and the relay wire format do not change.+ */+class OutboundFrameTest {++    /** Builds a frame exactly as Rust `encode_outbound_bin` does (spec in OutboundFrame). */+    private fun frameOf(vararg msgs: OutboundFrame.Msg): ByteArray {+        val out = mutableListOf<Byte>()+        fun u32(v: Int) = repeat(4) { out += (v shr (8 * it)).toByte() }+        out += 'V'.code.toByte(); out += 'X'.code.toByte(); out += 'B'.code.toByte(); out += '1'.code.toByte()+        u32(msgs.size)+        for (m in msgs) when (m) {+            is OutboundFrame.Msg.Chunk -> {+                out += 1; out += m.dim.toByte(); u32(m.cx); u32(m.cz); u32(m.data.size)+                out += m.data.toList()+            }+            is OutboundFrame.Msg.SignedJson -> {+                out += 0; val b = m.text.encodeToByteArray(); u32(b.size); out += b.toList()+            }+            is OutboundFrame.Msg.TransformJson -> {+                out += 2; val b = m.text.encodeToByteArray(); u32(b.size); out += b.toList()+            }+        }+        return out.toByteArray()+    }++    private fun chunk(data: ByteArray) = OutboundFrame.Msg.Chunk(1, -2, 3, data)++    @Test fun chunkRoundTripsByteEqualAtAllSizes() {+        for (data in listOf(+            ByteArray(0),+            byteArrayOf(0xAB.toByte()),+            ByteArray(128 * 1024) { (it % 251).toByte() },+        )) {+            val decoded = OutboundFrame.decode(frameOf(chunk(data)))+            assertEquals(1, decoded.size)+            val back = decoded.single() as OutboundFrame.Msg.Chunk+            assertEquals(1, back.dim); assertEquals(-2, back.cx); assertEquals(3, back.cz)+            assertTrue(data.contentEquals(back.data), "chunk bytes changed at size ${data.size}")+        }+    }++    @Test fun goldenFrameDecodesAndOpsJsonIsByteIdentical() {+        // Same golden bytes pinned in Rust net_bin tests.+        val golden = "VXB1".encodeToByteArray() + byteArrayOf(+            1, 0, 0, 0, 1, 1, -2, -1, -1, -1, 3, 0, 0, 0, 2, 0, 0, 0, 0, -1+        )+        val msg = OutboundFrame.decode(golden).single() as OutboundFrame.Msg.Chunk+        assertTrue(byteArrayOf(0, -1).contentEquals(msg.data))+        // The signed string: exactly the legacy serde/JSONObject representation.+        assertEquals(+            """{"type":"ChunkData","dim":1,"cx":-2,"cz":3,"data":[0,255]}""",+            msg.toOpsJson()+        )+        assertEquals(+            """{"type":"ChunkData","dim":1,"cx":-2,"cz":3,"data":[]}""",+            chunk(ByteArray(0)).toOpsJson()+        )+        assertEquals(+            """{"type":"ChunkData","dim":1,"cx":-2,"cz":3,"data":[171]}""",+            chunk(byteArrayOf(0xAB.toByte())).toOpsJson()+        )+    }++    @Test fun mixedBatchKeepsOrderAndKinds() {+        val json = OutboundFrame.Msg.SignedJson("""{"type":"BlockEdit","dim":0,"x":3,"y":64,"z":-7,"id":12,"meta":5}""")+        val transform = OutboundFrame.Msg.TransformJson("""{"type":"PlayerTransform","device":"d1"}""")+        val decoded = OutboundFrame.decode(frameOf(json, chunk(byteArrayOf(9)), transform))+        assertEquals(listOf(json, transform), decoded.filter { it !is OutboundFrame.Msg.Chunk })+        assertEquals(chunk(byteArrayOf(9)), decoded[1])+    }++    @Test fun corruptFramesDecodeAsEmpty() {+        assertTrue(OutboundFrame.decode(ByteArray(0)).isEmpty())+        assertTrue(OutboundFrame.decode("NOPE........".encodeToByteArray()).isEmpty())+        val good = frameOf(chunk(byteArrayOf(1, 2, 3)))+        assertTrue(OutboundFrame.decode(good.copyOf(good.size - 1)).isEmpty(), "truncated")+        assertTrue(OutboundFrame.decode(good + byteArrayOf(0)).isEmpty(), "trailing byte")+    }++    @Test fun binaryIsRoughlyBytePerByteWhereJsonWasThreePlus() {+        val data = ByteArray(128 * 1024) { (it % 256).toByte() }+        val bin = frameOf(chunk(data))+        val opsJson = chunk(data).toOpsJson()+        // Frame: 1 byte/byte + 22 header bytes. Signed JSON: ~2-4 chars/byte.+        assertEquals(data.size + 22, bin.size)+        assertTrue(opsJson.length > bin.size * 2, "JSON ${opsJson.length} vs binary ${bin.size}")+    }++    /** Pending-ops replay is untouched: a signed chunk op persists + replays verbatim. */+    @Test fun pendingOpsReplayOfSignedChunkOpIsUnchanged() = runBlocking {+        val signedChunkOp = """{"author":"dev","sig":"AAAA","ops":""" ++            "\"" + chunk(byteArrayOf(0, -1)).toOpsJson().replace("\"", "\\\"") + "\"}"+        val store = InMemoryPendingOpsStore()+        val sent = mutableListOf<List<String>>()+        var online = false+        val queue = PendingOpQueue(store) { ops -> if (online) { sent += ops; true } else false }+        assertEquals(1, queue.enqueueAndFlush(listOf(signedChunkOp)))+        assertEquals(listOf(signedChunkOp), store.load())+        online = true+        val replayed = PendingOpQueue(store) { ops -> sent += ops; true }+        assertEquals(0, replayed.flushPending())+        assertEquals(listOf(listOf(signedChunkOp)), sent)+        assertTrue(store.load().isEmpty())+    }+}