Skip to content
7 min readUpdated 24 Nov 2026

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#

How reaktor-struct works. One @Struct Kotlin data class compiles through reaktor-compiler-plugin (K2 FIR/IR automatic @JvmRecord and Str16 lowering) and reaktor-ksp (polyglot emitters for Kotlin, C++23, TypeScript, Static Hermes, C# and Python) onto two bit-identical reference cores (Core A C++23 and Core B KMM) derived from spec/rev4.spec.json. One verified binary block serves memory, FFI calls, mmap storage and the wire with zero re-encoding.@Struct data class Person (single Kotlin source of truth)@FieldId(1) val id: Long · @FieldId(2) @Hot val score: Double · @FieldId(3) val name: StringNo .proto or .fbs IDL. Layout order, alignment, evolution IDs and fingerprints derive from one class.Immutable classes automatically receive @JvmRecord on JVM; mutable var classes emit Ref + @JvmRecord Snapshot.reaktor-compiler-plugin (K2 FIR + IR · plane-origin)Auto @JvmRecord + java.lang.RecordStr16.eqConst → 2-word Long cmpZero-alloc View scalarizationTarget-aware ART / JS / Native IRreaktor-ksp (KSP2 Polyglot Codegen · plane-origin)Kotlin View/Ref/CodecC++23 *.rstruct.hppTS & Static HermesPython Py_buffer extC# readonly ref structSwift C++23 interopDUAL-CORE PARITY RUNTIME (spec/rev4.spec.json · sha256(cpp) == sha256(kmm) · 1,024-case differential fuzz)Core A · C++23 + C ABI (libreaktor_struct)NEON / AVX2 / simd128 · 4 KiB striped std::atomic_ref seqlocksPowers C++, Python Py_buffer (0.61 ns), Static Hermes (1.09 ns), Android JNI bulk, Swift & Wasm32Core B · Pure KMM (reaktor-struct)JVM FFM (0.63 ns) · K/N LLVM getLongAt (0.67–0.98 ns) · ART · JS 32-bitZero-FFI managed path across Android, iOS, Desktop, Server, Browser & Cloudflare WorkersOne Verified, Position-Independent Binary Block (identical bytes everywhere)In-memory records & ArrayViewSame-process FFI & SharedBlockmmap cold-start DB & SQLite BLOBWire RPC & RS_DELTA sparse patches
One Kotlin declaration generates zero-copy views across every language and runs on two bit-for-bit compliant cores locked to a single machine-readable specification.
PartModuleWhat it owns
Annotations & Dual-Core Runtimeplane-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 Pluginplane-origin/reaktor-compiler-pluginAutomatic @JvmRecord synthesis on immutable JVM @Struct classes, Str16.eqConst two-word lowering, zero-allocation IR optimizations
KSP2 Polyglot Codegenplane-origin/reaktor-kspGenerates 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 Truthreaktor-struct/spec/rev4.spec.jsonMagic 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 @JvmRecord on JVM: On JVM targets, reaktor-compiler-plugin synthesizes @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 @Struct classes (var fields) skip @JvmRecord on the class itself and receive a mutable zero-copy Ref plus an immutable @JvmRecord Snapshot projection.
  • Zero-allocation views: reaktor-ksp emits PersonView, PersonArrayView, PersonBuilder, and PersonCodec alongside matching C++23 (Person.rstruct.hpp), TypeScript/Static Hermes, C#, and Python bindings.
  • Compile-time Str16 lowering: Short-string comparisons like Str16.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-bit Int compares on JS/Wasm to avoid Kotlin/JS Long boxing.

Block layout and Str16#

reaktor-struct Rev 4 binary block layout. Bytes 0 to 63 hold the fixed header including magic, version, feature flags, root Any slot and 128-bit canonical digest. Following the header are the embedded shape table with 64-bit structural fingerprints, fixed-offset typed rows with 16-byte Str16 slots (inline up to 12 bytes, or 8-byte prefix plus 32-bit 8B-aligned heap ref), and the append-only heap and interned string pool. Below: schema binding (exact fingerprint gives constant offsets, compatible evolution builds a bind plan, incompatible rejects by field name) and RS_DELTA sparse patching.ONE SELF-DESCRIBING REV 4 BLOCK (8-BYTE ALIGNED · 32-BIT OFFSETS UP TO 32 GiB · NO ABSOLUTE POINTERS)64 B Block Header0..7 magic "RSTR" + v1.08..15 features + image_len24..47 shapes_ref + root_any48..63 canonical_digest128Embedded Shape Table64-bit SHA-256 fingerprintrow_size · align · presence_offfield names, kinds & offsetsChecked once at bind timeFixed-Offset Typed RowsNo per-row headers or field tagsAligned scalars · packed boolsPresence bits · Str16 / Bytes16ROW or 64-row TILED_64 columnsHeap & Interned PoolLong UTF-8 (>12 B) & BytesNested arrays & SipHash mapsSTRING_INTERN_POOL dedupStrict One-Owner / acyclic verifySTR16: 16-BYTE INLINE OR PREFIXED UTF-8 SLOTShort string (len ≤ 12 B)[u32 len][12 B inline UTF-8]Zero pointer chase · 2-word compareLong string (len > 12 B)[u32 len][8 B prefix][u32 ref]Fast reject on prefix before heap loadSCHEMA EVOLUTION (bind_shape) & STRICT VERIFICATIONExact fingerprintCompile-time offsetsZero indirectionCompatible driftBindPlan table (adds,drops, i32→i64 widen)IncompatibleRefused before readwith field nameMUTATION, CONCURRENCY & INCREMENTAL SYNC (ZERO COST FOR READ-ONLY BLOCKS)Frozen Block (Immutable)Verified once · zero locks · O(1) digest equalityIdeal for mmap caches, wire frames & SQLite BLOBsSharedBlock (4 KiB Striped Seqlocks)Single writer + lock-free concurrent readersShared across threads or OS processes via mmapRS_DELTA Sparse Patch Envelope128-bit base digest + changed 8-byte word runsO(changed bytes) IPC, WebSocket & DB journals
A block carries no per-record headers, no field tags and no absolute pointers. Every reference is an 8-byte-scaled 32-bit offset valid at any base address up to 32 GiB.

Five layout laws give reaktor-struct its speed and safety:

  1. 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.
  2. 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 be mmap()ed, moved across processes, or copied over the network without fixups.
  3. Str16 and Bytes16 slots. Every string or byte field occupies 16 bytes inline: [u32 length][12 bytes UTF-8] when length <= 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).
  4. Canonical 128-bit digest (FEAT_CANONICAL_DIGEST). Header bytes 48..63 hold the truncated SHA-256 digest of the canonical image, giving O(1) block equality, HTTP ETags, cache keys, and delta base verification.
  5. 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-simd128 scan and filter kernels, and 4 KiB striped std::atomic_ref seqlocks for lock-free concurrent reads. Directly powers C++, Python (Py_buffer C-API extension), Static Hermes (-typed c_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: LLVM ByteArray.getLongAt/setLongAt intrinsics (measured 5.0× faster than cinterop CPointer) plus usePinned zero-copy C++ handoff.
    • jsMain: 32-bit-half operations avoiding Kotlin/JS boxed 64-bit Long emulation (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 as i32 → i64 or f32 → f64), bind_shape builds a compact BindPlan table 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, SharedBlock places 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, and reaktor-db journal 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 / Languagereaktor-struct scanreaktor-struct wire_scanSpeedup vs. JSON (wire_scan)Speedup vs. Protobuf (wire_scan)
C++23 (Apple M4 Pro)0.66 ns1.85 ns214×40×
Kotlin JVM (JDK 25 FFM)0.63 ns1.63 ns204×35×
Python 3.14 (Py_buffer C-ext)0.61 ns1.53 ns250× (orjson)118× (upb)
C# .NET 11 (readonly ref struct)0.68 ns1.55 ns297×159×
Kotlin/Native (iPhone 14 Pro)0.98 ns3.95 ns288×53×
Static Hermes -typed (M4 Pro / S23)1.09 / 2.12 ns4.47 / 10.74 ns54×–140×154× (S23)
Chrome 158 TypeScript (TypedArray)1.16 ns3.67 ns115×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 APIreaktor-struct replacement
Reaktor.Flexbuffer dependencyReaktor.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.decodeGenerated TCodec / BlockBuilder + BlockVerifier + zero-copy TView
FlexPayload (reaktor-ffi)reaktor-struct blocks over reaktor-ffi + reaktor-service

Limitations#

  • Visibility: reaktor-struct stays Private in ReaktorPlanes.kt until its companion research paper moves out of reaktor/plane-origin/reaktor-struct/paper/ into the root papers/ directory; all source code and compiler plugins outside paper/ are already public-clean.
  • Not a replacement for public JSON APIs or compressed archives: External REST APIs remain JSON (reaktor-service Wire.Plain), and long-term archival still pairs reaktor-struct blocks with zstd/Brotli when wire bandwidth dominates over zero-copy random access.
  • Inline discriminated unions & TILED_64 codegen: BlockBuilder/BlockVerifier support Rev 4 features today; full KSP2 codegen for sealed interface inline unions and TILED_64 AoSoA views is staged alongside reaktor-ffi adoption.

Reference#

PathOwns
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