Skip to content

Architecture

How the pieces fit together.

Runtime Layers

Desktop and Android share the same high-level Kanama model: Kotlin user code is registered through generated metadata, the binding layer implements Godot's script/resource contracts, and an FFM layer calls the GDExtension ABI. The platform split is the runtime underneath that FFM layer.

iOS reuses the same generated-wrapper API surface but swaps the runtime entirely: no JVM and no FFM. A Kotlin/Native static library linked into the app's .xcframework calls a C GDExtension shim, and ObjectCalls is implemented over the shim's generic ptrcall dispatch instead of Panama. See iOS.

Desktop

flowchart TB
    subgraph PROJECT["Godot project"]
        USER["User Kotlin code<br/>@ScriptClass / @GlobalClass"]
        KSP["KSP-generated registrars<br/>KanamaRegistry / KanamaClassRegistry / KanamaScriptRegistry"]
    end

    subgraph JVM["Desktop JVM (JDK 25)"]
        BINDING["Kanama binding layer<br/>ScriptLanguage, resources, ObjectRegistry"]
        FFM["Panama FFM<br/>java.lang.foreign Linker / MethodHandle"]
    end

    BOOT["bootstrap.c<br/>JNI_CreateJavaVM once"]
    GODOT["Godot Engine<br/>GDExtension ABI"]

    USER -->|"compile-time metadata"| KSP
    KSP -->|"static registration"| BINDING
    GODOT -->|"dlopen .dylib / .so / .dll<br/>GDExtension entry symbol"| BOOT
    BOOT -->|"starts JVM and calls KanamaBinding.init"| BINDING
    BINDING -->|"downcalls / upcall stubs"| FFM
    FFM <-->|"C ABI: gdextension_interface.h"| GODOT

On desktop, everything above bootstrap.c is JVM bytecode. Everything below is Godot. The native bootstrap exists only because Godot loads a native .dylib/.so/.dll and we need somewhere to call JNI_CreateJavaVM from. After that one call, all boundary crossings happen through Panama MethodHandles, not JNI.

Android

flowchart TB
    subgraph PROJECT["Godot Android project"]
        USER["User Kotlin code<br/>demo scripts + generated KSP registrars"]
        GDAP["Android plugin descriptor<br/>KanamaAndroid.gdap"]
    end

    subgraph APK["Exported Android APK"]
        PLUGIN["Godot Android plugin AAR<br/>KanamaAndroid"]
        ART["Android ART runtime<br/>Kanama runtime + scripts"]
        PORT["PanamaPort FFM<br/>com.v7878.foreign"]
        SO["libkanama_bootstrap.so<br/>Android native bootstrap"]
    end

    GODOT["Godot Engine Android<br/>GDExtension ABI"]

    USER -->|"packaged into AAR / APK"| ART
    GDAP -->|"enables plugin during export"| PLUGIN
    PLUGIN -->|"loads native library<br/>captures Android JavaVM"| SO
    SO -->|"initializes Kanama on ART"| ART
    ART -->|"registration, resources, script instances"| PORT
    PORT <-->|"C ABI: gdextension_interface.h"| GODOT
    GODOT -->|"loads Android GDExtension entry"| SO

Android does not embed a desktop JDK. The exported game runs on Android ART and uses PanamaPort as the FFM layer. The Android plugin AAR packages the native bootstrap, Kanama runtime, project scripts, and generated registrars so Godot can initialize the same script language/resource-loader model inside the APK.

iOS

flowchart TB
    subgraph PROJECT["Godot iOS project"]
        USER["User Kotlin code<br/>demo scripts + generated KSP registrars"]
        EXPORT["Godot iOS export<br/>GDExtension entry"]
    end

    subgraph APP["Exported iOS app (.xcframework, device arm64)"]
        KN["Kotlin/Native runtime<br/>Kanama runtime + scripts, RawSegment aliases the MemorySegment shim"]
        WRAP["Shared generated wrappers<br/>src/commonMain api tree, the same files desktop/Android compile"]
        OC["ObjectCalls (iOS actual)<br/>typed ptrcall helpers"]
        SHIM["C GDExtension shim<br/>entry, get_method_bind, generic ptrcall dispatch"]
    end

    GODOT["Godot Engine iOS<br/>GDExtension ABI"]

    USER -->|"compiled into Kotlin/Native lib"| KN
    EXPORT -->|"packs xcframework into iOS app"| APP
    GODOT -->|"loads iOS GDExtension entry symbol"| SHIM
    SHIM -->|"initializes Kanama on Kotlin/Native"| KN
    KN -->|"registration, resources, script instances"| WRAP
    WRAP -->|"cached MethodBind + typed ptrcall"| OC
    OC -->|"one generic typed ptrcall dispatch"| SHIM
    SHIM <-->|"C ABI: ptrcall / object_method_bind_call"| GODOT

iOS embeds no JVM and no Panama/FFM. A Kotlin/Native static library is linked into the app's .xcframework, and the C shim exposes a single generic typed ptrcall dispatch that drives every wrapper shape — so the same generated wrapper API as desktop/Android runs on device with the platform seam isolated in ObjectCalls. iOS is Supported on 4.7 stable; see the iOS and iOS backend architecture for the current validation state and remaining support gates.

Initialization

This runs once, when Godot loads the extension.

sequenceDiagram
    autonumber
    participant G as Godot Engine
    participant B as bootstrap.c
    participant J as "JVM (libjvm)"
    participant K as KanamaBinding.kt

    G->>B: dlopen libkanama_bootstrap.dylib
    G->>B: kanama_entry(procAddr, library, init*)
    B->>J: JNI_CreateJavaVM
    B->>K: static KanamaBinding.init(procAddr, library, init*)
    Note over K: Wrap procAddr as a Panama MethodHandle. Call it for every GDExtension function we need, cache each as a Linker.downcallHandle in GodotFFI.
    K->>K: Fill *init with upcall stubs (initialize / deinitialize callbacks)
    K-->>B: return true
    B-->>G: return GDEXTENSION_INITIALIZATION_SCENE
    Note over G,K: From here on, all calls are direct Godot ⇄ JVM via Panama. Bootstrap is done.
    G->>K: initialize(level=SCENE) [upcall]
    K->>G: classdb_register_extension_class6(...) [downcall]

Key points:

  • bootstrap.c runs once and stops. It does not stay in the call path. After step 6 the C frame returns and is never re-entered.
  • The bootstrap chooses the JVM options. The classpath, native access, the JNI exit hook, JDWP when configured, then the user's options — from kanama-jvm-options.txt next to kanama.jar (exported games), the project setting kanama/jvm/options, then KANAMA_JVM_OPTIONS — and no heap or GC option of Kanama's own. They are JNI options, which HotSpot treats as command-line ones; G1 ignores young-generation sizes from JAVA_TOOL_OPTIONS. See Export for Desktop → JVM Options for the young-generation cap recommended to games that spawn many objects at once.
  • The proc-address getter is the only thing C hands to Kotlin. A single long. Everything else Kotlin needs, it asks for itself via that getter.
  • Class registration happens during the initialize upcall, not during bootstrap.c. Godot calls us back when it's ready for us to register — we don't push.
  • Every native call adapter is generated before the upcall stubs are installed. Linking a downcall handle for a FunctionDescriptor the process has not seen makes the JVM generate native code (a downcall stub blob plus a specialized binding class). Doing that while execution is already inside a Godot→JVM upcall puts code generation inside a thread-local executable-memory transition, so KanamaBinding.init calls NativeCallSurface.prewarm() first and an upcall only ever executes adapters that already exist.

Linker caches per descriptor, not per symbol, so the whole backend collapses onto 20 shapes — binding an engine function pointer to an already-linked shape generates nothing. scripts/check_native_call_surface.py fails the build if a source change introduces a shape that is not prewarmed, and KANAMA_TRACE_NATIVE_ADAPTERS=1 prints each adapter with a timestamp plus the first-upcall boundary (the runtime, tool, and hot-reload smokes assert no adapter appears after it).

Upcall stubs are the deliberate exception: each stub is its own native blob, and stubs for @RegisterClass / @ScriptClass members can only be built once those classes are known, which is inside the initialize upcall. The engine offers no earlier registration point.

Runtime Crossings

Two directions, both via Panama, each with its own mechanism:

flowchart LR
    subgraph JVM["JVM process"]
        UK["User Kotlin<br/>(MyNode.takeDamage)"]
        BIND["Binding layer<br/>(ClassRegistrar, Variant)"]
        SB["ScriptBridge<br/>generated dispatch slots"]
        FFI["GodotFFI<br/>downcall handles"]
        STUBS["KanamaBinding<br/>upcall stubs"]
    end
    subgraph NAT["Native"]
        GODOT["Godot Engine"]
    end

    UK -->|"Kotlin call"| BIND
    BIND -->|"MethodHandle.invokeExact"| FFI
    FFI ==>|"Panama downcall"| GODOT
    GODOT ==>|"Panama upcall"| STUBS
    STUBS -->|"script callback"| SB
    SB -->|"direct _process / _physics_process"| UK
    SB -->|"generic method/property dispatch"| BIND
  • Downcalls (JVM → Godot) — Linker.downcallHandle(addr, descriptor) produces a MethodHandle the JIT can inline through. Used for everything: classdb_register_extension_class6, object_method_bind_call, variant_new_copy, etc. The handles every wrapper call goes through (object_method_bind_ptrcall, object_get_instance_id, the freed-object check's object_get_instance_from_id, the String helpers) are JVM constants — @JvmField in a holder object, so static final — called with invokeExact on their exact type: the JIT folds them into the call site, with no Lazy read, generic invoker or asType per call (task 131 item 16). A pointer the caller only compares comes back as JAVA_LONG, so it allocates no MemorySegment. Keep each invokeExact a statement in a block-bodied function (ObjectCalls.bindPtrcall): as the last expression of a lambda or a try, Kotlin types it Object and the call throws WrongMethodTypeException. Android rewrites invokeExact to invokeWithArguments in its source remap (see backends/android.md).
  • Upcalls (Godot → JVM) — Linker.upcallStub(handle, descriptor, arena) produces a function pointer that, when called from C, lands inside a JVM method. Used for: lifecycle callbacks (initialize, deinitialize), per-instance virtual dispatch (_ready, _process), and class create/free hooks. Every stub goes through Upcalls.stub, which wraps the target in MethodHandles.catchException: a Throwable that escapes a callback is logged ([kanama] upcall <site> threw: …), reported to Godot as a script error (ScriptErrors, task 131: print_script_error_with_message with the Kotlin file:line of the top game frame, so it reaches the editor's Errors tab and not only stderr), and replaced by the zero of the return type instead of unwinding through native frames and aborting the process (task 98). Handlers whose return value carries meaning (siCall's call error, the property accessors' "owned, write rejected") keep their own catch on top, and report the same way.

Hot runtime paths keep the same ABI but avoid unnecessary JVM-side work:

  • KSP-generated script registrars provide direct lambdas for _process(delta) and _physics_process(delta). ScriptBridge.call_func checks those slots before the generic StringName when dispatch, so frame callbacks still enter through Godot's ScriptInstance vtable but skip the generated method switch.
  • ObjectRegistry keeps the monotonic handle map as the source of truth and mirrors dense low handles into an atomic array. ScriptInstance callbacks use the array for the common handle range and fall back to the map for oversized handles, preserving handle 0 invalidity and unregister cleanup semantics.
  • ObjectCalls uses small thread-local scratch buffers for selected high-rate ptrcall shapes, such as scalar float, Vector2, and draw-texture calls. These buffers are ordinary FFM MemorySegments reused by the current JVM thread, replacing fresh Arena.ofConfined() allocations for calls that do not retain argument memory after the ptrcall returns.
  • Typed object-array decoders can wrap elements directly as the requested type. For example, Array[Node] results no longer need a temporary GodotObject wrapper for each element before becoming Node.

The scratch buffers are a per-thread cache of tiny native argument/return slots, not a cache of Godot objects or Variant values. A ptrcall wrapper may use them only when the call is synchronous and Godot consumes the argument memory before returning. If Godot can retain the memory, the wrapper must still use an owned arena with the correct lifetime.

For real demo hot paths, separate downcall-heavy code from callback-heavy code before adding more helpers. Scratch buffers are most useful when Kotlin is calling many small Godot methods each frame, such as viewport, transform, input, or draw calls. If profiling points at repeated Godot→JVM ScriptInstance callbacks instead, the larger win is usually to reduce callback count, batch state on a parent script, or move repeated queries out of per-node callbacks; the registry and dispatch fast paths only run after the FFM upcall boundary has already been crossed.

Where JNI shows up — and where it doesn't. Panama (FFM) handles the JVM→native direction beautifully, but it has no story for creating a JVM from C in the first place. So bootstrap.c makes a handful of JNI calls, once, during startup:

  1. JNI_CreateJavaVM — bring a JVM into existence inside Godot's process (on Android the same file attaches to the existing ART VM instead, via GetJavaVM/AttachCurrentThread)
  2. FindClass("KanamaBinding") + GetStaticMethodID — locate the Kotlin entry point
  3. CallStaticVoidMethod(init) — hand off control, wrapped in ExceptionCheck/ExceptionDescribe so a failed init is reported, not lost

The moment that init call returns, JNI is done. Forever. No RegisterNatives, no further FindClass, no more JNI in any call path. From that point on, Godot ⇄ JVM traffic is only Panama: downcallHandle for JVM→Godot calls and upcallStub for Godot→JVM callbacks.

The only way to eliminate even those startup JNI calls would be GraalVM native-image (AOT-compile Kotlin to a native library that exports real C symbols). That's a different runtime — no JIT, no hot reload — and explicitly not the path Kanama is taking.

FFM Scalar Precision

Godot uses two related but different floating-point layouts at the FFM boundary:

  • Value-type components are stored as real_t in engine buffers. Vector2, Vector3, Basis, Transform3D, and similar built-ins expose Double in Kotlin and store their components at the same width (task 134): the generated internal GodotRealStorage — Float for normal single-precision Godot builds, Double for precision=double builds (Color is always Float). Constructors round with the generated internal inline narrowReal, properties widen with widenReal, the real_t formulas live once in types/shared/RealMath.kt (also compiled by web-runtime, whose WebReal.kt supplies the float32 storage), and the marshalling moves the stored values unconverted (GodotRealSegment.readRaw/writeRaw, the value types' internal raw factories and rawX… fields); GodotRealSegment.readIndex/writeIndex are the Double pair the generated script registrars use.
  • Scalar float method parameters and return values use the Variant float ABI slot, which is 64-bit. In ObjectCalls, helpers for scalar method arguments named float must allocate/read JAVA_DOUBLE, not JAVA_FLOAT.
  • Color components are fixed 32-bit floats in the engine (Color is not real_t) and Double in Kotlin; marshalling narrows with .toFloat() and widens with .toDouble().

This distinction matters because Godot API docs and extension_api.json call both scalar method values and value-type components "float". Wrapper work must check the ABI shape, not only the display name. JAVA_FLOAT in ObjectCalls.kt should be limited to fixed 32-bit component storage such as Color, while scalar method float helpers should use JAVA_DOUBLE.

The same split runs through the value types themselves, and it is the reason they can be shared: a value type is written into a builtin-call frame slot as its components at the real_t storage width (BuiltinFrame.putReal; int32 for Vector2i-style types, float32 for Color), while a scalar float argument travels as an 8-byte double (putDouble).

Object Handle and Raw Pointer

A wrapper's identity is net.multigesture.kanama.api.GodotHandle, a zero-cost @JvmInline value class that is the only handle type a public signature may name. It is ONE shared file in src/commonMain/kotlin/net/multigesture/kanama/api, because what it wraps is now also Kanama-named: net.multigesture.kanama.binding.runtime.RawSegment, the raw engine pointer, declared as a plain typealias once per backend — the FFM MemorySegment on desktop (com.v7878.foreign.MemorySegment after the Android remap), the Kotlin/Native shim of the same name on iOS — with the null pointer beside it as a top-level NULL_SEGMENT. Web declares its own GodotHandle under the same fully-qualified name over a generation-tagged registry id.

Nothing in src/commonMain — the value types, the seams and the whole API wrapper tree — names a java.lang.foreign type, because a KMP commonMain can neither declare nor expect a JDK package: RawSegment is expect sealed interface RawSegment with NULL_SEGMENT an expect val, and each platform actualizes them over its own pointer type (the FFM MemorySegment on desktop, the Kotlin/Native shim on iOS). The runtime seam (ObjectCalls, GodotObject.requireOpenHandle(), the KSP glue) carries RawSegment throughout.

Value Types

The 19 Godot builtin value types (Vector2, Vector3, Basis, Transform3D, Quaternion, AABB, Plane, RID, …) are ONE hand-written set under src/commonMain/kotlin/net/multigesture/kanama/types, the module's KMP common fragment beside the generated wrapper tree: the JVM target, the two iOS targets and the Android copy task all compile those files. Only Real.kt is per platform — generated at build time on desktop, hand-written on iOS, written by the plugin build script on Android. The Web build compiles the same files too: web-runtime adds the whole types directory as a source directory and supplies its own internal real_t half (WebReal.kt) and its own BuiltinFrame (web-runtime/.../binding/runtime), which runs an engine-backed method over the bridge (one immediate crossing, answered by the proxy's _kanama_web_builtin_call) or, for the few transcendental ones gameplay calls every tick, in Kotlin (WebLocalBuiltins, ports of Godot's core/math).

A value type is a Kotlin data class of Double components, immutable, with equals/hashCode following GDScript's == (signed zero equal, NaN reflexive, signed zero canonicalized in the hash). Methods split by who computes them:

  • Pure Kotlin, one body, no round trip: every operator and every method whose Godot implementation is plain arithmetic (dot, length, lerp, moveToward, slide, hasPoint, intersects, Transform2D.inverse, the is_equal_approx family, ...), ported with Godot's operand order and computed at the stored width, so the result is Godot's to the bit (the runtime smoke's builtin parity row proves each one against GDScript).
  • Engine-computed, through the builtin-call facade: everything with a transcendental or a long body — angle, rotated, slerp, Basis.getEuler / orthonormalized, Transform3D.lookingAt / interpolateWith, Color.lightened, and their kin. A BuiltinMethod constant resolves the builtin once (variant_get_ptr_builtin_method); a call takes the calling thread's next free BuiltinFrame (fixed native slots, nothing allocated), writes the base and the arguments, calls (which gives the frame back), and reads the return slot. The frames of a thread are a stack because a builtin can re-enter Kotlin while it runs (an engine WARN/ERR reaches a GDScript logger that calls a script); the runtime smoke's builtin re-entry row proves a nested call leaves the outer one intact.

Both kinds are generated (scripts/generate_builtin_ops.py). The facade is internal expect class BuiltinFrame / BuiltinMethod in the common fragment (src/commonMain/.../binding/runtime/BuiltinFrame.expect.kt) with one actual per backend — one unbound FFM downcall called with invokeExact for desktop and Android, the C shim (kanama_ios_godot_builtin_call) for iOS — so the compiler proves the two halves agree. Android compiles a remapped copy of the common and JVM sources as a plain Kotlin library: the copy skips every *.expect.kt file and strips the actual modifier, which is also why an expect declaration carries no default argument (scripts/check_expect_no_defaults.py).

Object Lifetime

Godot is reference-counted on the native side. A Godot object can be freed the moment its refcount drops to zero — which can happen on any thread, at any time, while a JVM-side wrapper still holds a reference to its raw pointer. Touching that pointer after free is undefined behaviour.

Kanama does not tie JVM wrapper lifetime to native lifetime; it keeps the two explicit:

Godot creates a script / extension instance
  → Kanama registers the Kotlin object in ObjectRegistry under a fresh
    monotonic Long handle, which is also the void* token passed to
    object_set_instance (never a JVM address: those move under GC)
  → every engine callback (call, virtual, set/get, notification, free)
    resolves that token back to the Kotlin object

Godot frees the instance
  → the free_instance upcall fires
  → ObjectRegistry.unregister(handle) drops the Kotlin object

Wrappers around engine-owned objects (Node, GodotObject, …) are non-owning views over a raw pointer plus the instance id captured at construction (GodotObject.instanceId, one object_get_instance_id downcall per mint). GD.isInstanceValid asks is_instance_id_valid about the captured id and never touches the pointer (task 98; before that it built an OBJECT Variant from the pointer and read the freed header), and equals/hashCode compare that id (two wrappers of one object are equal, task 131). Every other member reads the pointer through GodotObject.segment, which in debug builds (the editor, debug export templates: OS.is_debug_build()) first asks object_get_instance_from_id whether the captured id still resolves to that pointer and throws IllegalStateException("Invalid access to previously freed instance ...") when it does not — contained and reported as a script error like GDScript's error of the same name (task 131 item 2; FreedObjectChecks, ObjectRuntime.isLive). Holding a stale wrapper stays silent, as in GDScript: every place that encodes a wrapper as a value (Variant boxing, a script property read, a method or virtual return, an Array element; generated glue goes through BuiltinTypes.objectValueSegment) uses FreedObjectChecks.valueSegment, which answers NULL — nil — for a freed object. A release build skips the check, so there a wrapper kept past its object's death is still a dangling pointer for those members — see the script model below.

RefCounted wrappers are the exception — they own the +1 reference their factory or getter transferred and close() releases it. Every RefCounted-derived wrapper, generated or hand-shaped, refuses further use of a handle whose close() destroyed the object: each method opens with checkOpen() and each argument position goes through requireOpenHandle(), so a use-after-close surfaces as IllegalStateException("RefCounted handle is closed") rather than a native fault. The generator emits the guard and check_wrapper_generator.py locks it on both emission modes. The flag is per wrapper: a second wrapper minted over the same handle has its own, and a close() that only dropped one of several references leaves the object alive and the wrapper usable. The ownership rules are in RefCounted Return Ownership.

Garbage-Collector Fallback

An owned RefCounted wrapper that is never closed is released after the garbage collector drops it: the wrapper registers a cleanup that holds only its handle, and the collector's callback only queues the release; Godot's unreference() runs from the frame loop on the main thread, never on the collector's thread. The details the user page summarizes:

  • Only owned wrappers register. A borrowed view (fromHandle, a wrapper constructor, values read through call/get/getMeta) is never released, because its reference was never ours.
  • Any thread. A wrapper made on a worker (a Dispatchers.Default coroutine, a Thread, a threaded load) registers the same way. ObjectCalls.keepReachable keeps the wrapper reachable through its last call, so a release never lands inside a call a worker is still making.
  • Never twice. close() cancels the cleanup.
  • Timing. How soon a dropped wrapper is released depends on when the JVM (or Kotlin/Native) collects; it is not a deadline. Measured on an Apple M1 Max (desktop JVM, 600 frames of about 7 ms): dropping 200 owned getter results a frame, one collection ran and a dropped wrapper waited about 260 frames on average; dropping 5 a frame, no collection ran at all, so nothing was released in those 10 seconds. Releases run within about 1 ms per frame (the rest waits for the next frame); a backlog over 4,096 or a frame over 20 ms raises that to at most 4 ms, with at least 512 releases a frame when the backlog is large or the frame took over 50 ms, so a game at a few frames a second still drains its backlog. Above 100,000 waiting wrappers new ones stop registering and a warning names kanama/debug/log_gc_releases. The image, mesh or audio behind a wrapper lives in Godot's memory, which the collector does not see, so dropping a few large resources does not make it collect sooner.
  • Shutdown. Before Godot's leak report, Kanama runs a collection and releases what it finds, again while a round still releases something (a freed resource can free the resources its properties held), so a dropped wrapper does not show up as Leaked instance at exit.
  • Diagnostics. kanama/debug/log_gc_releases (off by default) logs each release the collector made, once per creation site: released by GC: Mesh (created at Player.kt:42). KANAMA_GC_RELEASES=0 in the game's environment turns the fallback off, for measurements.
  • Platforms. Desktop, Android and iOS run the same mechanism; the desktop runtime smoke checks it on every run, and the Android and iOS device self-tests check it on the phones. Web releases through the browser's collector (see Web).

A script object keeps its owner alive. A KanamaScript on a RefCounted owner holds a +1, and its native link is strong above count 1 and weak at 1 (C#'s CSharpInstance model), so holding the Kotlin object keeps the resource alive and dropping it releases the resource like any other forgotten wrapper. The user-facing rule is in Custom Resources.

The cache-reload edge. The garbage collector can drop the script object while Godot still caches the resource. If the resource is loaded again from the cache before the next frame, its script object is rebuilt on first use and re-reads its values from the resource's file, which is what GDScript's re-parse gives:

  • re-reading the file loads an uncached copy of the resource, so the script class's constructor and init blocks run once more for that copy, besides once for the rebuilt script object;
  • if the file changed on disk since the load, the result is mixed: the engine properties keep their in-memory values, the script properties come from the file;
  • a resource that was never saved, or a sub-resource stored inside another file (res://level.tres::Resource_x), is not re-read: its script object starts from its defaults, with a warning.

ResourceSaver.save does not take ownership. The scene wrapper is still live after save returns, so close() after it is the caller's to make. An early port got this wrong (issue #81); scripts/runtime_smoke.sh asserts the reference count and liveness after save to keep it fixed.

Threads and the Script Loader

Godot calls into Kanama on whichever thread made the call, and Kanama runs it there; Kanama makes no thread-affinity checks. ResourceLoader.load_threaded_request("res://Thing.kt") is the case where the engine itself leaves the main thread: it runs Kanama's .kt loader on a worker. The loader is written for that: its per-thread state is ThreadLocal, its script catalog is synchronized, and its create-and-attach path only assumes that creation and attach happen on the same thread, which Godot guarantees because _instance_create is synchronous.

To see whether a callback arrives off the initialize thread, run with KANAMA_THREAD_DIAGNOSTICS=1. Kanama then logs, once per site, when ScriptBridge.siCall (script method dispatch) or the .kt loader's _load runs on a thread other than the one that ran initialize:

[kanama:thread] KanamaResourceFormatLoader.callLoad ran on thread id=41 name=..., not the initialize thread (...)

It is a diagnostic, not an assertion: nothing is refused, and with the variable unset it costs one boolean read per call.

Autoload Lookup

Autoloads.<Name> (generated by AutoloadSource.kt from project.godot) finds the node at /root/<Name> on the first read and reuses it while it lives; a freed one is looked up again. A worker thread can read an autoload once the main thread has read it; before that the read throws, because only the main thread may query the scene tree. A class Kanama has no wrapper for on the target falls back to its nearest wrapped ancestor. A feature-tag override in project.godot (Music.android="*res://music_mobile.gd") is not an autoload of its own: it is skipped with a build warning, and Autoloads.Music is typed from the base entry. An autoload saved by uid ("*uid://...") is typed from the file that declares the uid (a script's .uid file, a scene's header). Editing the autoload list re-runs the processor: the build declares project.godot as a KSP input. How autoloads behave across a hot reload is in Hot Reload Internals.

Process Exit on Desktop

The desktop JVM is never destroyed: Kanama has no DestroyJavaVM. A normal quit runs Godot's Main::cleanup. That frees the scene tree, and Kanama releases what it owns at the extension deinitialize levels (the OwnedReleases drain, the script language, the registered classes and the owned StringNames). Then main returns and libc exit() runs Godot's static destructors on the main thread while the JVM is still running. An exit that the JVM starts is different. SIGTERM, SIGINT or SIGHUP through the JVM's signal handlers, or System.exit, run the Java shutdown hooks, and then the VM thread ends the process. Godot's cleanup never runs on that path. If libc exit() ran there, Godot's static destructors would call Kanama upcall stubs from the VM thread at its final safepoint, which crashes (SIGBUS in UpcallStub) or hangs. bootstrap.c therefore passes the JNI invocation API's exit hook, which flushes stdio and calls _exit(code); the runtime smoke's SIGTERM leg checks it. Android (ART, started by the app) and iOS (no JVM) do not have this exit path.

Script Class Model

@ScriptClass Kotlin types are separate script objects that hold the Godot-owned object handle. They do not inherit from the attach type. User code gets a typed non-owning view with KanamaScript<CharacterBody3D> and self. Secondary compatible views can be cached with selfAs(::Node3D) or another wrapper constructor.

This is intentional for the current architecture. Godot owns the native node; Kanama owns the JVM script instance. When Godot frees the node, the free_instance upcall (siFree) unregisters the script's registry token — it does not invalidate the self wrapper or any other wrapper over that node, which become stale views: a call through one is the freed-object error in a debug build and a dangling pointer in a release build. Making class Player : CharacterBody3D would blur those two lifetimes and make hot reload harder, because the JVM object would appear to be the native wrapper while still being a reloadable script instance.

The accepted direction is to keep the separate script object model and improve ergonomics around it incrementally. Two tiers are on the table, in ascending complexity; neither is implemented yet — this section records the accepted design, not shipped behaviour:

Tier 1 — KSP-generated per-type base classes (no compiler plugin needed)

KSP already sees @ScriptClass(attachTo = "CharacterBody3D"). It can emit a thin abstract base once per unique attachTo type:

// KSP generates:
abstract class CharacterBody3DScript(godotObject: GodotHandle) :
    KanamaScript<CharacterBody3D>(godotObject, ::CharacterBody3D)

// User writes:
@ScriptClass(attachTo = "CharacterBody3D")
class Player(godotObject: GodotHandle) : CharacterBody3DScript(godotObject) {
    fun physicsProcess(delta: Double) {
        if (self.isOnFloor()) { ... }   // self. still required
    }
}

Eliminates the <T>(godotObject, ::T) redundancy without any runtime cost.

Tier 2 — KSP-generated extension functions (no compiler plugin needed)

For each attach type, KSP generates extension functions on its script base that forward to self:

// KSP generates on CharacterBody3DScript:
fun CharacterBody3DScript.isOnFloor(): Boolean = self.isOnFloor()
fun CharacterBody3DScript.moveAndSlide(): Boolean = self.moveAndSlide()
// ... one per method of CharacterBody3D

Because Kotlin resolves extension functions for this, users can call isOnFloor() directly with no qualifier — the script body reads exactly like class Player : CharacterBody3D() inheritance, with none of the lifetime confusion:

@ScriptClass(attachTo = "CharacterBody3D")
class Player(godotObject: GodotHandle) : CharacterBody3DScript(godotObject) {
    fun physicsProcess(delta: Double) {
        if (isOnFloor()) moveAndSlide()   // no self. needed
    }
}

This makes a Kotlin compiler plugin unnecessary. A plugin (IR/FIR) would give the same call-site DX at the cost of significant toolchain complexity and fragility across Kotlin compiler versions. The KSP extension-function approach achieves the same result purely through code generation, with no compiler changes and no new build dependencies.

Expected runtime cost: zero — the JIT inlines one-liner static forwarders completely within the first few hundred calls; self is a cached field, so no lookup overhead. Expected build cost: longer KSP + kotlinc time and a slightly larger jar (both negligible).

Script-Language No-Op Callbacks

Godot calls script-language virtuals such as _add_global_constant, _add_named_global_constant, and _remove_named_global_constant on every registered script language to broadcast autoload and singleton names. GDScript stores them in its name-resolution table so user scripts can write an autoload as a free identifier.

Kanama scripts are compiled Kotlin, so names are resolved at compile time instead: the KSP processor generates an Autoloads object from project.godot (task 133 C; one typed property per autoload, looked up at /root/<Name> on each read). The callbacks are still implemented so Godot sees a complete script-language surface, but they are intentionally no-ops: the generated object does not need the runtime broadcast.

Rejected Designs

Three things this project deliberately does not do, and why:

Choice we rejected Why we rejected it
Engine module (forking Godot, à la modules/mono) Couples us to a specific Godot build. Pure GDExtension keeps Kanama on the stock Godot release path without an engine fork.
Hand-written JNI glue jextract reads gdextension_interface.h and emits all 300+ binding stubs in one pass. JNI would need ~300 hand-maintained C functions.
Mirrored object graph Some JVM/Godot bindings pair native objects with long-lived JVM mirror objects. Kanama instead keeps a JVM script instance plus lightweight, non-owning wrappers around Godot-owned handles. This keeps object lifetime, hot reload, and editor placeholders simpler in the current Panama/GDExtension architecture.

The cost we accept in exchange: Panama's managed↔unmanaged hop on every call. For per-frame hot paths (_process), the same advice applies as in C# Godot — keep per-frame logic lean, batch when you can.