Reaktor Struct
reaktor-struct is Reaktor's typed, verified, zero-copy binary record format and runtime. One Kotlin @Struct data class compiles into a fixed-offset layout that works identically in memory, across C++/Kotlin/TypeScript/Static Hermes/Python/C# FFI boundaries, inside mmap files or SQLite BLOB columns, and over the wire.
It replaces reaktor-flexbuffer, which is now deprecated. Unlike schemaless FlexBuffers (which paid key-lookup overhead and lacked verified schema fingerprints), reaktor-struct binds schemas once up front, reads fields at C-struct offsets with zero allocations, and strictly verifies untrusted bytes before any field is read.
Overview#
| Part | Module | What it owns |
|---|---|---|
| Annotations & Dual-Core Runtime | plane-origin/reaktor-struct | @Struct, @FieldId, @Hot, @Cold, C++23 Core A (src/commonMain/cpp), KMM Core B (src/commonMain/kotlin + platform backends), verifier, evolution, compaction, RS_DELTA, striped seqlocks |
| K2 Compiler Plugin | plane-origin/reaktor-compiler-plugin | Automatic @JvmRecord synthesis on immutable JVM @Struct classes, Str16.eqConst two-word lowering, zero-allocation IR optimizations |
| KSP2 Polyglot Codegen | plane-origin/reaktor-ksp | Generates Kotlin View/Ref/ArrayView/Codec/Snapshot, C++23 *.rstruct.hpp, TypeScript/Static Hermes *.rstruct.ts, Python Py_buffer C-API extension, and C# readonly ref struct |
| Single Source of Truth | reaktor-struct/spec/rev4.spec.json | Magic bytes, header/shape/field offsets, slot kind IDs, feature flags and canonical error codes emitted into both C++23 and Kotlin |
Authoring with @Struct#
Declare the model once in commonMain — no .proto or .fbs schema files and no hand-written DTO mappers:
@Struct(
layout = Layout.ROW, // ROW (default) | TILED_64 (64-row AoSoA micro-columns)
evolution = Evolution.STRICT, // enforces stable @FieldId bindings
)
data class Person(
@FieldId(1) val id: Long,
@FieldId(2) @Hot val score: Double,
@FieldId(3) val balance: Double,
@FieldId(4) @Hot val age: Int,
@FieldId(5) @Hot val level: Int,
@FieldId(6) @Hot val active: Boolean,
@FieldId(7) val name: String,
@FieldId(8) val email: String,
)
What the plane-origin compiler stack does automatically:
- Automatic
@JvmRecordon JVM: On JVM targets,reaktor-compiler-pluginsynthesizes@kotlin.jvm.JvmRecord(extends java.lang.Record) for every immutable@Struct data class(val-only) so single snapshots carry trusted final fields and Valhalla value-class compatibility without boilerplate. Mutable@Structclasses (varfields) skip@JvmRecordon the class itself and receive a mutable zero-copyRefplus an immutable@JvmRecord Snapshotprojection. - Zero-allocation views:
reaktor-kspemitsPersonView,PersonArrayView,PersonBuilder, andPersonCodecalongside matching C++23 (Person.rstruct.hpp), TypeScript/Static Hermes, C#, and Python bindings. - Compile-time
Str16lowering: Short-string comparisons likeStr16.eqConst(buf, off, "Asha K")are lowered in K2 IR directly to two 64-bit integer comparisons (Str16.eqWords) on 64-bit targets — or four 32-bitIntcompares on JS/Wasm to avoid Kotlin/JSLongboxing.
Block layout and Str16#
Five layout laws give reaktor-struct its speed and safety:
- Fixed-offset C-struct rows. Fields are sorted by descending alignment with
Booleans and presence bitmasks packed cleanly. A record has zero per-row header and zero tag overhead. - Position independence. Every internal reference is a 32-bit count of 8-byte words from the start of the block (
offset = ref << 3), reaching 32 GiB without pointer swizzling. A block can bemmap()ed, moved across processes, or copied over the network without fixups. Str16andBytes16slots. Every string or byte field occupies 16 bytes inline:[u32 length][12 bytes UTF-8]whenlength <= 12(zero heap indirection), or[u32 length][8-byte prefix][u32 heap_ref]when longer (filtering rejects mismatches on the 8-byte inline prefix without touching the heap).- Canonical 128-bit digest (
FEAT_CANONICAL_DIGEST). Header bytes48..63hold the truncated SHA-256 digest of the canonical image, giving O(1) block equality, HTTPETags, cache keys, and delta base verification. - Interned leaf strings (
FEAT_STRING_INTERN_POOL). Frozen blocks can deduplicate repeated strings (IDs, URIs, file paths, module names) into a shared read-only pool while remaining strictly acyclic because strings are leaves.
Verification before reading#
Untrusted bytes always pass BlockVerifier.verify(bytes) (KMM) or rs::verify(bytes) (C++23) before a view is opened. The verifier checks magic/version, image length, 8-byte alignment, shape-table integrity, bounds, zeroed padding, bool ∈ {0, 1}, strict UTF-8, Str16 prefix agreement, acyclicity, and the Rule of One Owner (via an ownership bitmap, with shared leaves permitted only under FEAT_STRING_INTERN_POOL). Both cores return the exact same (RsStatus, byteOffset) on every malformed input.
Dual-core parity (C++23 + KMM)#
reaktor-struct ships two co-equal, 100% wire-compliant cores rather than forcing every runtime through FFI or accepting managed-only overhead:
- Core A (
C++23,src/commonMain/cpp): Zero dependencies,-fno-exceptions -fno-rtti, NEON/AVX2/Wasm-simd128scan and filter kernels, and 4 KiB stripedstd::atomic_refseqlocks for lock-free concurrent reads. Directly powers C++, Python (Py_bufferC-API extension), Static Hermes (-typedc_ptr), Android JNI bulk kernels, Swift/C++ interop, and Wasm32. - Core B (
KMM,src/commonMain/kotlin): Pure Kotlin Multiplatform with target-specialized memory backends:jvmMain(JDK 25):VarHandle+ Foreign Function & Memory (MemorySegment) zero-copy views.androidMain: API-26+ little-endian byte ops for point reads, with C++ JNI bulk offload for large scans.iosMain/ Kotlin/Native: LLVMByteArray.getLongAt/setLongAtintrinsics (measured 5.0× faster than cinteropCPointer) plususePinnedzero-copy C++ handoff.jsMain: 32-bit-half operations avoiding Kotlin/JS boxed 64-bitLongemulation (eliminating a measured 215× cliff).
Parity is enforced continuously by parity/run_parity.py: 13/13 canonical wire fixtures assert sha256(cpp) == sha256(kmm) (up to 1.92 MB), 3/3 ping-pong compaction tests verify C++ → KMM → C++ mutation/compaction equivalence, and 1,024 differential fuzz cases verify identical accept/reject (status, offset) under Release -O3 and ASan/UBSan with zero divergences.
Schema evolution, concurrency and RS_DELTA#
- Schema binding (
bind_shape): Every block embeds its shape table. When the reader's 64-bit structural fingerprint matches the block's shape, reads use compile-time constant offsets directly. When the schema evolved compatibly (added optional fields, dropped unused fields, reordered fields, or lossless numeric widening such asi32 → i64orf32 → f64),bind_shapebuilds a compactBindPlantable once. Incompatible changes are rejected immediately with the name of the missing or conflicting field. - Frozen vs.
SharedBlock: Read-only blocks pay zero lock overhead. When multiple threads or OS processes (mmap) share a mutable block,SharedBlockplaces 4 KiB striped sequence locks in an adjacent handle so concurrent readers validate consistent snapshots without blocking the single writer. - Sparse delta patches (
RS_DELTA):BlockDelta.diff(base, next)emits an envelope anchored to the base block's 128-bit digest plus only the changed 8-byte word runs.BlockDelta.apply(base, delta)verifies the base digest, applies the patch, and updates the digest — enabling O(changed bytes) WebSocket, IPC, andreaktor-dbjournal updates.
Measured hardware performance#
Measured across 2,546 verified runs (0 checksum mismatches) on Apple M4 Pro, physical Samsung Galaxy S23 Ultra (Android 17), physical iPhone 14 Pro (iOS 26.5), Static Hermes (static_h), WebAssembly, and Chrome 158 (n = 20,000 records, median ns/record):
| Target / Language | reaktor-struct scan | reaktor-struct wire_scan | Speedup vs. JSON (wire_scan) | Speedup vs. Protobuf (wire_scan) |
|---|---|---|---|---|
| C++23 (Apple M4 Pro) | 0.66 ns | 1.85 ns | 214× | 40× |
| Kotlin JVM (JDK 25 FFM) | 0.63 ns | 1.63 ns | 204× | 35× |
Python 3.14 (Py_buffer C-ext) | 0.61 ns | 1.53 ns | 250× (orjson) | 118× (upb) |
C# .NET 11 (readonly ref struct) | 0.68 ns | 1.55 ns | 297× | 159× |
| Kotlin/Native (iPhone 14 Pro) | 0.98 ns | 3.95 ns | 288× | 53× |
Static Hermes -typed (M4 Pro / S23) | 1.09 / 2.12 ns | 4.47 / 10.74 ns | 54×–140× | 154× (S23) |
| Chrome 158 TypeScript (TypedArray) | 1.16 ns | 3.67 ns | 115× | 42× |
Scanning and strictly verifying 200,000 records (19.2 MB) takes 0.31–0.35 ms on JVM/Python/C# (~4% of a 120 Hz frame) and 0.79 ms on iPhone 14 Pro (~9.5% of a 120 Hz frame).
Migrating from deprecated reaktor-flexbuffer#
reaktor-flexbuffer and FlexCoderProcessor are deprecated across the monorepo:
| Deprecated FlexBuffer API | reaktor-struct replacement |
|---|---|
Reaktor.Flexbuffer dependency | Reaktor.Struct (plus Reaktor.Ksp and Reaktor.CompilerPlugin) |
@dev.shibasis.reaktor.flexbuffer.core.Struct | @dev.shibasis.reaktor.struct.Struct + @FieldId(n) |
FlexCoderProcessor (reaktor-compiler) | StructKspProcessor (reaktor-ksp) |
FlexBuffers.encode / FlexBuffers.decode | Generated TCodec / BlockBuilder + BlockVerifier + zero-copy TView |
FlexPayload (reaktor-ffi) | reaktor-struct blocks over reaktor-ffi + reaktor-service |
Limitations#
- Visibility:
reaktor-structstaysPrivateinReaktorPlanes.ktuntil its companion research paper moves out ofreaktor/plane-origin/reaktor-struct/paper/into the rootpapers/directory; all source code and compiler plugins outsidepaper/are already public-clean. - Not a replacement for public JSON APIs or compressed archives: External REST APIs remain JSON (
reaktor-serviceWire.Plain), and long-term archival still pairsreaktor-structblocks with zstd/Brotli when wire bandwidth dominates over zero-copy random access. - Inline discriminated unions &
TILED_64codegen:BlockBuilder/BlockVerifiersupport Rev 4 features today; full KSP2 codegen forsealed interfaceinline unions andTILED_64AoSoA views is staged alongsidereaktor-ffiadoption.
Reference#
| Path | Owns |
|---|---|
reaktor/plane-origin/reaktor-struct/ | Unified dual-core module (src/commonMain/{cpp,kotlin}, platform backends, spec/rev4.spec.json, parity/run_parity.py, bench/) |
reaktor/plane-origin/reaktor-ksp/ | ReaktorKspProvider and struct/emit/*StructEmitter.kt (Kotlin, C++23, TS, Static Hermes, C#, Python) |
reaktor/plane-origin/reaktor-compiler-plugin/ | ReaktorCompilerPluginRegistrar, @JvmRecord FIR/IR synthesis, Str16 word lowering |
Verification commands:
(cd dependeasy && ./gradlew :model:test --tests "*PlacementKernelTest*")
(cd reaktor && ./gradlew :reaktor-compiler-plugin:jar :reaktor-ksp:jar :reaktor-struct:jvmTest :reaktor-struct:testDebugUnitTest :reaktor-struct:jsNodeTest)
python3 reaktor/plane-origin/reaktor-struct/parity/run_parity.py
- Unified FFI and RPC builds its zero-copy inter-runtime ABI directly on
reaktor-struct. - Service layer uses
reaktor-structfor its binaryWire.Structfast path. - FlexBuffer (Deprecated) records the superseded format and historical measurements.