Unified FFI and RPC
This is the design for one graph-owned FFI/RPC layer across Kotlin, C++ and TypeScript. The mobile InteropRuntime already supports synchronous JSON calls and callbacks through C++ and Hermes. The shared session engine, Service-to-FFI binding, versioned async ABI, cross-runtime streams and replacement model below are proposed work. Reaktor V2 supplies the direction; its full runtime model is still evolving.
Overview#
Use the existing Service contract model as the authoring foundation. Generate portable contract manifests and language bindings from it. Introduce one small shared session/protocol implementation, proposed as reaktor-rpc, consumed by reaktor-service and reaktor-ffi. The graph admits and owns endpoint bindings, their authority, activations and lifetime. Admission compiles those bindings to direct call sites, codec plans, dispatchers and interceptor chains; calls do not query the graph.
Unify contract identity, typed outcomes, context, cancellation, bounded flow control, compatibility and conformance. Preserve the semantic difference between a synchronous local Bind and a failure-bearing distributed Session. Preserve the existing JSON APIs through adapters while replacing their separate protocol machinery incrementally. Ordinary function endpoints remain direct; actor scheduling is an explicit execution profile. RGP retains graph control responsibilities.
The first delivery proves one useful graph-to-foreign-service call and the same contract over an existing network adapter, with the application-to-service-to-Hangar observation path working. Binary FlexBuffer, stream expansion and reload qualification follow explicit gates. There is no requirement to finish the V2 graph kernel before delivering this path.
Try the existing bridge#
The current API is a useful starting point for an existing mobile interop build. This example comes from the FFI module README; it registers a Kotlin export and calls the bundled TypeScript diagnostics module:
InteropRuntime.mobile().use { runtime ->
runtime.kotlin.module("app") {
function<String, String>("echo") { it }
}
val hello = runtime.typescript.module("reaktor.diagnostics")
.function<Unit, String>("hello")
println(hello(Unit))
}
runtime.native has the same typed import API. The runtime belongs to its creating thread, including nested callbacks. Close it after calls return. This example uses the implemented synchronous JSON bridge; the proposed RpcLink and async session APIs are not available yet. The mobile factory does not currently provide a working JVM FFM or JS Wasm bridge. Build setup and qualification records live in the module README and Dependeasy.
The first proposed Service integration uses the existing bestbuds.config/getConfig contract. Its P1 fixture exercises a graph consumer, a foreign provider and the same contract over HTTP.
What exists in source#
| Area | Source-grounded finding | Design consequence |
|---|---|---|
| Mobile FFI | InteropRuntime owns a kernel and Kotlin exports. Kotlin, C++ and TypeScript call synchronously through JSON. C++ owns a lazy Hermes runtime and enforces creator-thread access. Nested callbacks are supported by the current path; closing during an active call is forbidden. | Preserve this working path and its ownership rules during migration. |
| Mobile ownership | Android uses JNI owner/global references; Apple uses a callback StableRef and releases owned result objects. Runtime.h exposes opaque runtime/results with C-string accessors and release functions. | Introduce length-bearing buffers, version negotiation and async shutdown deliberately; do not treat the existing handle as a safe wire identifier. |
| Foreign registries | Native dispatch checks C++ exports before host fallback; TypeScript has its own module/operation registry. | Resolve one admitted, unambiguous endpoint at activation; do not retain implicit shadowing as unified discovery policy. |
| TypeScript flows | The current collector/queue is a local single-observer queue. Its StateFlow name does not supply a cross-runtime latest-value, credit or cancellation protocol. | Specify signal, event stream and durable channel semantics separately. |
| Services | Service, Operation, Link, Served, Outcome, context and interceptors already cover suspend calls, server streams, routing, effects and idempotency metadata. | Reuse authoring and interception. Add client/bidirectional stream descriptors without replacing the service model. |
| Service sockets | SocketLink/SocketSession already multiplex calls, open/item/end/cancel and channel operations. An inbox is Channel.UNLIMITED; there is no application credit frame. | A transport wrapper alone cannot establish bounded streaming. Replace exchange machinery behind the existing facade. |
| Compatibility | Shape.kt produces a service shape and FNV64 fingerprint; its schema representation collapses integer widths, and the fingerprint retains HTTP route information while excluding some interaction policy. Compatibility.kt compares its own structural model. | Keep it for current service compatibility; do not promote that fingerprint to a cross-language layout, security or artifact digest. |
| Graph integration | ContractNode already provides service operations through graph ports and stamps identity; ChannelNode exposes broker channels. GraphDefinition/PortDefinition represent identities and connections but not the complete V2 ownership/QoS model. | Extend these integration points. Do not invent a parallel FFI-only graph or claim the full V2 validator exists. |
| WebView bridge | WebBridge has bounded queues, session/epoch checks, operation/schema validation, grants, revocation and host provenance integration. | Reuse its controls when changing framing. A generic session codec must not remove the host's origin/frame/navigation boundary. |
| FlexBuffer/codegen | @Struct/FlexCoderProcessor generate codecs. The inspected positional decoder chooses offsets from generated property layout; it does not first prove an incoming exact-layout fingerprint. FlexBufferValidator validates structural bounds, not contract compatibility. | Gate binary use on wire validation plus schema/layout validation. Neither replaces the other. |
| Native specialists | rsec.h already uses explicit statuses and owned pointer/length buffers for native security operations. | Retain specialist native ABIs and expose selected operations through graph-bound adapters; do not redesign cryptographic state as generic transport infrastructure. |
| Build integration | InteropBuild already composes C++, TypeScript and host tests through Dependeasy. | Extend existing generation/build declarations; no second build orchestrator or package pipeline. |
Primary implementation anchors: FFI ownership and status, Kotlin runtime, C++ kernel, native ABI, TypeScript collector, service operations, service links, socket exchanges, service shape, compatibility, graph contract binding, WebView bridge, generated decoding, binary validator, native security ABI, build integration.
The source map establishes these boundaries, not a fresh device or performance result. The module's existing qualification records cover the synchronous bridge; physical iOS behavior, async sessions and unified stream semantics need their own evidence.
Goals and requirements#
The layer must support Kotlin/JVM, Kotlin/Native, C++ and embedded TypeScript first, while leaving Kotlin/JS a qualified future host. Required interaction shapes are unary and server stream initially, then client stream and bidirectional stream. It must support reverse calls and callback lifetimes without leaking local handles into remote addresses.
Every production binding must identify its definition, contract, activation, place, principal/grant context, execution profile and resource budgets. Every accepted exchange must have bounded retained memory, typed completion, cancellation propagation and shutdown behavior. Generated readers must reject malformed bytes and incompatible layouts before unsafe access. The same contract and conformance suite must run over FFI and at least one existing network transport.
Scope boundary#
This proposal does not require a universal distributed router, a new actor scheduler, a C++ graph runtime, a general distributed transaction system, a broker rewrite, a new UI framework, immediate gRPC adoption, or simultaneous support for Python/Dart/React Native/Wasm/FFM. Existing HTTP, socket and specialist ABIs remain useful adapters. RGP remains graph control, and telemetry remains an observation path rather than the authority for business effects.
Implementation acceptance: the delivery gates, beginning with a graph-owned application call, service execution and Hangar observation before generalized recovery or performance work.
Design decisions#
| ID | Decision | Reason |
|---|---|---|
| D1 | Service is the canonical service declaration; extend it rather than adding @FfiService. | Calls, streams, effects, outcomes and graph adapters already exist. |
| D2 | One lightweight reaktor-rpc module owns neutral descriptors and exchange machinery. | FFI must not acquire reaktor-service -> reaktor-io and its network dependencies merely to run Hermes. |
| D3 | Graph admission is mandatory in production composition; the protocol implementation is an ordinary helper beneath it. | Matches the repository's graph-first direction and V2's definition/activation split. |
| D4 | Keep bind.sync, bind.async and session as explicit interaction profiles. | Blocking, reentrancy and partial failure cannot be erased by a common function name. |
| D5 | Default cross-language payload ownership is copied value. | A correct portable baseline precedes optional borrowed or shared buffers. |
| D6 | Use a versioned, length-delimited C ABI and a bounded duplex session protocol. | Existing C-string and sync JSON bridges cannot express async ownership or flow control. |
| D7 | Define strong semantic/schema/layout fingerprints before binary compatibility is enabled. | Current service fingerprints and generated positional decoders do not establish a portable ABI. |
| D8 | Share protocol machinery with RGP; retain separate domain profiles and authority. | Graph control and ordinary application RPC have different admission and exposure rules. |
| D9 | Outcome uncertainty survives timeout, cancellation and reconnect. | Delivery acceptance is not a durable business commit. |
| D10 | Treat Kotlin/JS in Hermes and code-push replacement as later qualified host profiles. | Current TypeScript/Hermes interop does not prove those capabilities. |
All proposed names, frame layouts and C signatures below are design sketches. Their semantics are the intended decision; version 1 bytes and generated public APIs are frozen only after the conformance gates in the delivery plan.
What it improves#
| Usual approach | What goes wrong | Reaktor approach |
|---|---|---|
| Separate JSON bridges and network protocols | Cancellation, compatibility and outcomes drift between adapters. | One contract model and shared exchange semantics, with adapter-specific ownership. |
| A runtime registry doubles as discovery and routing | Export names can shadow one another, and lookup lacks graph authority and lifecycle. | Graph admission selects one endpoint and installs an immutable binding plan. |
| A common call API hides sync and remote behavior | A blocking call can wait on its own runtime; remote loss hides effect uncertainty. | Explicit bind.sync, bind.async and session profiles with distinct guarantees. |
| Generated positional decoding without an exact layout check | Valid binary bytes can be interpreted against the wrong fields. | Directional schema compatibility plus exact layout fingerprints before positional access. |
| A socket queue stands in for stream flow control | Slow consumers retain unbounded items or silently lose events. | Item and byte credit, bounded queues and an explicit signal/event/channel distinction. |
| Host pointers or callbacks outlive their runtime | Late completion can target freed state or a replacement implementation. | Generational local handles, activation ownership and a close barrier. |
| Transport acceptance is treated as successful execution | Timeout or retry can conceal an already applied effect. | Typed outcomes retain uncertainty; durable certainty belongs to the actual commit owner. |
The earlier Switchboard proposal's Cell/Switch/Trunk vocabulary is replaced by graph contracts, ports and admitted bindings. The graph is foundational. FFI does not introduce another semantic graph, universal actor scheduler or separate service IDL.
Mapping to Reaktor V2#
The relevant V2 commitments are typed interactions and identity, ownership and resources, runtime realization, RGP, code push and implementation boundaries.
| V2 element | FFI/RPC realization |
|---|---|
Contract | Stable service/operation identities; canonical value schemas; interaction, ownership, effect and QoS descriptors. |
Component, ports and Export | Kotlin, C++ or JS implementation with an explicit set of graph-visible ports. Foreign registry entries alone do not export authority. |
Place, Places, Realizes | A process/runtime placement and its qualified adapter, compiler/runtime versions and host profile. Embedded Hermes is a runtime place inside a process. |
Bind | Co-process endpoint binding. A synchronous borrow may cross runtimes only within a qualified nested call extent. |
Session | Explicit asynchronous/failure-bearing interaction, normally across process/network boundaries. It may also realize an explicitly declared asynchronous local session. |
Channel | Broker delivery semantics such as fan-out, competing consumers, acknowledgment and redelivery. Stream DATA frames alone do not implement these guarantees. |
Transition | Activation/admission, quiescence, replacement and drain state changes. Reload is not an ordinary call frame. |
Activation | A concrete admitted instance with definition revision, place, activation key and epoch; owns endpoints, callback scopes and queues. |
Resource versus Grant | Runtime/queue/buffer availability is separate from authority to discover or invoke a port. Neither implies the other. |
Observation/Claim | Correlated spans and qualification evidence with method, freshness, coverage and limits; telemetry is not proof of a durable commit. |
V2's fourteen base kinds and relation model do not need FFI-specific additions such as Cell or Switch. A connection profile supplies realization details. The current graph implementation can carry an explicitly typed admitted-binding record while V2 IR evolves; this is a migration representation, not a claim that arbitrary attributes satisfy V2 well-formedness.
Definition revision, activation epoch and local handle generation are separate. Replacing code creates a new activation generation and potentially a new contract/layout. A callback retained by an old activation must not silently resolve against a newer implementation with the same service name.
High-level architecture#
Authoring, admission and execution#
The overview diagram separates authoring, admission and execution. Dashed arrows install a binding plan or report observations. There is no per-call round trip to the graph control plane. The direct in-process endpoint may skip framing entirely after the same admission checks.
The shared engine runs on Kotlin hosts and later Kotlin/JS hosts. Native-only C++ or TypeScript endpoints need a small compatible peer implementation for local call state, framing and credits. They do not acquire the graph's planner, query engine, scheduler or authorization database. Cross-language conformance transcripts constrain those peer implementations.
Physical module ownership#
Arrows in this diagram mean depends on. Proposed reaktor-rpc is a protocol/contract unit used by the graph, not an independently marketed graph-agnostic framework. It may depend on established core primitives, coroutines, serialization and FlexBuffer; it must not depend on reaktor-io, graph runtime, Compose, JNI or Hermes. Put the initial descriptor and codec work in this one module; do not create one new module for each language or abstraction.
Portable C++/TypeScript frame definitions and minimal session peers belong to that same protocol unit and use existing Dependeasy interop targets. Host glue importing JNI, JSI or Hermes belongs in FFI. Contract-specific generated types/stubs belong to the declaring module's generated outputs, rather than one global handwritten FFI registry. This lets a WebView or future native network adapter use the protocol peer without acquiring an embedded JS runtime.
reaktor-service currently depends on reaktor-io; its existing Operation/Shape/Outcome declarations cannot all be imported into FFI without that dependency closure. Extract neutral representations and machinery, preserving service-facing types through adapters or compatible exports as appropriate. Keep HTTP route annotations and network implementations in service. Avoid moving the whole DSL or inventing a second DSL to resolve this packaging issue.
reaktor-graph-runtime consumes a neutral endpoint/binding SPI. Host composition supplies FFI endpoint providers and retains their runtime owner. Graph runtime must not import a concrete JNI/Hermes implementation. reaktor-graph is not the home for protocol code because it includes UI dependencies. Compiler/codegen extends reaktor-compiler; native/TypeScript packaging extends the existing Dependeasy interop declarations.
The admitted binding plan#
An immutable plan contains:
- Consumer/provider definition and port IDs, their definition revisions, source provenance and expected activation epochs.
- Selected endpoint reference, adapter, local handle generation, owner dispatcher and sync/reentrancy profile.
- Directional schema compatibility result, exact layout eligibility, generated codec references and negotiated protocol features.
- Verified authority context, grant/revocation source, disclosure policy and allowed reverse ports.
- Queue/call/stream/buffer limits, deadline policy, interceptor array, tracing policy and close/drain ownership.
Admission validates this record and allocates bounded resources before publication. A successful call uses immutable plan fields and local state. Revocation, lease expiry or replacement can invalidate an endpoint through a small local epoch/authority gate; that is different from traversing or remotely querying the graph on every call. New admission may fail while existing healthy admitted endpoints continue during control-plane unavailability, subject to their declared lease policy.
Contracts, identities and generation#
One declaration model#
Preserve Service and its current calls/streams. Extend operation descriptors with explicit stable operation IDs, all required interaction shapes, value schemas, ownership, execution profile and relevant policy. Keep today's Call suspend semantics. Do not turn it into a blocking C++ method by calling runBlocking.
Add a narrowly scoped synchronous local profile only for implementations and policy hooks that can complete synchronously. Its generated API is visibly different (invokeSync in this sketch), requires a bind.sync plan and cannot target a network endpoint. Suspend interceptors are not silently executed in this path; supply equivalent non-suspending checks or reject admission. bind.async and session use the asynchronous engine and current suspend/Flow facade.
Generation produces one versioned portable manifest, Kotlin codecs/adapters, C++ typed codecs/stubs, TypeScript types/runtime validators/stubs, and contract conformance fixtures. Do not infer authority from a TypeScript cast or C++ template. Register generated manifests with implementation exports and compare them at admission.
KSP can generate declarations and serializers. It cannot by itself prove arbitrary capture safety, borrow escape, purity or host compatibility. V2's stronger capture/effect checks require compiler/K2 support or explicit, limited qualification evidence. Manual/native exports state what was checked and remain within a qualified host profile.
The consumer keeps its existing consumes(ConfigService().getConfig) port. Host composition chooses the admitted realization; conceptually:
// Proposed integration sketch; these adapter names are not implemented today.
val endpoint = admittedBindings.endpoint(configProviderPort)
remote(ConfigService() over RpcLink(endpoint))
The endpoint may realize FFI or a network session without changing the value contract. The binding plan still declares which failure, ownership and scheduling profile the consumer accepts. Current HttpLink consumers remain supported while migrating.
Identity domains#
| Identity | Definition and use |
|---|---|
| Definition ID | Stable namespaced service, operation, component and port identity. Independent of process, placement, source filename and object address. Existing authored service IDs are the migration seed. |
| Contract fingerprint | Strong digest of canonical contract semantics, including value schemas and interaction requirements. It is not authority. |
| Layout fingerprint | Digest of exact codec/layout version, positional order and representation details. Required before positional reads. |
| Artifact/config digest | Identity of built bytes and deployment/configuration inputs. Separate from contract compatibility. |
| Definition revision | Immutable revision of graph semantic definitions. |
| Activation identity | Definition + place + activation key + epoch. Changes when a new execution generation is admitted. |
| Session identity | Fresh negotiated link epoch plus authenticated peer association. No resumable execution is implied by reconnect. |
| Call key | Link epoch + opener role + monotonic unsigned counter. Unique for both directions, even for reverse calls. |
| Local handle | Slot + generation within one runtime owner. Never a network address or authority token. |
| Effect identity | Stable semantic operation identity across delivery attempts, scoped to authoritative principal/tenant/target. Distinct from call key. |
Use full identities at trust boundaries. A session may negotiate collision-checked compact endpoint/operation tables later; their mapping is scoped to that session epoch. Do not truncate IDs or fingerprints to 16-bit hash slots. Encode 64-bit counters and integers losslessly in TypeScript; plain JS number is insufficient beyond its safe integer range.
Canonical descriptors and compatibility#
Specify a domain-separated canonical binary descriptor and SHA-256 digest, with cross-language golden bytes. The descriptor must distinguish integer width/signedness, numeric/enum representation, nullable versus absent fields, field/variant identity, defaults where semantic, collection ordering and operation interaction/ownership requirements. Specify deterministic references for recursive schemas. Maps and sets need a specified ordering; source reflection order, host JSON serialization and sorted top-level keys alone are insufficient canonicalization. Exclude HTTP routes from value/layout identity; include security-relevant interaction policy in the appropriate contract/policy descriptor.
Treat compatibility as directional: a provider must accept every request the consumer is allowed to send, and the consumer must understand every response the provider is allowed to return. For stream lanes apply this independently in each direction. Numeric coercion and unknown variants are allowed only by an explicit adapter, never as implicit binary compatibility.
Two decoding profiles are proposed:
| Profile | Gate | Decoder |
|---|---|---|
| Keyed FlexMap | Valid bytes + recognized schema + directional compatibility + supported field/default rules | Look up stable field identities; reject missing required fields and unsupported required features. |
| Exact positional layout | All of the above + exact layout fingerprint and negotiated codec version | Generated positional reader with validated bounds. No fallback to guessed indexes. |
Legacy JSON is an explicitly negotiated value codec during migration. It does not authorize binary positional reads or collapse exact numeric types. Define JSON encodings for byte strings, wide integers and non-finite floating values before a contract using them is admitted. Existing TypeScript JSON validation already rejects unsafe integer and unsupported values; preserve that protection.
FlexBuffers supplies schema-less random-access encoding, not Reaktor's schema or lifetime rules. Its documented value conversions reinforce the need for explicit typed validation. Official FlexBuffers documentation.
The existing FlexBuffer implementation document records stability issues around map hash/equality, empty maps, null/default handling, required/layout rejection, cache concurrency and retention. These are documented qualification blockers, not freshly reproduced failures in this investigation. Reconcile each with current code and behavioral evidence before enabling the binary profile. See FlexBuffer implementation status.
Shared session protocol#
Layering and bootstrap#
Use one logical session envelope and exchange state machine with transport-specific framing. A provisional profile name is reaktor.session/1; final naming is a protocol-freeze decision. RGP retains its graph-control profile/version and message schemas. Application service payloads retain their own contract/schema identities. Do not collapse wire major, message schema, graph profile and operation contract into one version number.
Distinguish a new session peer from a legacy carrier adapter. New duplex peers perform the bootstrap below. An adapter to today's unary HTTP Served maps one admitted call to the existing request/response format; it does not send HELLO, CREDIT or a session envelope to an unchanged HTTP endpoint. Its supported contract, codec and unary-only limits are selected at admission. It shares caller state, context, typed outcomes and bounded resources through the endpoint SPI; it cannot advertise duplex session features. Contract and outcome conformance applies to both profiles; frame-transcript conformance applies to peers that actually implement the session wire protocol.
Bootstrap uses a fixed, bounded UTF-8 JSON object schema that both peers can decode before choosing an application codec. Its strict reader rejects duplicate keys, invalid numeric encodings, excessive depth and unknown required features. Wide counters are decimal strings. Network carriers use a length-prefixed frame or a carrier's explicit message boundary with an enforced maximum. C ABI and JNI carry explicit byte lengths. No receiver assumes NUL termination or discovers length by scanning.
Negotiate envelope encoding separately from value encoding. P1 uses the same logical envelope encoded as JSON, with encoded payload bytes represented as base64; this intentionally pays copying/size overhead to establish the path using existing value codecs. P2 can negotiate keyed FlexMap envelopes and binary payloads after qualification. Switch only after READY, never by guessing from failed decoding. The fixed bootstrap itself does not depend on the unqualified generated positional decoder. These encoding choices are defaults to confirm with the P0 golden corpus, not frozen bytes in this HLD.
HELLO/READY negotiate wire major/minor, required/optional features, envelope/value codecs, limits, interaction profiles, host capabilities, contract offers and the fresh link epoch. Authenticate the carrier/host provenance before disclosing a catalog; a bootstrap diagnostic must not reveal unauthorized endpoints. Unknown required features fail admission. Unknown optional features can be ignored only when the message schema says that is safe. Never fall back from an authority or fingerprint failure to a weaker profile. A peer advertises only modes it implements; P1 rejects unsupported streaming modes during admission.
Every steady-state envelope identifies kind, link epoch and call key where applicable, negotiated endpoint/operation reference, message schema and bounded metadata. OPEN additionally identifies interaction mode, relevant contract/layout choice, remaining deadline budget, initial response credit, and effect identity/digest when required. Per-lane DATA carries a monotonic sequence and payload. Layout/contract fields may be session-table references after negotiation; they remain semantically explicit.
Frame families#
| Frame | Semantics |
|---|---|
HELLO, READY, GOAWAY | Establish a link; negotiate; stop new opens while draining. |
OPEN | Create a call once after local resource reservation. Unary/server-stream mode includes one bounded request and closes the request lane. Client/bidi mode opens a streaming request lane. |
DATA(lane, seq, payload) | One ordered item in the request or response lane. Allowed only in a streaming lane and within granted credit. |
CREDIT(lane, items, bytes) | Additional bounded receiver allowance; additive and overflow checked. No credit is inferred from application observation or a successful transport write. |
HALF_CLOSE(request) | Caller has finished a streaming request lane. It does not close the response lane. |
FINISH(outcome, response?) | The callee's single terminal result. Unary/client-stream success carries exactly one response; server/bidi success follows zero or more response items. It closes both lanes. |
CANCEL(reason) | Caller requests termination and stops producing. Cancellation may race with effect commit or a terminal result. |
Reverse invocation is a new call with the other opener role, not a response DATA item interpreted as executable code. An unsolicited result, wrong opener, wrong epoch, illegal lane, duplicate/out-of-order sequence or second terminal is rejected according to the negotiated protocol-error policy. Retain bounded tombstones until an agreed call-ID/epoch boundary so late frames cannot resurrect closed calls. Close the link before counter wrap.
ACCEPTED from a local transport means the transport owns the submitted frame/copy. It is not a provider acceptance, grant decision, durable receipt or effect commit. Handler validation can return a typed rejection through FINISH. On a lost link, callers complete locally according to uncertainty rules; a missing FINISH does not leave an unbounded waiter.
State and races#
This is the caller-side projection; the callee has a corresponding admitted/running/finishing machine. One owner serializes each call's transitions. Only the callee emits wire FINISH; caller timeout/cancel can complete the local facade without waiting indefinitely for it. A later result can update an explicitly retained effect-status record, but cannot deliver a second completion to the original caller. If the callee finishes before a client request stream ends, the caller stops that producer and releases its buffers.
Exchange state and business effect state are separate. Model-check or exhaustively explore the finite race projection—cancel versus finish, close versus open, credit versus terminal, duplicate versus epoch change—then test generated transcripts in each language. Such checks establish protocol properties within their model; they do not establish device latency or arbitrary native memory safety.
Cold Kotlin Flow collection opens a distinct exchange per collection unless the authored port explicitly provides shared subscription semantics. Cancelling collection closes that exchange and its producer. TypeScript async-iterator return()/explicit close propagates cancellation; garbage collection is not the primary subscription cleanup mechanism. Late in-flight data after terminal is discarded and released against a bounded tombstone; it cannot reopen a call or consume fresh unbounded state. A repeated OPEN never executes the handler twice within a live call key.
Flow control and bounded retention#
Each receiver owns initial and incremental item/byte credits for each streaming lane. A sender must satisfy both. Credit counts encoded payload bytes using a specified accounting rule; frame and metadata overhead have separate fixed limits. A maximum item size prevents a legal item from requiring impossible credit. Credit is returned when bounded receiver capacity is released, not merely when bytes arrive.
Set explicit limits for frame bytes, metadata bytes/depth, initial unary request/response bytes, pending calls, streams, queued items/bytes, retained buffers, exported callback handles, tombstones and control frames. Reserve a bounded control path so terminal/cancel/credit progress is possible when data queues are full. Apply connection and per-principal/activation quotas so many small calls cannot evade a per-call bound. Do not replace today's unlimited socket inbox with another hidden unlimited adapter queue.
An event stream cannot silently drop items. A signal/latest-state port may conflate only when its contract declares that behavior. A watch/delta stream requires producer epoch and application cursor/from-to continuity; overflow produces an explicit reset/resnapshot requirement. A durable channel requires acknowledgment, redelivery and retention at its broker; stream sequence numbers are not a broker offset.
gRPC has four interaction shapes and ordered delivery within an individual stream, but its flow-control contract is distinct from these application credits. A future gRPC adapter must bound its own read/write queues and avoid assuming a successful write means peer application consumption. gRPC concepts, gRPC flow control.
Invocation sequence#
The receiver's initial response credit travels with OPEN; the callee grants request credit for client/bidi streams after admission. Callbacks/reverse calls use the same sequence with a separate call key and a separately admitted reverse endpoint.
Native ABI, buffers and scheduling#
ABI surface#
Evolve the existing Runtime.h boundary rather than exposing C++ classes or JSI values. A representative ABI has the following roles; signatures and symbol names remain provisional:
/* All public structs have struct_size and ABI version where applicable. */
status api_query(uint32_t required_major, api_table* out);
status runtime_create(const runtime_config* config, runtime_handle* out);
status session_open(runtime_handle runtime, const session_config* config,
session_handle* out);
status submit_copy(session_handle session, byte_view frame);
status pump(runtime_handle runtime, uint32_t max_events,
event_consumer consumer, void* context);
status invoke_sync(session_handle session, byte_view request,
buffer_handle* owned_result);
status begin_close(runtime_handle runtime, close_mode mode);
status runtime_destroy(runtime_handle runtime);
status buffer_view(buffer_handle buffer, byte_view* out);
void buffer_retain(buffer_handle buffer);
void buffer_release(buffer_handle buffer);
byte_view is pointer plus byte length with fixed-width fields and a defined null/empty rule. Status is an ABI-stable integer enum, never an exception or an unowned message pointer. No C++ exception crosses C/JNI. Structured remote errors are protocol values; local ABI statuses identify immediate acceptance or local failure. Version mismatch is detected before interpreting a struct. Specify size/alignment/calling conventions and supported architectures in the frozen header and compile its fixtures with C, C++ and Kotlin/Native consumers.
Production Kotlin wrappers hold generational runtime/session handles. Native opaque implementation pointers may remain internal to a qualified wrapper, but are never serialized or exposed as stable identities. Buffer handles have their own lifetime independent of an already destroyed runtime. Export the buffer API from a library whose code remains loaded until all handles are released.
Ownership rules#
| Operation | Rule |
|---|---|
submit_copy | Borrows bytes only for the duration of the call. On ACCEPTED, an internal immutable copy is owned by the session. On BUSY/CLOSED/invalid input, nothing is accepted and no frame-triggered handler has run. Validation before reservation must itself be bounded. |
pump events | Run on the declared runtime owner thread. Event frame views are borrowed until callback return; callers may copy or explicitly retain an owned immutable buffer if the event contract offers it. |
invoke_sync | Allowed only for an admitted bind.sync endpoint on its qualified owner/reentrancy path. Returns an owned result buffer. It cannot await network or async completion. |
| Buffers | Immutable while shared. Each retained reference has one release. Reading a view is valid while a reference is held; no runtime-owned scratch pointer escapes. Retain/release are thread-safe even if guest execution is thread-confined. |
| Optional owned submission | Add only after measurement. Ownership moves exactly once only when acceptance succeeds; on rejection the caller retains it. This is a buffer transfer guarantee, not exactly-once service execution. |
| Optional borrow | Restricted to a synchronous nested extent in one process with a qualified implementation. No suspension, storage, queueing, remote hop or escaping callback may retain the view. |
| Remote payload | Encoded value. Pointers, JNI references, StableRefs, JSI objects and runtime handles never cross a network. A distributed immutable reference requires a separately defined resource/lease protocol. |
Copying is the default portable implementation. Direct ByteBuffer views or external JS buffers are qualified optimizations only after owner lifetime, detach/finalizer behavior, GC and shutdown tests demonstrate safety. Calling a decoder zero-copy does not establish a zero-copy JNI-to-Hermes round trip.
Threading and reentrancy#
Keep one owner dispatcher per Hermes/JSI runtime. Submission may be thread-safe and enqueue immutable values, but no foreign thread executes guest code. A host wake hook may signal that the owner has work; it must not invoke JS itself. Coalesce wake signals, retain the callback context until a shutdown barrier, and bound each pump turn by events/time so input and cancellation are not starved.
Generated async C++/TS stubs return futures/promises or stream handles. Kotlin adapters resume continuations in the caller's structured scope. Completion is scheduled onto the appropriate owner rather than assumed to occur on the sending thread. Promise microtasks, timers and interrupt handling are part of the host profile; never block a runtime waiting for its own queued completion.
Default new bindings disallow synchronous reentrancy unless explicitly qualified. The current bridge's nested synchronous host callbacks remain supported by its compatibility profile. A generated reverse synchronous call can run inline only on a declared safe nested path. Reject an unsupported synchronous cycle; do not resolve it with an implicit mailbox/blocking wait. CPU-heavy C++ work can use a declared executor with value inputs, then post its completion back to the runtime owner.
Shutdown and failures#
Runtime states are OPEN -> DRAINING -> CLOSED. Draining refuses new opens/exports, cancels or drains admitted calls according to the selected mode and deadline, closes stream producers, then detaches callbacks and releases guest references on the owner thread. A synchronized admission gate and active-entry count fence concurrent submissions against destruction. runtime_destroy succeeds only after active entries, pump callbacks and accepted work reach the documented barrier; otherwise it returns BUSY/WRONG_THREAD. Wrappers make repeated close safe without dereferencing a freed native handle. Public generational-handle lookup must acquire a live owner reference before touching native state; returning a raw freed pointer is never the stale-handle check.
Outstanding independent immutable buffers remain valid until released. Callback endpoints are scoped to their activation/call owner, expire on close and cannot be reused through a stale generation. JNI global references and Apple StableRefs are disposed only after the callback barrier. An invalid stale handle is a local error, never a lookup of a newly allocated object in the same slot.
Ordinary C++ exceptions/JS exceptions become sanitized typed failures where the host boundary can catch them. Segmentation faults, arbitrary native memory corruption and an uninterruptible guest loop are not made recoverable by this ABI. Untrusted native code requiring isolation belongs in a separate process/session profile.
Context, cancellation and effect certainty#
Build on ExchangeContext, ServiceIdentity, existing interceptors and the four-way outcome model. Carry bounded trace propagation, authenticated principal association, environment/workspace/tenant, contract and activation identities, effect metadata and a remaining deadline budget. Service authorization does not trust a principal string supplied in the payload.
Convert incoming remaining budget into a local monotonic deadline; subtract elapsed time before forwarding. Do not compare wall-clock timestamps from different processes or restart the original budget at every hop. Existing Served already interprets its deadline metadata as a remaining duration; retain that intent while making it transport-neutral. Stop child work when the local scope is cancelled. gRPC deadline guidance supports remaining-budget propagation and application responsibility for stopping spawned work.
| Observation | Caller-visible interpretation |
|---|---|
| Rejected locally before a frame can be accepted | Known not submitted by this attempt. Return a precise local validation/unavailable/authority failure. |
| Provider rejects before invoking effectful work | Known not applied only if the provider explicitly supplies that certainty under the contract. |
| Domain rejection after handler execution | Typed business result. It is not a generic rollback guarantee; domain operations can reject after partial effects. |
| Timeout/cancel/link loss after possible submission | Outcome may be unknown. Never translate it to proof that the operation did not execute. |
| Authenticated retained commit record for the semantic effect | Applied/rejected status with its evidence and retention boundary. |
Keep result status and effect certainty distinct. Existing OutcomeUnknown is a useful foundation. Pre-dispatch gates may establish non-execution; a status code or absence of a reply generally cannot.
Preserve structured coroutine cancellation: Kotlin callers still receive CancellationException when their scope is cancelled. Record possible effect uncertainty through the bounded exchange/effect-status observation, rather than swallowing cancellation and returning an ordinary success/failure value. Other generated facades map cancellation to their native cancellation/closed-stream mechanism while retaining the same effect-identity semantics.
For keyed effects, allocate the stable effect ID outside the retry loop. Compute a canonical request digest from semantic request, target/operation, relevant revision and authoritative principal/tenant scope. Exclude transient call IDs, trace IDs and delivery deadlines. The authoritative commit owner atomically records request digest plus outcome with the domain effect, or declares a weaker guarantee. Reusing an effect ID with a different digest is a conflict.
A process-local session cache cannot advertise durable deduplication. A durable lookup(effectId) is meaningful only with declared retention and authority. An absent record does not prove non-execution if an older request can still arrive: require an enforced admission fence/tombstone or return uncertainty. Keep store epochs/fences at the actual commit owner. Do not build a generalized outbox or transaction coordinator merely to ship read-only/volatile baseline RPC.
On reconnect, establish a new session epoch and complete unfinished calls according to certainty. Do not automatically replay effectful requests or treat frame sequence numbers as recovery cursors. Retry policy uses declared effects/idempotency and budget; stream resumption is a separate contract with a cursor and producer epoch.
Authority, discovery and WebView integration#
Admission verifies caller authority and endpoint visibility before catalog disclosure and again at the required invocation/revocation boundary. It binds authority to the authenticated host/carrier context, exact operation, environment, activation and applicable tenant/workspace. A resource handle means an object is available; it does not grant permission. A fingerprint means bytes/contracts match; it does not grant permission either.
Export only declared graph ports. Reverse calls and callbacks receive narrowly scoped endpoint capabilities with generation and owner lifetime. They cannot enumerate arbitrary host methods or manufacture a new privileged target by passing a string. Preserve label/redaction policy before encoding/export, with bounded sanitized errors.
For WebView migration, retain the complete provenance chain: platform-confirmed origin/frame, navigation/session epoch, application revision, host-selected principal/workspace/environment, exact allowed operation list, schema checks, queue limits and revocation. Replace framing beneath these controls. A WebView CANCEL or SUBSCRIBE must remain scoped to that session; a generic RPC endpoint table is not a replacement for provenance. The current WebView design/status and WebBridge implementation are the baseline.
In-process C++ is trusted native code for memory-safety purposes. TypeScript in Hermes receives only explicitly exposed host capabilities, but generic FFI does not itself establish a complete security sandbox or make arbitrary host APIs safe. Privileged UI/component rendering must remain an explicitly granted graph capability with its own validated model.
The Surface renderer contract remains a separate UI capability; sharing the exchange engine does not broaden access to it.
RGP and transport integration#
RGP is a graph-control protocol: discovery, query/watch, activation/change and related owner operations have their own schemas, authority and compatibility axes. Reuse session framing, bounded lanes, cancellation, context and codecs underneath it. Keep exported application service contracts separate from graph-owner operations.
The Reaktor Graph Protocol design defines the base protocol. An optional Invoke extension may invoke an owner-exported graph operation through the existing operation gate, using shared exchange machinery. It must not turn every service call into an RGP query, bypass the owner kernel, or add a second executor. RGP envelope/schema details and this session proposal need one reconciled wire specification before either freezes overlapping fields.
| Adapter | Reuse | Adapter-specific obligations |
|---|---|---|
| Direct Kotlin | Service descriptors, policy/context, typed outcome | No bytes or queues when a direct admitted call suffices; preserve cancellation/scope. |
| JNI / Apple C ABI | Complete session engine and generated codecs | Native buffer ownership, owner-thread pump, callbacks, close barrier, ABI qualification. |
| Hermes TypeScript | Generated contract + minimal peer engine | Safe numeric representation, validated values, promises/microtasks, explicit host capability table. |
| Existing socket | Session multiplexing and streams | Bound carrier queues, keep transport authentication, propagate close, no silent auto replay. |
| Existing HTTP | Unary service model and codecs | Map statuses without losing typed certainty; enforce body/deadline limits. Streaming only where the selected carrier supports it. |
| WebView | Session framing/value schemas | Preserve host provenance/grants/navigation lifecycle and browser limitations. |
| Future gRPC | Contract and interaction shape where representable | Explicit schema/status mapping, deadline/cancellation propagation and queue/credit translation; no assumption that all Reaktor graph semantics fit protobuf. |
| Specialist native ABI | Selected operation wrapper | Preserve the specialist's owned state, status and allocation rules behind the graph endpoint. |
Do not claim gRPC or kotlinx.rpc is already the framework substrate. The inspected source does not establish that. Select a new external RPC dependency only for a concrete interoperability consumer after the initial existing-transport path works.
Replacement, Kotlin/JS and code push#
An activation owns the runtime instance, endpoint table, queues, callback scopes and leases. An admitted call pins its endpoint generation until terminal/drain. Replacing code prepares a candidate privately, validates it, publishes the new binding atomically, and drains or explicitly cancels the old generation. Existing calls must not jump to the new implementation midway.
Follow V2 region closure: unadapted bind dependencies, moved/borrowed state, shared session/global-type assumptions, schema accessors and fused artifacts can enlarge the replacement unit. Pin imports, contract/layout versions and host profile in the release manifest. Require explicit state migration and commit-owner epoch fencing where state changes. A rollback is a newly admitted generation; it is not reuse of an old mutable epoch.
The current bridge loads TypeScript into Hermes; this does not prove Kotlin/JS plus coroutines can run there. A Kotlin/JS host profile must qualify module loading, runtime/library versions, clock/IDs, timers, microtasks, dispatcher scheduling, promise completion, cancellation/interrupt budgets, memory limits and platform APIs. Strong compiler capture/effect checks remain a separate work item. Initial deployment uses compiled mobile/native artifacts; downloaded code and store/platform distribution policy are separate release decisions.
Do not implement a new C++ graph engine to make code push look symmetric. C++ exports declare their requirements and participate through admitted ports; graph interpretation stays with the owning Reaktor host unless measured requirements justify another implementation.
Observability and performance#
Extend existing service spans/interceptors. Correlate caller and provider with trace context, contract/operation ID, consumer/provider port, relation/binding identity, activation epoch, session epoch/call key and typed outcome/uncertainty. Record bounded queue wait, dispatch time, codec bytes, active call/stream counts, credits/stalls, rejected frames, dropped/reset signals, buffer retention and close/drain duration. Do not log payloads, credentials or unbounded exception strings by default.
The first acceptance walk is application -> service execution -> existing telemetry service -> Hangar, with the same call identifiable at each step. Use the existing telemetry path; a second telemetry bus is outside scope. A span says an execution was observed, not that a domain transaction durably committed. Telemetry outage must not block admitted calls unless an operation explicitly requires audit persistence at its authority boundary.
Measure JSON baseline first, then keyed binary, then any exact-layout/borrow optimization. Report complete Kotlin-to-C++/Hermes round-trip and async/stream paths: median/tail latency, allocations/copied bytes, throughput, peak retained memory, GC behavior and shutdown time on actual supported devices. Separate cold runtime creation from warm calls, small control payloads from large values, and native compute from boundary overhead. Codec-only numbers are not FFI latency.
Do not retain the old proposal's microsecond target as a measured fact. Set regression budgets from the initial measured consumer path, with device/OS/compiler/runtime/ABI and workload recorded. Use the existing reaktor-performance/FlexBuffer harnesses and extend them only for missing bridge measurements.
Alternatives and tradeoffs#
| Option | Assessment |
|---|---|
| Keep separate JSON bridges and network protocols indefinitely | Lowest immediate change, but each duplicates cancellation, authority, compatibility and flow-control behavior. Keep as migration adapters, not the destination. |
| Make FFI depend directly on current service module | Reuses types quickly, but pulls the IO dependency closure into embedded interop. The neutral extraction is justified by this concrete boundary. |
| Create a completely new FFI DSL and runtime mesh | Conflicts with graph-first/V2 direction and duplicates already useful service authoring and graph identity. |
| Use gRPC as the only internal ABI | Useful for some network consumers; does not solve JNI/StableRef/JSI lifetime, sync borrows, local owner scheduling or graph admission. Keep as a potential adapter. |
| Mirror the complete Kotlin engine in Kotlin/JS immediately | Attractive long term, but depends on an unqualified Hermes host profile. Start with generated foreign stubs and a minimal peer; consolidate when qualified. |
| Promise zero-copy from day one | Makes GC, shutdown and cross-runtime lifetime the critical path before proving a useful call. Start with copied immutable values. |
| Put a mailbox around every function | Simplifies one concurrency shape but changes sync semantics, adds latency and can deadlock nested calls. Declare exclusivity only where required. |
| Require the complete V2 IR/compiler first | Delays useful delivery unnecessarily. Implement explicit admitted binding records now, with a documented mapping to evolving V2 semantics. |
The principal cost of the recommendation is protocol and codegen discipline across three languages. Golden manifests/transcripts and a small bounded peer implementation are therefore baseline deliverables, not optional cleanup.
Delivery plan#
Scope and sequencing#
Proposed implementation budget: one new runtime module, extensions to the existing compiler/Dependeasy interop declarations, adapters in current service/FFI/graph-runtime modules, and focused conformance fixtures. No new graph runtime, scheduler, server, telemetry bus or per-language module family.
The implementation phases depend on one another as follows:
P2/P3 can progress independently after P1; migration requires the features actually used by a consumer. Do not wait for client/bidi streams to migrate a unary-only consumer. Later languages, gRPC and durable recovery are funded by concrete consumers rather than imposed on this critical path.
P0 — Contract and executable baseline#
Ownership: service/protocol maintainer with compiler and graph integration review. Extend existing authoring; create only the neutral module boundary.
Work: write canonical descriptor and protocol semantic specifications and their cross-language digest fixtures; enumerate current JSON consumers/exports; capture exact manifests and compatibility fixtures; define status/uncertainty mapping and resource budgets; settle the bind.sync extension; establish current JSON tests/measurements and reproducible build/device commands. Inventory the documented FlexBuffer blockers against current code, but do not make all binary optimizations prerequisites for the JSON walking path.
Exit gate: Kotlin/C++/TS agree on contract golden descriptors and IDs; negative schema/authority cases reject deterministically; JSON wide-number policy is explicit; every current synchronous behavior has a compatibility decision. Produce the versioned source for the ABI/protocol specification, not just prose in this HLD.
P1 — Graph-owned unary path, async boundary and observation#
Ownership: protocol engine in reaktor-rpc; service facade in reaktor-service; native runtime/pump in reaktor-ffi; graph bindings in reaktor-graph-runtime; host composition owns runtime lifetime. Compiler and Dependeasy own generation/packaging.
Work: extract neutral contracts/outcomes/context; implement bounded unary state and async submission/completion using the negotiated JSON value codec; add versioned ABI ownership/scheduling; generate initial Kotlin/C++/TS stubs; install a graph-admitted endpoint provider; adapt Link/Served and an existing socket or HTTP unary carrier. Preserve old sync APIs through explicit compatibility bindings. Instrument the existing observation path.
Use the existing native diagnostics/hello and Unicode/nested JSON round-trip fixtures for low-level bridge conformance. The concrete application acceptance contract is bestbuds.config, operation getConfig (Unit -> Config). ConfigGraph already binds it over HttpLink; ConfigRepository consumes it through a graph port; ConfigurationGraphTest already proves cached flag hydration followed by a refresh crossing that port. The proposed stable operation ID is bestbuds.config/getConfig, subject to the common ID normalization in P0.
Run an isolated dev/test composition with the existing cached graph_configuration_probe=false fixture, then supply the same Config value with the flag true from a generated TypeScript provider through FFI. Assert that the graph port/interceptor runs and the repository publishes/persists the refreshed flag. Run the same contract and fixture against Kotlin Served over the existing HTTP adapter, preserving the current live-provider option. The current Cloudflare configuration implementation is an existing Kotlin/JS server example, not a reason to require a new deployment. This exercises a real consumer and a read operation without changing production configuration or adding a new product API.
Exit gate: the selected graph consumer calls a C++ or TypeScript provider through Link/the endpoint SPI; the same declared contract runs against a Kotlin Served over an existing network adapter. Reverse host invocation is demonstrated. Application, service and Hangar show correlated evidence. Caller cancellation, late completion, wrong authority, close during work and stale handles have deterministic outcomes and bounded retained memory. Host tests and physical Android/iPhone evidence are recorded separately; an iOS framework build is not physical-device proof. No binary or exactly-once claim is needed to pass P1.
P2 — Safe binary values and native buffers#
Ownership: FlexBuffer/compiler maintainers and native interop owner; no new codec library or independent generator pipeline.
Work: reconcile/fix documented binary blockers with behavioral cases; implement canonical fingerprints and bounded validators across languages; enable keyed binary profile; qualify owned result buffers and length-bearing JNI/Apple transport; enable exact positional readers only behind layout equality. Compare against JSON without changing service semantics.
Exit gate: golden bytes and decode/re-encode cases match across Kotlin/C++/TS; malformed/truncated/deep/oversized input is bounded and rejected; integer limits, null/absent/default, required fields, enum variants and incompatible layouts are covered. Physical mobile round-trip and close/GC stress pass. Any fallback is negotiated in advance; invalid binary never triggers opportunistic JSON interpretation. Publish end-to-end measurements and copied-byte counts.
P3 — Structured streams and credits#
Ownership: shared engine plus existing socket/FFI adapters and generated language peers.
Work: ship server streams first; add request streams and bidirectional descriptors/stubs after the same lane machine passes conformance. Implement item/byte credit, reserved control capacity, structured producer cancellation and bounded tombstones. Adapt Flow, TS async iteration and C++ stream handles; document signal/event/channel distinctions.
Exit gate: slow consumers remain within fixed queue/memory limits; cancellation unblocks producers; both directions can make progress under full data queues; early callee finish, duplicate terminal, stale epoch, sequence gap and reconnect produce the specified result. Local and network peers execute the same transcript suite. Watch overflow produces explicit reset/resnapshot, and no durable channel guarantee is inferred from a stream.
P4 — Consumer and adapter migration#
Ownership: existing service/socket and WebView owners with host security review; native specialists keep their ABI ownership.
Work: migrate operation by operation from legacy JSON/kernel/socket machinery to the shared engine; retain bounded legacy adapters for old clients. Reconcile the RGP HLD/envelope and its optional owner Invoke extension. Migrate WebView only after origin/navigation/grant parity is demonstrated. Remove duplicate exchange state machines only when no consumer depends on them.
Exit gate: explicit old/new interoperability matrix, no authority/disclosure regression, no new unlimited queues, operational rollback by endpoint/profile selection, and a consumer inventory showing what can be deleted. Do not remove a specialist native ABI or a still-used sync binding for architectural symmetry.
P5 — Replacement and additional qualified hosts#
Ownership: graph activation/code-push and runtime/compiler maintainers.
Work: generation-pinned calls/callbacks/leases; prepare/publish/drain replacement; release manifest/import closure and state migration/fence hooks. Qualify Kotlin/JS/Hermes only if the consumer needs it. Add gRPC or another language only with its concrete contract mapping and qualification budget.
Exit gate: old calls cannot cross into new generations; stale handles/grants are rejected; old runtime resources retire at the defined barrier; rollback admits a new epoch; host profile evidence identifies supported timers/microtasks/coroutines/interrupt behavior. Durable effect recovery is advertised only by a commit owner with tested retention/fencing semantics.
Verification matrix#
| Concern | Required evidence before claiming support |
|---|---|
| Contracts | Cross-language canonical descriptor/digest fixtures; directional compatibility; operation identity stability; transport annotations excluded from layout. |
| Codec | Golden bytes; numeric boundaries including unsafe JS integers; null/absent/default; malformed/deep/truncated values; exact-layout mismatch before positional access. |
| Session | State/transcript conformance; unique role/counter keys; stale epoch; duplicate/open/terminal; sequence validation; cancel/finish/close races. |
| Memory | Hard queue and byte bounds under slow/absent consumers; buffer retain/release; repeated create/close; outstanding-buffer-after-close; no hidden unlimited adapter queues. |
| Threads | Wrong-thread rejection; owner pump; qualified nested callbacks; non-owner completion; no wait-for-own-pump deadlock; shutdown callback barrier. |
| Authority | Hidden catalog, wrong target/operation/tenant, revoked grant, stale activation, forged principal metadata, reverse endpoint scope. |
| Mobile | Host C++/TS tests plus distinct physical Android and iPhone runs through the supported wrappers; JNI/global-ref and StableRef cleanup. |
| WebView | Existing origin/frame/navigation/session/grant acceptance/rejection cases on each supported host before migration. |
| Effects | Known-not-submitted versus unknown; same effect/different digest conflict; commit-owner lookup retention and late-arrival fence for any durable claim. |
| Observation | Application -> service -> telemetry -> Hangar correlation; bounded/sanitized diagnostics; observation failure does not falsely determine effect status. |
| Performance | Warm/cold full-path measurements, allocation/copy counts, retained memory and device/runtime provenance. No codec-only latency substitution. |
| Replacement | Generation pinning, drain/cancel deadline, callback/lease retirement, state migration/fence, rollback as new epoch. |
Select affected checks through Atlas and existing Dependeasy interop declarations when implementing each phase. Run Gradle through the configured build wrapper. Mobile qualification requires supported physical Android and iPhone devices; a host test or framework build is a separate evidence class. Record the exact source, target, host profile and result for every claim.
Rollout and rollback#
Advertise new protocol/codec profiles only after their gate passes. Select an adapter/profile at admission and retain it for that call generation. Keep legacy clients on their original endpoint or explicitly negotiated legacy profile. Avoid a heuristic decoder that tries multiple protocols after failure. Canary one real consumer, inspect correctness/retention evidence, then migrate additional consumers.
Rollback selects a qualified earlier artifact/profile under a new activation epoch. It does not replay unresolved effectful requests, discard uncertainty, weaken grants or reinterpret incompatible layouts. Removal of legacy code is a consumer-inventory decision after old generations and buffers have drained.
Decisions before protocol freeze#
The recommendation above is concrete enough to begin a bounded implementation. These remaining choices require targeted evidence, not another framework redesign:
| Choice | Proposed default | Evidence needed |
|---|---|---|
| Neutral module name | reaktor-rpc | Confirm naming and source compatibility strategy during extraction. Dependency boundary is the substantive decision. |
| Sync authoring surface | Explicit local-only operation/profile on the existing service model | Small Kotlin/C++ callback prototype; equivalent synchronous authority/interceptor hooks; reject suspension. |
| Wire fields and canonical descriptor bytes | Bounded keyed bootstrap, strong domain-separated digests, explicit lane/epoch/required features | Cross-language golden corpus and RGP reconciliation. |
| Initial resource numbers | Conservative fixed host-profile budgets | Current fixture payload distribution and measured mobile retention; specify all limits before endpoint publication. |
| First app fixture details | bestbuds.config/getConfig with existing ConfigRepository cache/refresh behavior | P0 freezes complete safe dev fixture bytes, ID normalization and the test server composition; the operation is already selected. |
| C ABI wake/pump integration | Owner-driven pump, coalesced wake signal, copied submission | Android/Apple callback and shutdown prototype on real devices. |
| Durable effect support | No durable guarantee in the baseline | Actual commit-owner storage transaction, retention and admission fence. |
| Kotlin/JS in Hermes | Deferred qualification | Host-profile suite, not a successful TypeScript evaluation. |
Limitations#
- The unified layer is a proposal.
reaktor-rpc, graph-admittedRpcLink, the async ABI and the credit protocol still need implementation and conformance evidence. Existing JSON interop does not establish those guarantees. - Full V2 admission, resource/QoS typing and compiler capture/effect checks are not implemented by the current graph definitions. The initial binding record must state its actual checks and limits.
- Kotlin/JS in Hermes, downloaded-code replacement, additional language bindings and gRPC are later host qualifications with concrete consumers. TypeScript evaluation alone proves none of them.
- Binary framing requires both structural bounds validation and contract/layout validation. Reported FlexBuffer blockers must be reconciled before enabling that profile.
- Copied immutable values are the baseline. Borrows, shared buffers and zero-copy paths require a qualified lifetime and measurement; arbitrary native faults remain process faults.
- A timeout or cancelled call can leave an effect unknown. Durable deduplication and recovery can be claimed only by a commit owner with atomic recording, retention and fencing.
- The design selects the first application contract and its fixture behavior. Protocol bytes, complete fixture bytes, numeric budgets and final public API names remain P0 decisions.
Reference and source map#
Source paths below are relative to the named repository. They identify the implementation boundaries to inspect during delivery; existing tests describe coverage and do not qualify the proposed protocol.
| Area | Main code and evidence |
|---|---|
| Current mobile bridge | Module README, InteropRuntime, kernel interface, Kotlin exports, C++ kernel, native ABI and ABI implementation |
| Host ownership | Android JNI, Apple wrapper, TypeScript API, local collector |
| Service facade | Operation, Link, Served, Outcome, Socket, Shape, Compatibility, spans |
| Graph and host authority | GraphDefinition, ContractNode, WebBridge, specialist security ABI |
| Values and generation | FlexCoderProcessor, FlexBufferValidator, InteropBuild |
| Existing bridge tests | C++ tests, TypeScript tests, Android interop test |
| First application fixture | ConfigGraph, ConfigRepository, ConfigurationGraphTest, configuration Worker |
| Specifications to reconcile | Service layer, V2 index, types/ownership, realization, RGP, code push, implementation boundaries |
Related docs#
- Graph explains the nodes, ports and wiring that own these bindings.
- Service layer covers the authoring and client/server pipelines this design extends.
- Reaktor V2 defines the evolving semantic model.
- FlexBuffer implementation records codec status and the binary qualification work.
- WebView bridge describes the existing provenance and grant boundary.
- Telemetry and Hangar supply the observation path.
- Dependeasy owns generation, interop packaging and build checks.