Skip to content

feat: async - #1923

Merged
raphaelrobert merged 11 commits into
mainfrom
raphael/async
Oct 12, 2026
Merged

raphaelrobert merged 11 commits into
mainfrom
raphael/async

Conversation

@raphaelrobert

@raphaelrobert raphaelrobert commented Jan 7, 2026 •

Copy link
Copy Markdown
Member

This PR introduces maybe_async for the storage provider. A few things to note:

  • the changes to the core library are fairly minimal
  • the sqlite providers remain exclusively "sync"
  • the sqlx provider is now exclusively "async"
  • the memory provider can do both
  • there's a new crate to test the "async" API by using the sqlx provider and the memory provider, and we test it on CI
  • sync remains the default mode

@raphaelrobert
raphaelrobert marked this pull request as ready for review May 15, 2026 20:14
@raphaelrobert
raphaelrobert requested a review from a team as a code owner May 15, 2026 20:14
tylerhawkes added a commit to xmtp/openmls that referenced this pull request Jul 24, 2026
…XMTP fork

Base: e125674 (insipx/bincode-fixes — the rev libxmtp pins).
Merged: 18a7243 (upstream raphael/async tip, main merged through 2026-05-15).

Storage traits become async-by-default via maybe-async 0.2.11 (AFIT mode);
the sync feature (maybe-async/is_sync) collapses everything back to the
existing synchronous shape, which is what libxmtp consumes today. The branch
also carries openmls_sqlx_storage — an async StorageProvider over sqlx whose
schema is relational (openmls_group_data keyed by (group_id, data_type))
rather than an opaque KV, which is what makes batched group loads possible.

Conflict resolutions:
- message_secrets.rs: keep the fork's 5-field persisted MessageSecrets with
  #[serde(skip)] added_at (upstream's #[serde(default)] 6th field corrupts
  stored MessageSecretsStore blobs mid-VecDeque under bincode).
- config.rs / past_secrets.rs / lifetime.rs / past_secrets tests: web-time
  import convergence (fork carry vs upstream openmls#2016) — upstream form kept.
- membership.rs: annotate the fork's update_group_membership with
  #[maybe_async::maybe_async] and await load_psks/stage_commit/
  write_group_state.

Fix an upstream defect that made the async path unbuildable:
openmls_memory_storage hardcoded openmls_traits/sync, and openmls_rust_crypto
depends on it unconditionally. Because maybe-async/is_sync is a global switch
on a proc-macro crate, any graph reaching rust_crypto was forced to compile
every trait in sync shape — which broke openmls_sqlx_storage's async impls
with 53 signature-mismatch errors. Neither sqlx_storage nor openmls_async_tests
is a workspace member, so nothing in CI ever compiled them and the rot went
unnoticed. MemoryStorage's StorageProvider impl is now maybe_async(AFIT) like
the rest, and both crates expose sync/async passthrough features.

Verified: cargo check -p openmls in both modes; full cargo test -p openmls
--features sync,test-utils green (23 suites, incl. the serde variant-index
lock tests); openmls_async_tests now compiles AND runs its end-to-end
two-member async group flow (credential -> add_members -> create_message ->
process_message) against SqliteStorageProvider over sqlx.

Known gap: sqlx_storage is SQLite-only (SqliteStorageProvider, sqlx feature
"sqlite"); Postgres needs a second provider plus a Migrate impl twin, since
migrator.rs copies sqlx's SqliteConnection Migrate impl to rename the
migrations table.
tylerhawkes added a commit to xmtp/openmls that referenced this pull request Jul 27, 2026
…ostgres sqlx provider

Base: e125674 (insipx/bincode-fixes — the rev libxmtp pins).
Merged: 18a7243 (upstream raphael/async tip, main merged through 2026-05-15).

Storage traits become async-by-default via maybe-async 0.2.11 (AFIT mode); the
sync feature (maybe-async/is_sync) collapses everything back to the existing
synchronous shape, which is what libxmtp's wasm and mobile targets consume.

Merge conflict resolutions:
- message_secrets.rs: keep the fork's 5-field persisted MessageSecrets with
  #[serde(skip)] added_at. Upstream's #[serde(default)] 6th field corrupts
  stored MessageSecretsStore blobs mid-VecDeque under bincode.
- config.rs / past_secrets.rs / lifetime.rs / past_secrets tests: web-time
  import convergence (fork carry vs upstream openmls#2016) — upstream form kept.
- membership.rs: annotate update_group_membership with maybe_async and await
  load_psks/stage_commit/write_group_state.

Fix an upstream defect that made the async path unbuildable: memory_storage
hardcoded openmls_traits/sync and openmls_rust_crypto depends on it
unconditionally. maybe-async/is_sync is a global switch on a proc-macro crate,
so every graph reaching rust_crypto compiled the traits in sync shape, breaking
openmls_sqlx_storage with 53 signature mismatches. Neither sqlx_storage nor
openmls_async_tests is a workspace member, so CI never compiled them and the rot
went unnoticed. MemoryStorage's impl is now maybe_async(AFIT) and both crates
expose sync/async passthrough features.

Teach openmls_sqlx_storage PostgreSQL alongside SQLite, behind 
(default) and  features that may be enabled together:
- storage_provider.rs used the compile-time query!/query_scalar! macros with a
  checked-in .sqlx offline cache, which bakes one driver in at compile time.
  Converted to the runtime API so a second dialect is expressible and no live
  database is needed to build; .sqlx/ and .env are deleted as dead.
- One impl_storage_provider! macro emits a whole module per backend. Emitting a
  module (rather than sharing types) is required because the Storable* newtypes
  carry inherent methods over an executor, and inherent impls are crate-global.
  It also leaves call sites byte-identical to upstream, which matters for a fork
  that has to rebase.
- The 26 statements live once in a statement_set! macro rendered per dialect;
  18 of them differ only in ?N vs $N, and silent drift between dialects in
  crypto-key storage is the failure worth engineering against.
- Postgres needs its own Migrate impl: sqlx's is copied per-backend solely to
  rename the migrations table, and the Postgres one takes a pg_advisory_lock.
- leaf_index binds as i64 on both backends since Postgres has no unsigned types.
  Verified backward-compatible against existing SQLite data: rows written with
  the old u32 binding are still found, and upserts still collapse onto the same
  primary key. SQLite's migrations/ are byte-unchanged, so deployed migration
  checksums still match.

Verified: openmls builds in both modes; full sync suite green (23 suites);
openmls_async_tests runs its end-to-end two-member async group flow;
sqlx_storage green on sqlite, postgres, and all-features, with the Postgres
round-trip suite (tests/postgres.rs, opt-in via OPENMLS_SQLX_POSTGRES_URL,
schema-isolated) passing against a live postgres:16.

Known gap: CI compile-checks Postgres but does not run its tests — that needs a
service container the macos matrix leg cannot host. No sqlx TLS feature is
wired; a deployment wanting encrypted connections enables sqlx/tls-rustls
downstream.
tylerhawkes added a commit to xmtp/openmls that referenced this pull request Jul 27, 2026
…ostgres sqlx provider

Base: e125674 (insipx/bincode-fixes — the rev libxmtp pins).
Merged: 18a7243 (upstream raphael/async tip, main merged through 2026-05-15).

Storage traits become async-by-default via maybe-async 0.2.11 (AFIT mode); the
sync feature (maybe-async/is_sync) collapses everything back to the existing
synchronous shape, which is what libxmtp's wasm and mobile targets consume.

Merge conflict resolutions:
- message_secrets.rs: keep the fork's 5-field persisted MessageSecrets with
  #[serde(skip)] added_at. Upstream's #[serde(default)] 6th field corrupts
  stored MessageSecretsStore blobs mid-VecDeque under bincode.
- config.rs / past_secrets.rs / lifetime.rs / past_secrets tests: web-time
  import convergence (fork carry vs upstream openmls#2016) — upstream form kept.
- membership.rs: annotate update_group_membership with maybe_async and await
  load_psks/stage_commit/write_group_state.

Fix an upstream defect that made the async path unbuildable: memory_storage
hardcoded openmls_traits/sync and openmls_rust_crypto depends on it
unconditionally. maybe-async/is_sync is a global switch on a proc-macro crate,
so every graph reaching rust_crypto compiled the traits in sync shape, breaking
openmls_sqlx_storage with 53 signature mismatches. Neither sqlx_storage nor
openmls_async_tests is a workspace member, so CI never compiled them and the rot
went unnoticed. MemoryStorage's impl is now maybe_async(AFIT) and both crates
expose sync/async passthrough features.

Teach openmls_sqlx_storage PostgreSQL alongside SQLite, behind `sqlite`
(default) and `postgres` features that may be enabled together:
- storage_provider.rs used the compile-time query!/query_scalar! macros with a
  checked-in .sqlx offline cache, which bakes one driver in at compile time.
  Converted to the runtime API so a second dialect is expressible and no live
  database is needed to build; .sqlx/ and .env are deleted as dead.
- One impl_storage_provider! macro emits a whole module per backend. Emitting a
  module (rather than sharing types) is required because the Storable* newtypes
  carry inherent methods over an executor, and inherent impls are crate-global.
  It also leaves call sites byte-identical to upstream, which matters for a fork
  that has to rebase.
- The 26 statements live once in a statement_set! macro rendered per dialect;
  18 of them differ only in ?N vs $N, and silent drift between dialects in
  crypto-key storage is the failure worth engineering against.
- Postgres needs its own Migrate impl: sqlx's is copied per-backend solely to
  rename the migrations table, and the Postgres one takes a pg_advisory_lock.
- leaf_index binds as i64 on both backends since Postgres has no unsigned types.
  Verified backward-compatible against existing SQLite data: rows written with
  the old u32 binding are still found, and upserts still collapse onto the same
  primary key. SQLite's migrations/ are byte-unchanged, so deployed migration
  checksums still match.

Verified: openmls builds in both modes; full sync suite green (23 suites);
openmls_async_tests runs its end-to-end two-member async group flow;
sqlx_storage green on sqlite, postgres, and all-features, with the Postgres
round-trip suite (tests/postgres.rs, opt-in via OPENMLS_SQLX_POSTGRES_URL,
schema-isolated) passing against a live postgres:16.

Known gap: CI compile-checks Postgres but does not run its tests — that needs a
service container the macos matrix leg cannot host. No sqlx TLS feature is
wired; a deployment wanting encrypted connections enables sqlx/tls-rustls
downstream.
@tylerhawkes

Copy link
Copy Markdown
Contributor

@raphaelrobert We're evaluating this branch for XMTP and merged it onto our fork. We hit three bugs, then prototyped the two receiver shapes that would prevent the third. Everything below reproduces on raphael/async at 18a7243.

openmls_memory_storage forces the whole graph to sync

memory_storage/Cargo.toml:13 pins openmls_traits = { workspace = true, features = ["sync"] }, and openmls_rust_crypto/Cargo.toml:14 depends on memory_storage unconditionally. maybe-async/is_sync is a global switch on a proc-macro crate, so any dependency graph that reaches openmls_rust_crypto compiles every trait in sync shape. openmls_sqlx_storage is async, so it fails with 53 signature mismatches, and openmls_async_tests does not build at all.

We annotated MemoryStorage's StorageProvider impl with #[maybe_async::maybe_async(AFIT)] and gave memory_storage and openmls_rust_crypto sync/async passthrough features.

Nothing in CI compiles the async crates

The root Cargo.toml carries exclude = ["sqlx_storage"], and openmls_async_tests is not listed at all. That is why the bug above survived. We understand the exclusion, since their async traits conflict with the workspace's sync default. A separate job that builds both would catch this class of drift.

Storage futures are not Send

SqliteStorageProvider holds RefCell<&mut SqliteConnection> at sqlx_storage/src/lib.rs:41 and keeps the borrow across await points, at 56 borrow_mut() sites in sqlx_storage/src/storage_provider.rs. RefCell is not Sync, so no MLS operation backed by this provider can be handed to tokio::spawn. Any server running a task per session is blocked.

openmls_async_tests misses it because that binary drives everything from main's future and never spawns.

We swapped the RefCell for tokio::sync::Mutex, which is Send + Sync and meant to be held across await, and added a compile-time Send assertion to the test crate.

Pools do not need a cell at all

&sqlx::Pool implements Executor, so a pool-backed provider satisfies the existing &self methods with no interior mutability. Shipping a pool flavor next to the borrowed-connection one would give most clients a Send provider by default, and keep the borrowed form for callers who need the provider to join a transaction they opened.

Receiver shape for 0.9

All of this follows from StorageProvider methods taking &self while a bare sqlx Connection only executes through &mut. Something has to close that gap, and the choice of primitive decides whether the futures are Send. We built both alternatives to get real numbers. Both are breaking, so 0.9 is the moment if either happens.

Measure with an isolated CARGO_TARGET_DIR. A shared one produces phantom &-vs-&mut errors across sibling checkouts, which cost us time twice.

&mut self

Branch tyler/exp-storage-mut-self. OpenMlsProvider::storage (traits/src/traits.rs:35) becomes a &mut self accessor. No GAT needed.

openmls compiles green in async, sync and test-utils modes. The library conversion is 67 files and about 790 lines.

The call sites are free. All 256 .storage() sites in openmls/src are byte-identical afterwards, because implicit reborrow of &mut Provider absorbs them, and the whole library needed two explicit &mut *x reborrows. We had budgeted this as the bulk of the work.

Both provider shapes then work with no cell, pool-backed and borrowed &mut Connection, and their futures are Send and tokio::spawn-able. That removes 56 lock acquisitions and the run_task helper from openmls_sqlx_storage.

The cost is 1383 unique error locations in test, bench, example and bin code. It does not respond to mechanical fixing: 846 regex substitutions closed 220 of them, because each &mut added exposes a new E0596 or E0499 one level up. The cause is harnesses that hold a provider in a struct and hand out overlapping shared borrows, not .storage().

self by value, the serde Serializer pattern

Branch tyler/exp-storage-by-value. Implementors pick their own receiver:

impl StorageProvider for &PostgresPoolProvider      // shared, concurrent
impl StorageProvider for &mut SqliteStorageProvider // exclusive, no cell

This is the smaller diff at 38 files and about 830 lines, and the only shape where one trait serves both providers natively. &P is Copy, so a pool handle drives two live futures with no reborrow at all.

It needs a GAT:

type StorageError: Debug + Error;
type StorageProvider<'a>: storage::StorageProvider<{CURRENT_VERSION}, Error = Self::StorageError> where Self: 'a;
fn storage(&mut self) -> Self::StorageProvider<'_>;

Hoisting StorageError out is mandatory, since Self::StorageProvider<'?>::Error cannot be named without picking a lifetime.

A provider that itself carries a lifetime parameter then fails Send with "implementation of OpenMlsProvider is not general enough". That is a GAT well-formedness limit rather than a genuinely !Send future, and it clears only when the provider has no lifetime parameter. Two of our three providers carry one, so this is the reason we are not adopting it.

The friction is also not reborrows. rustc auto-reborrows &mut receivers even for by-value self. The failures land in functions holding an opaque Storage: StorageProvider by value, where a reborrow cannot be expressed, and they became 10 signature changes: MlsGroup::{load,delete,store}, PublicGroup::{load,delete,store,from_external,merge_commit} and load_psks twice. PublicGroup's storage methods widen from PublicStorageProvider to a full OpenMlsProvider, which is a capability regression for public-group-only clients.

Its test tail is not comparable to the 1383 above. openmls/src/test_utils still has 47 errors, so the downstream crates are blocked behind them and unmeasured.

What both variants hit

A function returning an elided-lifetime type alongside &mut Provider silently pins the provider exclusively, so the next call in the chain is E0499. Two independent conversions hit this, which points at &mut itself rather than either encoding. The case we found is build_group at openmls/src/group/mls_group/commit_builder/external_commits.rs:136.

CommitBuilder::load_psks(storage: &'a Storage) at openmls/src/group/mls_group/commit_builder.rs:315 ties the storage borrow to the builder's lifetime even though the builder never keeps it. Under &self that is invisible. Under &mut it freezes the provider for the rest of every commit chain, and decoupling it dropped one conversion from 37 errors to 8 in a single edit.

Expressions mixing crypto() and storage() become E0502 and need the crypto call hoisted to a let.

Whether it is worth doing

Branch tyler/exp-storage-pool-baseline shows a pool-backed provider satisfying the current &self trait with no interior mutability, on an otherwise unmodified tree. So the receiver change buys a cell-free borrowed connection and nothing else. Clients that only need a pool are already fine today.

Branches

The three fixes are on xmtp/openmls tyler/maybe-async, which also adds a PostgreSQL backend to openmls_sqlx_storage behind a postgres feature. That is what made the Send behavior matter to us. The three experiment branches are based on it rather than on raphael/async, so a diff against upstream will include that work.

Happy to open PRs for any of this, whichever pieces are useful to you. The three fixes are the obvious ones, but the same goes for the pool provider, the CI job, or either receiver shape if you decide to take one for 0.9.

@raphaelrobert

Copy link
Copy Markdown
Member Author

Thanks for the feedback. Note that this is still in an early stage and should not be expected to work flawlessly. It's out of sync with the main branch and will likely see substantial changes. We'll resume work on this after v0.9 is published.

@raphaelrobert
raphaelrobert requested a review from a team as a code owner September 24, 2026 16:18
@raphaelrobert

Copy link
Copy Markdown
Member Author

@raphaelrobert We're evaluating this branch for XMTP and merged it onto our fork. We hit three bugs, then prototyped the two receiver shapes that would prevent the third. Everything below reproduces on raphael/async at 18a7243.

Thanks for reporting the issues, they should all be addressed in the refactoring now.

@boxdot
boxdot self-requested a review October 8, 2026 13:03
# Conflicts:
#	openmls/src/group/mls_group/creation.rs
#	openmls/src/group/mls_group/updates.rs
#	openmls/src/key_packages/vc.rs
#	openmls/src/treesync/node/leaf_node.rs

@boxdot boxdot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me!

I checked that the code is basically the same (except for several replacements of iterators by loops) in sync mode.

The Send+Sync requirement on futures in the provider traits is a tradeoff, which won't allow to implement those traits in a non-send context. However on the other hand, the requirement for futures to be able to be spawned on different threads is more important for us.

@raphaelrobert
raphaelrobert merged commit 8ee6b40 into main Oct 12, 2026
50 checks passed
@raphaelrobert
raphaelrobert deleted the raphael/async branch October 12, 2026 11:39
MicroDroid pushed a commit to MicroDroid/openmls that referenced this pull request Nov 17, 2026
* introduce maybe_async

* follow-up to merging main branch

* refactoring

* make reinit async as well

* include reinit & fork resolution in async tests

* one feature mode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants