Skip to content

[generator] Bind Kotlin suspend functions as Task-returning methods - #13583

Open
jonathanpeppers wants to merge 14 commits into
mainfrom
jonathanpeppers-kotlin-suspend-as-task
Open

jonathanpeppers wants to merge 14 commits into
mainfrom
jonathanpeppers-kotlin-suspend-as-task

Conversation

@jonathanpeppers

@jonathanpeppers jonathanpeppers commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: bf62112faf1fbe4325db588753a6e783851bbff1

Dimension Assessment Rationale
Change confidence 8/10 ↑ Generator tests pass (508), including a new test for the helper with and without kotlinx.
↑ The build test that binds kotlinx-coroutines-android passes locally, so the helper compiles against the real Kotlin and kotlinx bindings.
↑ Internal CI on the previous head: the only failure from this PR was this test (NU1101, DataStore packages not in the feed), now replaced; the other failures were DNS errors, a missing android-37.0 platform, an MSBuild version check, and PoliCheck findings in unchanged files.
↑ On a Pixel 7, Release with R8: resume, null, exception, and cancellation all work, with no Kotlin keep rules.
↑ The review finding about JNI peer lifetimes in the COROUTINE_SUSPENDED check is fixed and was checked on the device.
↓ Debug was checked on an earlier commit; later commits only changed the helper template and peer lifetimes.
↓ The DataStore on-device run used the earlier Mono.Android design.
↓ The helper's member names (Instance, COROUTINE_SUSPENDED, Job, Cancel) come from current Kotlin binding packages; other package versions were not checked.
↑ Latest main merged; it changed no generator or Kotlin code, and generator tests still pass.
↓ CI on this head not yet inspected.

Many Android libraries, such as DataStore, Room, and Paging, expose Kotlin suspend functions. On the JVM, a suspend function takes an extra kotlin.coroutines.Continuation parameter and returns Object. The binding generator emitted that JVM shape as-is, so C# code could only call it with a hand-written Continuation implementation.

Bindings now also get an *Async method that returns a Task. The existing method does not change.

Kotlin and C# side by side

Kotlin libraryC# binding (new *Async methods)
class WeatherClient {
    suspend fun temperature(city: String): Int

    suspend fun forecast(city: String): String?

    suspend fun refresh()
}
public sealed partial class WeatherClient : Java.Lang.Object {
    public Task<int> TemperatureAsync (string city,
        CancellationToken cancellationToken = default);

    public Task<string?> ForecastAsync (string city,
        CancellationToken cancellationToken = default);

    public Task RefreshAsync (
        CancellationToken cancellationToken = default);
}
val client = WeatherClient()
val t = client.temperature("Paris")
val f = client.forecast("Paris")
client.refresh()
var client = new WeatherClient ();
int t = await client.TemperatureAsync ("Paris");
string? f = await client.ForecastAsync ("Paris");
await client.RefreshAsync (cancellationToken);

The result type comes from the Kotlin metadata, not from the erased Object:

Kotlin result C# result
Unit Task
Int, Boolean, Long, … Task<int>, Task<bool>, Task<long>, …
Int? Task<int?>
String / String? Task<string> / Task<string?>
A bound class, such as Preferences Task<Preferences>
Type parameter, inline value class, or a type the binding does not generate Task<Java.Lang.Object>
Java platform type (String!) nullable, for example Task<string?>

A real example from androidx.datastore:datastore-preferences-core-jvm:

suspend fun DataStore<Preferences>.edit(transform: suspend (MutablePreferences) -> Unit): Preferences
public static Task<Preferences> EditAsync (IDataStore obj, IFunction2 transform, CancellationToken cancellationToken = default);

Generated binding

The generator keeps the existing Continuation-based method and adds a wrapper next to it. For temperature above (JNI body omitted):

[Register ("temperature", "(Ljava/lang/String;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;", "")]
public global::Java.Lang.Object? Temperature (string city, global::Kotlin.Coroutines.IContinuation _completion)
{
	// unchanged JNI call
}

public global::System.Threading.Tasks.Task<int> TemperatureAsync (string city, global::System.Threading.CancellationToken cancellationToken = default)
{
	return global::__KotlinCoroutines.InvokeAsync<int> (__continuation => Temperature (city!, __continuation), __value => global::Android.Runtime.Extensions.JavaCast<global::Java.Lang.Integer> (__value)!.IntValue (), cancellationToken);
}

The second lambda converts the Kotlin result to the C# type. Unit results call the non-generic InvokeAsync and return a Task.

Interface instance methods get the wrapper as an extension method in the existing *Extensions class. Static interface methods get it on the interface. The generator skips overrides, explicit interface implementations, methods that already use generateAsyncWrapper, and names that already exist.

Runtime: generated __KotlinCoroutines

There is no new API in Mono.Android. When a binding has at least one *Async wrapper, the generator also writes __KotlinCoroutines__.cs: an internal class in the binding assembly that the wrappers call. A binding with suspend functions already references the Kotlin standard library binding (Xamarin.Kotlin.StdLib), because the bound methods take Kotlin.Coroutines.IContinuation, so the helper uses the bound Kotlin types:

  • A nested Java.Lang.Object subclass implements Kotlin.Coroutines.IContinuation. It gets a normal Java callable wrapper.
  • When the Kotlin function returns IntrinsicsKt.COROUTINE_SUSPENDED, the Task completes later, when Kotlin calls resumeWith. Other return values complete it immediately. A kotlin.Result$Failure becomes the matching managed exception, for example Java.Lang.IllegalStateException. Result$Failure is internal in Kotlin, so the helper reads its exception field through JNI.
  • Cancellation: the token always cancels the Task. When the binding references kotlinx.coroutines, the continuation context is a new Job from JobKt.Job, and the token also calls IJob.Cancel, so cancellable Kotlin code (delay, withContext, …) stops. Otherwise, the context is EmptyCoroutineContext.Instance, and the Kotlin work continues.
  • R8 keeps the bound Kotlin types because managed code uses them, so no new ProGuard rules are necessary.

Alternatives:

  • A public helper in Mono.Android. That puts Kotlin knowledge into Mono.Android, and it needs a java.lang.reflect.Proxy, reflection, and Kotlin keep rules in every ProGuard configuration.
  • A separate NuGet package with a Kotlin bridge built on kotlinx.coroutines. That adds a build-time Kotlin dependency and a new package, and it requires kotlinx.coroutines in every app.

Validation

Standalone tests (bin\Debug\dotnet\dotnet test --project <csproj>, MSTest on Microsoft.Testing.Platform):

  • tests\Xamarin.Android.Tools.Bytecode-Tests: Passed 140, Skipped 2. Includes the new KotlinSuspendTests, which reads a Gradle-compiled SuspendFunctions.kt fixture.
  • tests\Java.Interop.Tools.JavaTypeSystem-Tests: Passed 17.
  • tests\generator-Tests: Passed 508. Includes the new KotlinSuspendTests, which runs the fixture through class-parse, the api.xml adjuster, and the generator.

Full SDK build (dotnet-local.cmd build Microsoft.Android.slnx, then -t:BuildExtraApiLevels, then -t:PackDotNet), then:

set TEST_ANDROID_JDK_PATH=<path to JDK 21>
dotnet-local.cmd test --test-modules bin\TestDebug\net11.0\Xamarin.Android.Build.Tests.dll --filter "Name~KotlinSuspendFunctionsAsTasks"

Passed 1/1. The test binds org.jetbrains.kotlinx:kotlinx-coroutines-android 1.10.2 with <AndroidMavenLibrary/>, and checks the generated HandlerDispatcherKt.AwaitFrameAsync and the Job in __KotlinCoroutines__.cs. Its dependencies are in the CI NuGet feed; the DataStore JVM packages are not.

On-device, CoreCLR:

  • Pixel 7 (arm64), with the generated __KotlinCoroutines helper: a Gradle module with Kotlin suspend functions, bound into an app with Nullable enabled. This is the same code as the new MSBuildDeviceIntegration test KotlinSuspendTests.SuspendFunctionsAsTasks. Release with $(AndroidLinkTool)=r8 logs sum=5 greeting=Hello, Kotlin nothing=True failure=boom canceled=True. That covers an asynchronous resume, a synchronous result, a null result, a Kotlin exception, and cancellation through kotlinx.coroutines.delay. Debug gives the same result. The generated binding code compiles without warnings.
  • x86_64 API 36 emulator, with the earlier Mono.Android helper design: the real DataStore library, Release with R8: two PreferencesKt.EditAsync calls and one canceled edit log count=2 thread=DefaultDispatcher-worker-1 canceled=True. The transform runs on a kotlinx.coroutines Dispatchers.IO worker thread, the second edit reads the stored value, and cancellation works.

I ran the MSBuildDeviceIntegration test project by hand, not through the test runner, because its Windows teardown runs adb kill-server on a shared host. The test uses kotlinx-coroutines-core:1.10.2 from Maven (compile only). If the CI Maven mirror does not have it yet, seed it with eng/gradle/mirror-dependencies.ps1 -MavenArtifact.

Copilot AI balanced review requested due to automatic review settings November 16, 2026 18:46
@jonathanpeppers jonathanpeppers changed the title jonathanpeppers kotlin suspend as task [generator] Bind Kotlin suspend functions as Task-returning methods Nov 16, 2026

Copilot AI 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.

🟡 Changes recommended

JNI peer-lifetime and generated-name collision bugs can cause runtime failures and uncompilable bindings, while the cancellation test does not verify that the Kotlin coroutine actually exits.

3 open issues
What changed in this PR

Adds Task-based bindings for Kotlin suspend functions, connecting Kotlin metadata parsing, C# binding generation, and the .NET for Android runtime.

Changes:

  • Preserves suspend-result metadata and generates *Async wrappers with optional cancellation tokens.
  • Adds a runtime continuation bridge for results, exceptions, and cancellation, plus R8 retention rules.
  • Adds bytecode, generator, binding-build, and device integration tests.
File Description
tests/​Xamarin.Android.Tools.Bytecode-Tests/​Xamarin.Android.Tools.Bytecode-Tests.csproj Embeds the suspend fixture.
tests/​Xamarin.Android.Tools.Bytecode-Tests/​KotlinSuspendTests.cs Tests suspend-result metadata extraction.
tests/​Xamarin.Android.Tools.Bytecode-Tests/​kotlin-gradle/​src/​main/​kotlin/​SuspendFunctions.kt Adds Kotlin suspend test cases.
tests/​Xamarin.Android.Tools.Bytecode-Tests/​kotlin-gradle.targets Tracks the compiled fixture output.
tests/​MSBuildDeviceIntegration/​Tests/​KotlinSuspendTests.cs Exercises results, failures, and cancellation on-device with R8.
tests/​generator-Tests/​Unit-Tests/​KotlinSuspendTests.cs Checks generated Task wrappers.
tests/​generator-Tests/​Unit-Tests/​KotlinInlineClassEndToEndTests.cs Shares the fixture-loading helper.
tests/​generator-Tests/​generator-Tests.csproj Embeds the suspend fixture for generator tests.
src/​Xamarin.SourceWriter/​Models/​MethodParameterWriter.cs Supports default parameter values.
src/​Xamarin.Android.Tools.Bytecode/​XmlClassDeclarationBuilder.cs Exports suspend-result metadata to XML.
src/​Xamarin.Android.Tools.Bytecode/​Methods.cs Stores suspend-result metadata.
src/​Xamarin.Android.Tools.Bytecode/​Kotlin/​KotlinFixups.cs Recognizes suspend functions and their result types.
src/​Xamarin.Android.Build.Tasks/​Tests/​Xamarin.Android.Build.Tests/​BindingBuildTest.cs Checks Task wrappers for DataStore bindings.
src/​Xamarin.Android.Build.Tasks/​Resources/​proguard_xamarin.cfg Retains reflectively accessed Kotlin members.
src/​Xamarin.Android.Build.Tasks/​Resources/​proguard_typemap.cfg Adds Kotlin retention rules for typemap builds.
src/​Xamarin.Android.Build.Tasks/​Resources/​proguard_typemap_coreclr.cfg Adds Kotlin retention rules for CoreCLR builds.
src/​Mono.Android/​PublicAPI/​API-37/​PublicAPI.Unshipped.txt Records the new runtime API.
src/​Mono.Android/​PublicAPI/​API-37.2/​PublicAPI.Unshipped.txt Records the new runtime API.
src/​Mono.Android/​PublicAPI/​API-37.1/​PublicAPI.Unshipped.txt Records the new runtime API.
src/​Mono.Android/​PublicAPI/​API-36/​PublicAPI.Unshipped.txt Records the new runtime API.
src/​Mono.Android/​PublicAPI/​API-36.1/​PublicAPI.Unshipped.txt Records the new runtime API.
src/​Mono.Android/​PublicAPI/​API-35/​PublicAPI.Unshipped.txt Records the new runtime API.
src/​Mono.Android/​Mono.Android.csproj Includes the coroutine bridge.
src/​Mono.Android/​Android.Runtime/​KotlinCoroutines.cs Bridges Kotlin continuations to managed Tasks.
src/​Java.Interop.Tools.JavaTypeSystem/​Adapters/​JavaXmlApiImporter.cs Preserves suspend metadata through type processing.
src/​generator/​SourceWriters/​KotlinSuspendMethodWrapper.cs Generates Task-returning suspend wrappers.
src/​generator/​SourceWriters/​InterfaceExtensionsClass.cs Adds suspend wrappers as interface extensions.
src/​generator/​SourceWriters/​BoundInterface.cs Integrates static wrappers and extension generation.
src/​generator/​SourceWriters/​BoundClass.cs Integrates class and nested-interface wrappers.
src/​generator/​Java.Interop.Tools.Generator.ObjectModel/​Method.cs Stores and clones suspend-result metadata.
src/​generator/​Java.Interop.Tools.Generator.Importers/​XmlApiImporter.cs Imports suspend-result metadata for generation.

Review effort: Balanced

@jonathanpeppers
jonathanpeppers force-pushed the jonathanpeppers-kotlin-suspend-as-task branch from e0feeef to 7b2b727 Compare November 16, 2026 22:43
@jonathanpeppers
jonathanpeppers force-pushed the jonathanpeppers-kotlin-suspend-as-task branch from 7b2b727 to da9ba1f Compare November 23, 2026 17:21
Base automatically changed from jonathanpeppers-kotlin-default-arguments to main November 26, 2026 13:34
@simonrozsival
simonrozsival force-pushed the jonathanpeppers-kotlin-suspend-as-task branch from b587d21 to a08bb04 Compare November 26, 2026 13:34
jonathanpeppers and others added 8 commits November 30, 2026 11:31
…thods

class-parse records the Kotlin result type of suspend functions in
api.xml (kotlin-suspend-return-type); the JavaTypeSystem adjuster passes
it through. The generator emits an additive *Async(…, CancellationToken)
method that calls the existing Continuation-based method through the new
Android.Runtime.KotlinCoroutines helper.

KotlinCoroutines creates the Continuation with java.lang.reflect.Proxy,
so Mono.Android has no build-time Kotlin dependency. When
kotlinx.coroutines is present, a Job is the coroutine context and the
CancellationToken cancels it.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…; add device test

* Java.Lang.Throwable is not a Java.Lang.Object: cancel the Job with a
  null cause, and convert the Result.Failure exception by peer reference.
* Add R8 keep rules for the Kotlin members that KotlinCoroutines finds by
  name, in all three default ProGuard configurations.
* Add an MSBuildDeviceIntegration test that binds a Gradle module with
  Kotlin suspend functions and awaits the generated *Async methods.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
* Always cancel the Task when the token is canceled; with kotlinx, also
  cancel the Job. Not all suspend functions observe the Job.
* Unregister (not Dispose) the token registration, so completion never
  waits for a running cancellation callback.
* Treat a missing kotlinx Job member like a missing kotlinx.
* Result types: skip inline classes (boxed here) and invalid or
  non-public types.
* Skip methods with an explicit interface; don't emit empty interface
  extension classes for static-only suspend methods.
* Add MethodParameterWriter.DefaultValue instead of a custom writer.
* Tests: drop a duplicate XML test; run the device test once, in
  Release with R8, which covers the keep rules.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…sk methods

datastore-preferences-core-jvm has real Kotlin suspend APIs. The test
binds it with <AndroidMavenLibrary> and checks that PreferencesKt.edit
gets a Task-returning EditAsync method. Version 1.2.1 matches the
published NuGet packages for its dependencies.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…findings

KotlinCoroutines.InvokeAsync<T> hid a nullability mismatch with
#pragma warning disable CS8603: JavaConvert.FromJavaObject<T> returns
T?, and C# cannot tell string from string? at run time. Split the API:

  * InvokeAsync<T> where T : notnull returns Task<T>, and throws when
    Kotlin breaks its non-null contract.
  * InvokeNullableAsync<T> returns Task<T?>.

The generator calls InvokeNullableAsync when the Kotlin result type is
nullable, so NRT bindings now get Task<string?> for String?.

Review fixes:

  * Kotlin platform types (T!) are nullable results.
  * Generic types fall back to Java.Lang.Object.
  * Add the [RestrictTo] warning to *Async wrappers.
  * Only add interface extension classes when a wrapper is generated.
  * Keep the Result.Failure exception alive while converting it.
  * Always cancel the Task, even when Job.cancel throws.
  * Treat any kotlinx lookup failure as kotlinx not present.

Tests: run the generator test through the shared adjuster helper, and
cover a nullable primitive result.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Only generated bindings call Android.Runtime.KotlinCoroutines, so:

  * Mark it [EditorBrowsable (EditorBrowsableState.Never)], like
    ResourceIdManager and GeneratedEnumAttribute.
  * Rename InvokeAsync<T>/InvokeNullableAsync<T> to
    CallSuspendFunctionAsync<T>/CallNullableSuspendFunctionAsync<T>,
    after the JNIEnv.Call*Method pattern.
  * Remove the non-generic InvokeAsync. A Unit result uses
    CallNullableSuspendFunctionAsync<Java.Lang.Object>, because
    Task<T> is a Task.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…tlin-side cancellation

* The generated self, cancellationToken and __continuation names now
  get a '_' prefix when a Kotlin parameter already uses the name.
* The device test cancels after the coroutine suspends, and checks
  that the Kotlin code stops (a finally block sets a flag). Before,
  the test passed even if the Kotlin Job was not canceled, because
  the token always cancels the Task.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…in *Async wrappers

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@jonathanpeppers
jonathanpeppers force-pushed the jonathanpeppers-kotlin-suspend-as-task branch from a08bb04 to b71bb50 Compare November 30, 2026 17:45
…pper

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@jonathanpeppers

Copy link
Copy Markdown
Member Author

/azp run Xamarin.Android-PR

@azure-pipelines

Copy link
Copy Markdown
No pipelines are associated with this pull request.

jonathanpeppers and others added 2 commits November 30, 2026 15:24
Remove `Android.Runtime.KotlinCoroutines` from Mono.Android. The generator now writes an internal `__KotlinCoroutines` type into each binding assembly that has Kotlin `suspend` wrappers.

The helper implements the bound `Kotlin.Coroutines.IContinuation` directly, and uses the bound `EmptyCoroutineContext`, `IntrinsicsKt.COROUTINE_SUSPENDED` and, when the binding references kotlinx.coroutines, `JobKt.Job` and `IJob.Cancel`. R8 keeps these types because managed code uses them, so the Kotlin keep rules are removed. Each wrapper converts the result itself, because `JavaConvert` is internal to Mono.Android.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Write the helper from one template, and cancel the Task before the Job so no try/finally is needed.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@jonathanpeppers

Copy link
Copy Markdown
Member Author

/azp run Xamarin.Android-PR

@azure-pipelines

Copy link
Copy Markdown
No pipelines are associated with this pull request.

The CI NuGet feed does not have the DataStore JVM and Okio packages, so restore failed with NU1101. kotlinx-coroutines-android has a real suspend API, and its dependencies are in the feed.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@jonathanpeppers

Copy link
Copy Markdown
Member Author

/review

@jonathanpeppers jonathanpeppers added the ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). label Dec 1, 2026
@github-actions

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13583

@github-actions github-actions Bot 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.

⚠️ Needs Changes

1 error · 0 warnings · 0 suggestions on 65636c8079b0632689ab95fc74a0e061b04c2dfa.

The inline finding identifies an unrooted JNI peer in the generated coroutine-marker comparison, which can cause a runtime abort on CoreCLR/NativeAOT.

The metadata-driven suspend detection preserves the existing continuation-based API, and the fixture covers nullable results and generated-name collisions.

CI: license/cla passed, but the current head has no dotnet-android Azure DevOps checks or commit statuses available; pipeline validation is unverified. Reviewed all 23 changed files in full. Static review only; builds and device tests were not run.

Generated by Android PR Reviewer for #13583 · copilot · gpt61 · ~65 AIC · ⌖ ~11 AIC · ⊞ 22.3K
Comment /review to run again

jonathanpeppers and others added 2 commits December 2, 2026 10:17
Store COROUTINE_SUSPENDED in a static field, and keep the result alive until IsSameObject returns, so the GC cannot delete their global references during the call.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@jonathanpeppers

Copy link
Copy Markdown
Member Author

@dalexsoto review

@dalexsoto

Copy link
Copy Markdown
Member

In response to @jonathanpeppers's request: The source changes and the follow-up fixes look consistent in the paths I reviewed. I still need the complete KotlinSuspendTests and KotlinInlineClassEndToEndTests changes, the kotlin-suspend-return-type export round-trip, the generated Continuation Java-wrapper path, and the referenced Kotlin/kotlinx member and R8-keep contracts (including GenBase.ContainsName and ParameterList.GetCall). These are reviewer coverage gaps, not defects found in the PR. No API error occurred; those integration reads were not completed within this bounded review interval.

@jonathanpeppers

Copy link
Copy Markdown
Member Author

@dalexsoto review

@dalexsoto dalexsoto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reviewed the Kotlin suspend-function generator, runtime continuation and cancellation handling, generated bindings, trimming/AOT integration, and tests. The pinned Kotlin stdlib failure representation matches the JNI lookup. No blocking issues found.

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

ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable).

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants