Skip to content

RFC: shared native host interface (rivetkit-host-adapter + C ABI), with a Java 25 SDK as first consumer - #6034

Open
cleaton wants to merge 8 commits into
rivet-dev:mainfrom
cleaton:java-sdk-v2
Open

cleaton wants to merge 8 commits into
rivet-dev:mainfrom
cleaton:java-sdk-v2

Conversation

@cleaton

@cleaton cleaton commented Nov 26, 2026 •

Copy link
Copy Markdown

Proposal

RivetKit's actor host logicturning rivetkit-core's events into calls into user code
(lifecycle order, timeouts, connections, HTTP/WebSocket dispatch, shutdown), currently lives
inside each binding. This PR proposes a shared, binding-independent native interface for
it, and adds a Java 25 SDK as its first consumer to prove the interface end to end.

This is meant as a starting point for discussion. Feedback on the boundary itself is the
most valuable part; the Java SDK shows it works.

Layers

Layer What it is
rivetkit-host-adapter (new crate) The actor event loop (ported from napi's, without deprecated state) behind HostActor/HostInstance traits, plus a byte-level wire protocol: u64 handles, ops and events with CBOR headers, bodies passed through untouched, leased buffers, credit-based streams, cancellation, per-resource ordering and ownership.
rivetkit-ffi (new crate) A 7-function C ABI over the wire protocol. Exactly one unsafe block (CI-enforced, Miri-tested). Header generated by cbindgen and checked in CI.
rivetkit-client (small, additive) action_cbor on handles/connections, so user CBOR passes through without a JSON round trip, and a typed ActionError. Existing behaviour unchanged.
rivetkit-java (new) Java 25 SDK over the C ABI via FFM: typed interface-based API (wrong events, params, hooks, schedules and async arguments fail to compile), per-actor turns on virtual threads, SQLite, connections and events, schedules and cron, raw HTTP streaming and WebSockets, actor-to-actor calls, a RivetTest harness.

napi, wasm and the Rust SDK are unchanged. Moving them onto the adapter is possible
follow-up work, not part of this PR.

Performance

Same counter actor, one Rust client driver, one local engine: Java is within 3% of the Rust
SDK (392 vs 404 sequential calls/s; 993 vs 1026 parallel) and ahead of TypeScript
(mise run bench:compare).

Testing

cd rivetkit-java && mise run test runs in about 15 s: 30 Rust tests, 31 Java unit tests
(including 16 compile-safety cases) and 47 end-to-end tests against a spawned engine on a
free port. A leak check at the end of the suite fails if any call is left waiting or any
stream, connection or socket is left open. CI (.github/workflows/java.yml) also checks
that the generated header and bindings are current and that there is exactly one unsafe block.

Known issues (not caused by this PR)

  • The debug engine sometimes exits on an internal storage check
    (tablet_maintainer_machine, "invalid state machine state"), failing the run it happens in.
    Seen in roughly 1 in 7–10 local runs; to be reported separately.
  • rivetkit-client: a subscribe sent while a connection is opening can be overtaken by the
    first action. One test retries around it; see the TODO in SdkTest.

Questions for maintainers

  1. Is a shared host adapter plus C ABI the direction you want for non-JS SDKs?
  2. Should napi/wasm move onto the adapter eventually, or should it stay Java/C-only?
  3. Is the wire protocol's shape acceptable (CBOR headers, u64 handles, leased buffers)?
  4. Where should the Java SDK live and be published from (Maven Central, per-platform native jars)?

Not in this PR

Publishing (native jars per platform, Maven Central, Windows), moving napi/wasm onto the
adapter, and file-level refactors in a few large files.

Design notes: rivetkit-java/DESIGN.md and rivetkit-java/BRIEF.md (both new in this PR).

cleaton and others added 7 commits November 26, 2026 12:09
Add a production Java SDK for Rivet Actors, built as a thin layer over the
Rust core through FFM.

- rivetkit-host-adapter (new): binding-independent actor host logic (the napi
  event loop without deprecated state) plus a byte-level wire protocol with
  u64 handles, CBOR headers, pass-through bodies, leased buffers and
  credit-based streams.
- rivetkit-ffi: a 7-function C ABI over the adapter, with one unsafe block.
- rivetkit-client: additive action_cbor on handles and connections so user
  CBOR passes through without a JSON round trip.
- rivetkit-java: interface-based typed API (compile-time checked events,
  params, hooks, schedules and async calls), per-actor turns, SQLite, vars,
  connections and events, schedule/cron, raw HTTP streaming and WebSockets,
  actor-to-actor calls, a RivetTest harness, examples and an e2e suite.
- CI: one Linux job running Rust and Java tests, bindings and unsafe checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- FeaturesTest + Lab test actor cover the rest of the actor and client API.
- Tests run concurrently on one shared registry; each run gets a fresh
  engine store (an engine on old data delayed the first call by ~30s).
- Per-test 20s timeout so hangs fail fast.
- Fixes found by the tests and reviews: a failing streaming writer now aborts
  the body instead of ending it cleanly; actor-initiated WebSocket close runs
  onClose; leased chunks are no longer freed when the actor stops; an object
  first argument followed by more arguments decodes positionally.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…fast stable tests

Fixes from a four-way review of the Java SDK, the Rust host adapter and FFI,
the shared client changes and CI, plus the test suite.

Public API (rivetkit-java):
- ActorContext<A, E>: schedule() and cron() take only the actor's own methods,
  and a context whose events are not the API's does not compile.
- Client.handleWithParams(api, params, key) replaces the untyped
  Handle.withParams(Object).
- connect(api, Supplier params, key) calls the supplier before every dial,
  reconnects included (new CONN_PARAMS event over rivetkit-client's
  connect_with_params; ABI 2 -> 3).
- Response is a sealed interface (Bytes | Streaming); the client side of a fetch
  is the new FetchResponse (AutoCloseable).

Correctness:
- A panic in a spawned op, or in serving, still completes its call (drop guard);
  Java no longer hangs on it.
- Ops on one response body go through a per-body FIFO, so a write, fin or abort
  never overtakes an earlier one.
- Client status events are held until Java knows the connection, then flushed
  in order with a status snapshot; Java ignores repeats.
- A client owns its connections, sockets and fetch bodies: releasing it releases
  them. Client.close() closes them on the Java side; ctx.client() closes when
  the actor sleeps; events for a released actor instance are dropped.
- onRequest request bodies are closed when the response is done, read or not.
- Client WebSocket sends go through a bounded queue (backpressure) and give up
  the actor's turn while they wait.
- Past 10,000 waiting events, an actor closes a flooding WebSocket with 1013.
- Releasing a registry that never served settles its ServeDone waiters.
- Db.transaction keeps the actor's turn (no deadlock with outbound calls).
- Failed async client calls complete on a virtual thread, not a Rust thread.
- A throwing completion callback fails the call instead of hanging it.
- Db.Statement.of accepts null parameters.
- A WebSocket opened inside an actor runs its listeners as actor turns.
- The ActionError doc comment (added by this branch) names the paths that
  actually return it.

Tests (~11s Java, ~4s Rust):
- The engine runs on a free port per run and is killed at JVM exit instead of
  waiting out its ~10s storage drain (21s -> ~10s).
- One leak check after all classes: no calls waiting on Rust, no streams,
  connections or sockets left open.
- Fixed flakes: response-abort race, warm-up without deadline, Rust wait_for
  limit, shared temp dir; separate-thread timeouts; core tests get timeouts.
- A typed-event test retries around a subscribe race in rivetkit-client.
- New tests for every fix above; 16 compile-safety cases.

CI: the Java job also runs on Cargo.lock, toolchain, engine and other
rivetkit-rust changes; no LFS checkout.

Known: the debug engine occasionally exits on an internal storage check
(tablet_maintainer_machine), failing a run; an upstream engine bug.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…e their fixes

Correctness (Rust host adapter):
- The client status snapshot is read under the hold-back lock and skipped when
  it repeats the last event, so a stale status can no longer follow a newer one.
- A connection, socket or fetch body opened while its client is being released
  is refused (insert_owned) and closed, instead of outliving the client.
- A client socket send waiting on a peer that stopped reading still sees close.
- A panic in a response body's writer task aborts the body instead of ending it.

Correctness (Java):
- An interrupted connect, fetch or webSocket closes what the late answer still
  creates (no orphan connection redialing forever).
- Request bodies are also closed when the request is refused as overloaded or
  cancelled while queued.
- A streaming response takes its keep-awake region before sending the head.
- A cancelled CONN_PARAMS request interrupts the params supplier.
- A connection or socket whose owning actor instance stopped is closed and
  logged instead of silently dropping events.
- A client socket's own listener sending on it keeps the turn (frame order).

API:
- handleWithParams(api, params, key, rest...): a String params type can no
  longer be mistaken for a key.
- Request, FetchResponse, Response.Bytes and Response.Streaming are final
  classes, not records; Response.of(status, headers, body).
- run, Schedule and Cron take up to three arguments, like async.
- ActorOptions.maxWaitingEvents; one overload policy (1013 for sockets),
  documented in DESIGN.md.

Cleanup: dead code removed (Rust ResponseBody::cancelled; Java Wire.Empty,
Turn.ownerThread, ApiModel.eventClasses, ActorType.liveInstances), shared body
helpers, Recorder.as, rivetkit-host-adapter as a workspace dependency,
#[expect] over #[allow], stale docs fixed. rivetkit-client keeps its existing
behaviour; a comment on action_cbor notes it duplicates action and could share
one path (left for upstream).

Tests (~10s Java with 8 threads, ~4s Rust):
- Tests now fail if their fix is reverted (unread bodies checked inside the
  actor; typed params and reconnect statuses asserted).
- Flood test uses a 100-event cap and a 300ms hold, so it no longer loads the
  other tests. Waits capped at 10s; polling every 25ms.
- Leak check compares against the idle baseline with <= and waits up to 10s.
- Rust: deterministic status hold-back tests, released-owner test, timeout on
  the body-order test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@eersnington

Copy link
Copy Markdown
Member

nice

@cleaton
cleaton marked this pull request as ready for review November 26, 2026 23:59
Brings in upstream's reconnect fix: actions sent on a socket that closes now
fail instead of waiting forever, and abandoned queued actions are never sent.
action_cbor shares the in-flight map and send path, so it gets the fix by
using the new InFlightRpc entry. Also bumps the rivetkit-host-adapter pin to
3.1.2-rc.9 to match the release bump.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@RivetAgent

Copy link
Copy Markdown
Contributor

No high-confidence issues found in the reviewed changes.

Checked for bugs and CLAUDE.md compliance; no applicable CLAUDE.md files were present. No Blocking, Should-fix, or Nit findings.

Builds and tests were not run. GitHub authentication was unavailable, so PR status and prior comments could not be verified.

Copy prompt to fix all
Fix all actionable findings in the latest Ironworks code review on PR rivet-dev/rivet#6034. Inspect every referenced location, address each finding without changing unrelated behavior, run the relevant tests, and summarize what changed.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants