Skip to content
Design18 min readUpdated 27 Oct 2026

10. RGL: the Reaktor Graph Language

RGL is RG embedded in Kotlin common code. It has four sublanguages that share one syntax and one identity fabric. Definitions elaborate scopes into patches. Behaviour is code entries that perform distributed operations. Queries are traversals. Changes are patches, rewrites, migrations and releases. The language is defined by RG’s abstract syntax and semantics, not by Kotlin (Section 10.8).

10.1 Phases#

Every RGL program passes through phases whose effects and authorities differ:

elaborate → check → plan → compile → admit → activate → observe.

Elaboration runs ordinary Kotlin (loops, functions, generics) over pinned inputs and produces a patch. It has no production effects: files, clocks, randomness and network access are excluded or declared as build inputs, so elaboration is deterministic and its patch has a digest. Check is 𝖶𝖥𝗌𝗍𝖺𝗍𝗂𝖼. Plan chooses placements and bindings and computes closures. Compile produces JVM, native and JavaScript artefacts, and Hermes bytecode for pushable regions. Admit evaluates 𝖶𝖥𝖺𝖼𝗍 and the release predicate on each host. Activate publishes. Observe joins runtime facts back to the graph by identity. A loop in behaviour updates local state; it never publishes a revision. A revision is published only by a committed patch.

10.2 Definitions#

Listing 7 declares the chat feature of Figure 1, with one difference: the message store belongs to the scope, so the actor writes it directly rather than through the messaging service. The scope has a boundary session client, a signal channel (fan-out, latest value), a mailbox channel (competing consumers, one consumer), a store, an exclusive component, two routes and two surfaces. Every call creates typed elements; every declared name becomes a stable identifier within its scope; every port is typed by family, role and contract. The scope is self-contained: its only external need is a boundary Session client for MessagingApi.

val Chat = scope("chat", owner = Source, updateUnit = true) {
    val api      = require(Session.call<MessagingApi>())
    val timeline = channel<RoomEvent>("timeline", Signal)
    val inbox    = channel<ChatCommand>("inbox", Mailbox)
    val db       = store("chat-db", Transactional) {
        dataset<Message>("messages") { key(Message::id); references(Message::roomId, "rooms") }
    }
    component("actor", ::ChatActor, profile = Exclusive) {
        consumes(inbox); produces(timeline); calls(api); writes(db["messages"])
    }
    val list   = route("/chats")
    val detail = route("/chats/{id}", ChatArgs.serializer())
    surface("list", ::ChatListScreen, at = list)   { observes(timeline); navigates(list to detail, Push) }
    surface("chat", ::ChatScreen,     at = detail) { observes(timeline); produces(inbox) }
    export(detail)
}

Listing 7.

A self-contained feature scope (proposed API).

10.3 Behaviour#

Behaviour is ordinary Kotlin in code entries: named, registered functions with a receiver that offers the distributed operations of Table 10. The unit transferred to another place is a code reference with input values and delegated capabilities. It is never a closure: a closure may capture a mutable object, a coroutine or an authority that cannot move. Listing 8 shows an effect committed together with its outbox record in one transaction at one authority; the record is published only after the commit. It also shows a fan-out to shard owners with an explicit join policy, followed by a call to a ranker that a Python provider implements.

@Entry("chat.send")
suspend fun RglScope.send(cmd: SendMessage): Outcome<MessageId, SendError> =
    atomic(chatDb, idempotency = cmd.effectId) {
        val id = insert(Message(cmd.room, cmd.text))
        outbox(MessageSent(id, cmd.room))
        id
    }

@Entry("search.rank")
suspend fun RglScope.rank(q: Query): Ranked = distributedScope(failure = CollectAll) {
    val parts = q.shards.map { s -> spawn(SearchShard, ShardQuery(q.text, s), at = ownerOf(s)) }
    call(ranker) { rank(parts.awaitOutcomes().successes(onUnknown = Exclude).flatten()) }
}

Listing 8.

Code entries with distributed operations (proposed API).

Table 10. Distributed operations available to code entries.
Operation Family Required meaning
call(port) {…} Session Returns an Outcome that separates a domain rejection, a failure and an unknown effect; carries a deadline and an idempotency key
emit, receive Channel Admission at the channel’s stated point; acknowledgement and replay per the channel’s attributes
fire(transition) Transition Enabled only if the guard and the join policy hold; durable transitions persist before acknowledging
spawn, await runtime containment A child activation under the current scope; the join policy is explicit; a timeout is not evidence of termination
atomic(store) Access A transaction at one named authority; the body may use only that authority’s operations and its outbox
submit(work) Session (durable) Returns a handle only after the durable authority has accepted the request
observe(ref) Observes Facts with provenance, coverage and freshness

10.4 Queries and changes#

Traversals are declared with their selector and their algebra, so the kernel can check monotonicity and compile them incrementally (Section 8.2). Rewrites are traversals that return patches. Listing 9 computes reachable routes and installs a tracing interceptor on every call in a scope. Its second half is how auth, telemetry, rate limiting and similar concerns are “bolted on” (R5). Each is a typed, reviewable patch, so its effect is visible in the graph diff.

val reachable = traversal<Boolean>("routes.reachable") {
    select(Transition, from = Pre, to = Post); start { it == root }
    lattice(BooleanOr)
}
val traceCalls = rewrite("telemetry.trace-calls") {
    forEach<Session>(where = { it.protocol == Call && tracer !in it.interceptors }) { call ->
        addIncidence(call, role = Interceptor, port = tracer.port, ordinal = 0)
    }
}

Listing 9.

A query and a rewrite (proposed API).

10.5 Graph types as Kotlin types#

RGL encodes as much of a port type as Kotlin’s type system can carry. Many errors are then ordinary type errors, reported by the Kotlin compiler before any RG rule runs; the plugin checks the rest.

  • Ports. A port handle is typed by family, role and contract, as in Port<Session, Client, MessagingApi>. A connection operation accepts only ports of its own family and roles that the family allows, so connecting a Session client to a Channel, or giving a call session two servers, does not compile (rule Inc of Figure 9, and W3).

  • Contracts. A contract is a Kotlin type, usually a sealed interface of serializable classes. Its fingerprint is the digest of the canonical form of its serial descriptor [184]. The canonical form includes every serial name that reaches the wire, so renaming a class changes the fingerprint unless @SerialName pins the old name, and any change of schema changes it.

  • Outcomes. A Session call returns a sealed Outcome with four cases: success, domain rejection, failure and UNKNOWN. A when over it without an else branch must be exhaustive, so code that forgets UNKNOWN does not compile, and the plugin flags else branches and helpers that discard it silently.

  • Effect ceilings. The receiver of a code entry is indexed by its ceiling, RglScope<E>; Listing 8 omits the parameter. An operation whose effect exceeds E is not a member of that receiver, so W10 is a type error at the call site.

  • Ownership. A 𝖻𝗈𝗋𝗋𝗈𝗐 port hands its body a scoped value, as the parameter of a lambda that the plugin’s escape analysis forbids to escape (W9). Kotlin has no linear types [349], so the plugin checks that a 𝗆𝗈𝗏𝖾 value is consumed exactly once only on statically known paths, and reports the rest.

  • Labels. Data from a labelled source arrives wrapped, as Labeled<T, L>. Only a declassifier held by an authorised principal unwraps it, and the plugin tracks labels through bodies on statically known paths (W11), in the spirit of decentralized labels [259].

What Kotlin cannot express (hyperedges with several parties, placement, layers and the global rules) is checked on the elaborated graph. Each finding is reported at the source span that created the element, so it appears in the IDE next to the code that caused it.

10.6 Compilation and the Hermes host#

The Kotlin compiler keeps its job. Symbol processing (KSP) extracts declarations, registries and FlexBuffers codecs. A compiler plugin performs the body-level checks that symbol processing cannot: capture analysis for code entries, effect summaries, and lifting entries out of closures. The Kotlin/JS IR backend emits an ES2015 module, and hermesc compiles it to bytecode for a pinned engine version [180, 241]. On a device, the native host runs its own RG runtime. A pushed region runs in a Hermes engine with a second runtime instance, connected to the host through a JSI trunk whose typed host imports are exactly the region’s capability ports [289]. The engine is a runtime place nested in the app’s process. Its boundary ports are Exported through the trunk, and Corollary 4 is what makes mounting it there sound. Section 13.4 describes the reference implementation of these steps.

This requires a kernel without platform dependencies. RG removes each obstacle found in the current runtime:

  • identifiers are minted through a capability rather than crypto;

  • time comes from a clock capability, and scheduling from a dispatcher capability that maps to the Hermes microtask queue;

  • the kernel depends on no injection framework, HTTP client or database;

  • ports match by contract fingerprint rather than by KClass, so separately compiled bundles connect.

The host profile pins the compiler, the engine version, the module format, numeric semantics, the coroutine dispatcher, interrupt and budget mechanisms, and teardown. It is qualified by tests on each target. Cash App’s Zipline and Redwood run Kotlin/JS in an embedded QuickJS behind typed service interfaces and drive Compose-based UI from it [52, 53]. They are the closest industrial precedent. RGL generalises the unit from an interface to a typed subgraph, with a closure computation, an admission predicate and fenced activation.

10.7 Compiling with the whole graph#

A compiler that sees one module must be conservative at every interface. It cannot know which implementation an interface call reaches, which fields a remote reader uses, whether a buffer escapes, which code is dead, or how often a path runs. Each of these is a fact about the system, and the graph records it. RGL therefore connects the Kotlin compiler and the graph in both directions (Figure 17):

  • Source to graph. A build step runs the compiled definitions, which elaborates them into a patch: elements, ports, contracts, effect summaries and Access footprints. The K2 frontend [182] analyses bodies but does not execute them, so its checkers report the rules that a single module can decide, and the rest run on the elaborated graph.

  • Graph to compiler. After planning, a compilation plan records the facts that the plan has fixed: resolved bindings, placements, the consumers of every port, release boundaries and profiles. The plugin’s backend extension specialises code to it.

The compilation plan is a FlexBuffers file pinned by digest, and it is an input of the build like any source file. Builds therefore stay deterministic, and an artefact’s digest identifies both its code and the facts it was specialised to. The separation is Halide’s: the definition is the algorithm and the plan is the schedule [285], so one definition compiles differently for a phone, an edge isolate and a cluster. Graph-owned scopes, edited in the workbench rather than as text, take the same path: Kotlin is generated from the graph and compiled with the rest. Unlike Blueprints, which run on a virtual machine (Section 4), they then share the compiler, the optimisations and the debugger of handwritten code.

Figure 17

Figure 17. The Kotlin compiler and the graph in one loop. A build step runs the definitions, which elaborates them into a patch, and the frontend checks what one module can decide. The planner fixes bindings, placement and the release closure, and hands the compiler a compilation plan pinned by digest. The backend specialises code to it, admission checks the artefacts, and observations return as profiles for the next plan. Among the elements of a region admitted together on one host, the compiler may assume a closed world; across hosts, generations and regions, only contracts.

Optimisation domains#

A fact may be used only where it cannot change behind the compiler’s back. A release region is not such a place on its own: admission is decided per host (Section 9.5), next-entry activation runs two generations side by side, and versions coexist during a rollout (P13 in Section 16). The domain of an optimisation is therefore the set of elements of one release region that are admitted together on one host, at one generation. Admission checks their digest and the fingerprints at their boundary before activation, so every structural fact among them holds for as long as the code runs: which provider a Bind resolves to, which of its consumers share the host, which place each component occupies. Inside that set the compiler may assume a closed world, as whole-program compilers do [88, 352]. Any connection that crosses hosts, generations or an installed app binary keeps only its contract, because the other side can change independently, even when it belongs to the same region. Region boundaries are barriers in the same way. Optimising across one requires fusing the two regions, and the closure of Equation 3 then releases them together. A small region can be pushed quickly but admits fewer optimisations; a large one is optimised more but is released as a unit. The planner reports this trade for each candidate region.

The optimisations#

Table 11 lists thirteen, each with the graph fact it needs. Four illustrate the pattern.

  • Static injection. The injection traversal resolves every Bind at plan time. The compiler emits constructor calls in dependency order, as Dagger does within one program [150], but across the whole region and with the graph’s scope chain. Nothing is looked up at run time, and a missing provider is a compile error with a witness.

  • Specialised sessions. A Session is realized according to its placement. If the plan puts both ends in one process and one generation, and the request is deeply immutable or moved, the stub passes the request object without encoding it, so no alias can arise. It keeps the deadline and the Outcome, and an exclusive server still receives the request through its mailbox, because the family’s semantics does not depend on the realization. Service Weaver makes the same choice between local calls and remote procedure calls at deployment time [143]. If the ends are in different places, the stub uses the codec generated for exactly that contract fingerprint.

  • Fusion. Consider a chain of pure or stream components in one place and one supervision scope, linked by Channels that each have one producer, one consumer, no durable buffer, no observer, lossless back-pressure and no time windows or watermarks. Removing such a buffer changes neither what is delivered nor when a failure is contained. The compiler fuses the chain into one loop, as stream fusion removes intermediate lists [77] and FlumeJava fuses parallel stages [55]. Attaching an observer to an intermediate channel is a patch. The patch makes the fused artefact stale, and the region is rebuilt unfused.

  • Codec pruning. The plugin records, for each body, which fields of each contract it reads; forwarding a value, logging it or comparing it counts as reading every field. When the producer and every consumer of a transient channel run on one host at one generation, these summaries show which optional fields no reader uses, and the encoder skips them. A durable or replayed channel keeps every field, because a consumer added later may read them, and so does any channel with a reader on another host.

Table 11. Optimisations for which the graph supplies the facts. Each is sound among the elements of a region admitted together on one host and generation, under the side conditions stated in the text; a connection that crosses hosts, generations or app binaries keeps only its contract.
Optimisation Graph fact it relies on Effect Precedent
Static injection Bind resolution by the injection traversal (Table 8) constructor calls in dependency order; no container at run time; a missing provider is a compile error Dagger [150]
Devirtualisation, inlining a local Bind whose provider is unique in the region direct calls that the backend can inline class hierarchy analysis [88]
Dead-code elimination ports without incidences; components unreachable from entries, routes and schedules smaller bundles per Worker, app and engine; host capability ports that pushable regions may need are kept R8 [152]
Session specialisation the realization and placement of each Session in-process stubs without codecs; one stub per kind of binding Service Weaver [143]
Codec specialisation contract fingerprints; per-body summaries of the fields each reader uses generated FlexBuffers readers and writers; unread optional fields pruned among readers on one host kotlinx.serialization [184]
Fusion one-producer, one-consumer Channels between pure or stream components of one place and supervision scope, with no durable buffer, observer or time window, and lossless back-pressure one loop, without intermediate buffers or tasks stream fusion [77], FlumeJava [55]
Ownership 𝗆𝗈𝗏𝖾, 𝖻𝗈𝗋𝗋𝗈𝗐 and 𝗌𝗁𝖺𝗋𝖾 on ports no copies of borrowed buffers; moved values reused in place; W9 checked in bodies escape analysis, linear types [61, 349]
Batching Session attributes (batchable, idempotent read) and the call sites in one place many calls to one place become one round trip Haxl [235]
Partitioning by place Places one bundle per place; communication only across cut edges TensorFlow [3]
Profile-guided optimisation Observations joined by identity: call counts, latencies, payload sizes inlining, code splitting, codec fast paths, co-location hints Pettis and Hansen [283]
Incremental compilation the impact traversal over a graph diff only artefacts whose inputs or assumptions changed are rebuilt ThinLTO [186], Bazel [331]
Closed-world initialisation the elements admitted together on one host: entries, registries, codecs, injection plan construction code generated at compile time; no scanning or reflection at start-up Native Image [352]
Runtime specialisation the whole compilation plan the generic runtime specialised to one region partial evaluation [188], Truffle [355]

Specialising the runtime#

A generic RG runtime interprets the graph: it looks up providers, dispatches calls through ports and encodes payloads by contract. Specialising an interpreter to a fixed program yields a compiled program. This is the first Futamura projection [188], and Truffle and Graal use it to compile guest-language programs by partially evaluating their interpreters [355]. A compilation plan is that specialisation, applied to the elements of a region on one host. Generated construction code completes it. The injection graph, registries and codecs are built by code generated at compile time, the counterpart, for Workers, ART and Hermes, of the heap image that GraalVM Native Image builds for a closed world [352]. A Worker, an Android process or a Hermes engine then starts without scanning, reflection or wiring.

Profiles from observations#

Observations are joined to elements by identity (Section 5.4). Call counts, latencies and payload sizes per port are therefore graph data with provenance and freshness. Profile-guided optimisation [283] then works at the scale of the system:

  • hot local calls are inlined;

  • cold code is split into chunks that the web and Hermes hosts load lazily;

  • codecs get fast paths for the commonest shapes;

  • the placement solver learns which sessions are chatty enough to co-locate.

A profile is evidence, so it goes stale like a claim. Inlining and layout chosen from a stale profile change performance, not meaning. Code splitting and co-location are different: a lazily loaded chunk must be available when its host is offline, and co-location changes failure domains, so both are changes to the plan that admission checks, not choices the compiler makes alone.

Incremental compilation from graph diffs#

The impact traversal (Table 8) computes which artefacts a patch affects:

  • a body change that leaves the contract fingerprint unchanged rebuilds its module and every artefact that inlined that body or pruned a codec on its behalf;

  • a contract change rebuilds the module and its dependents;

  • a placement change rebuilds stubs and bundles, not bodies.

This is the summary-based scheme of ThinLTO [186] and the action graph of build systems [251, 331], with the system graph as the summary index. Each optimisation also records its assumptions as dependencies on elements. A patch therefore invalidates at least the artefacts whose assumptions it breaks. This is the mechanism that marks claims stale (Section 15). It is also the static counterpart of dynamic deoptimisation, which replaces optimised code when code that it inlined is edited [172]. Listing 10 shows a compilation plan as a reviewer sees it.

compilation plan  region chat  release chat@17  place edge  revision r-9f2c
  bind      actor.clock  -> isolate clock        resolved; call inlined
  session   actor.api    -> MessagingApi#7f3a    region boundary: stub and codec, no inlining
  channel   inbox        -> actor                mailbox keyed by room; codec ChatCommand#5d10
  codec     RoomEvent#91c2                       writer generated; nothing pruned: readers on phones
  init      registries, codecs, injection plan   built at compile time
  assumes   14 elements; a patch to any of them makes this plan stale

Listing 10.

A compilation plan for the chat region on the edge place (proposed format, rendered as text).

What authors declare#

The compiler can use only facts that the graph states. Purity is a component profile; batching and idempotence are attributes of a Session; and optional fields are part of a contract. These already exist for checking, and the compiler reuses them. One attribute is new: a region is either sealed, or open to mounts at run time. An open region keeps more boundaries and receives fewer optimisations.

Soundness and cost#

Optimisation must not change meaning. The generic runtime, which interprets the graph, is the reference semantics, and a compiled region must refine it in a sense that also preserves progress: every behaviour of the compiled region, including what it refuses and whether it diverges, must be one that the interpreted region allows. Trace refinement alone (Corollary 5) would accept a compiled region that deadlocks. The conformance suite runs its test vectors on both and so tests their equivalence on those vectors; it does not prove it. Admission accepts an optimised artefact only with that evidence. Optimised code must also stay explainable. Every transformation is recorded in the compilation plan with the elements it touched, and source spans survive it (Section 13.4). A frame in fused or inlined code therefore still maps to the elements and lines it came from. Whole-region optimisation costs build time, so it is enabled per release profile; debug builds keep the interpreted path. Kotlin’s compiler plugin interface is not stable and changes with compiler releases [181], so the plugin is pinned in the host profile and requalified with each compiler upgrade.

10.8 Portability#

RGL Core consists of the abstract syntax (Σstd as data, the patch operations and the traversal intermediate form), the semantics of Section 7, and the wire protocol. The wire protocol, rgp/1, carries graph messages in the frames of Reaktor’s FFI layer, encoded with FlexBuffers [148, 289]; Section 12 defines it. A conformance suite of graph test vectors covers judgments, patch results, traversal results and specification traces. A host language can implement RGL if it offers six things:

  1. sum and product types, or a schema system, for contracts and codecs;

  2. first-class functions or a table of named entries;

  3. asynchronous concurrency with cancellation;

  4. a deterministic binary codec;

  5. for pushable regions, an embeddable interpreter or a portable bytecode;

  6. a C ABI or an equivalent FFI.

Swift, TypeScript, Rust, C++ and Python could implement RG from the same abstract syntax. Reaktor implements it once, in Kotlin, and uses Swift, C and TypeScript only as glue (Section 13.5). A system written in another language joins as a Component on its own Place, such as a Python model host behind a Session. Its internals stay opaque, and its boundary is typed like any other.