Skip to content

[Mono.Android] Map mixed dictionary constructors from exemplars - #13723

Merged
simonrozsival merged 3 commits into
mainfrom
simonrozsival-valuetypefactory-constructor-mapping
Nov 24, 2026
Merged

simonrozsival merged 3 commits into
mainfrom
simonrozsival-valuetypefactory-constructor-mapping

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Context: #13721
Context: #13656

Java.Interop.ValueTypeFactory<T>.CreateReferenceMixedDictionary() requires an IL2072 suppression because Activator.CreateInstance() receives a runtime-constructed dictionary type whose constructors the trimmer cannot track.

Obtain the activation constructor from the statically rooted closed exemplar, map it onto the requested dictionary type with GetMemberWithSameMetadataDefinitionAs(), and invoke it. This applies the constructor-mapping approach from #13721 independently of that change and removes IL2072. Retain the closed exemplar roots: mapping preserves neither constructors nor the NativeAOT canonical templates for the exact value-type argument. The separate IL2055 and IL3050 suppressions for MakeGenericType() remain.

Add reference-key/value-type dictionary coverage alongside the existing value-key/reference-value test. A string/bool? case avoids the independently rooted string/int wrapper, allowing the reference-key exemplar to be tested in isolation.

Validation

On macOS arm64 with SDK 12.0.100-alpha.1.26556.115, Release arm64 apps were tested on the shared Android API 35 emulator (emulator-5554). Baseline and mapped SDK builds passed:

MSBUILDDISABLENODEREUSE=1 DOTNET_CLI_USE_MSBUILD_SERVER=0 make prepare leeroy CONFIGURATION=Release MSBUILD_ARGS="-nr:false"
MSBUILDDISABLENODEREUSE=1 DOTNET_CLI_USE_MSBUILD_SERVER=0 make leeroy CONFIGURATION=Release MSBUILD_ARGS="-nr:false"

The following build/install and test commands passed for each runtime, using the indicated runtime-specific arguments ($runtime_args):

  • Trimmed CoreCLR: -p:PublishTrimmed=true -p:TrimMode=full -p:PublishReadyToRun=false -p:_AndroidRuntime=CoreCLR — 49 passed, 0 failed, 0 skipped.
  • NativeAOT: no additional arguments — 49 passed, 0 failed, 0 skipped.
export MSBUILDDISABLENODEREUSE=1 DOTNET_CLI_USE_MSBUILD_SERVER=0
./dotnet-local.sh build -t:Install -c Release \
  tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj \
  -p:RuntimeIdentifier=android-arm64 -p:PublishAot=true \
  -p:IncludeCategories=NativeAOTTrimmable%2CTrimmableTypeMapRuntimeCoverage \
  -p:TrimmerSingleWarn=false -p:Device=emulator-5554 -nr:false -m:4 \
  $runtime_args
(
  cd tests/Mono.Android-Tests/Mono.Android-Tests
  ../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --no-build -c Release \
    -p:RuntimeIdentifier=android-arm64 -p:PublishAot=true \
    -p:IncludeCategories=NativeAOTTrimmable%2CTrimmableTypeMapRuntimeCoverage \
    -p:Device=emulator-5554 $runtime_args \
    --report-trx --results-directory <results-directory>
)

CoreCLR uses PublishAot=true to enable the safe managed conversion path while explicitly retaining CoreCLR. PublishReadyToRun=false avoids a baseline R2R packaging failure. Runtime evaluation confirmed _AndroidRuntime=CoreCLR and _AndroidRuntime=NativeAOT respectively; APK contents confirmed libcoreclr.so versus libMono.Android.NET-Tests.so.

No ValueTypeFactory warnings were emitted by the compiler trim analyzer, ILLink, or ILC. Baseline/mapped app warning comparisons showed only MSTest-generated lambda renumbering after adding the test.

Exemplar-only regression

The new test passed on a private Android API 33 emulator (emulator-5562): 50/50 for trimmed CoreCLR and 50/50 for NativeAOT. The build/install and test commands above were repeated with -p:Device=emulator-5562; the test invocation also included -p:TrimmerSingleWarn=false.

As a negative control, temporarily replacing the reference-key JavaDictionary<IJavaPeerable, T> exemplar with JavaDictionary<IJavaPeerable, IJavaPeerable> made only FromJniHandle_IDictionaryStringNullableBoolean fail on NativeAOT with Reflection_InsufficientMetadata_EdbNeeded (49 passed, 1 failed). Restoring the exemplar and rebuilding returned the run to 50/50. The production exemplar remains unchanged. Each SDK rebuild passed with:

MSBUILDDISABLENODEREUSE=1 DOTNET_CLI_USE_MSBUILD_SERVER=0 make leeroy CONFIGURATION=Release MSBUILD_ARGS='-nr:false -m:4'

Before adding the tests, matched signed APK builds (-t:SignAndroidPackage, otherwise the same build properties) measured CoreCLR 35,670,798 → 35,666,702 bytes and NativeAOT 13,215,861 → 13,211,765 bytes. Each difference is a single 4,096-byte alignment page; no meaningful size benefit is claimed.

`ValueTypeFactory.CreateReferenceMixedDictionary()` constructed the
requested closed `JavaDictionary<K,V>` with `Activator.CreateInstance()`
on a `MakeGenericType()` result, requiring an IL2072 suppression.

Instead, get the `(IntPtr, JniHandleOwnership)` constructor from the
statically rooted `TExemplar` type, map it onto the requested closed
type with `Type.GetMemberWithSameMetadataDefinitionAs()`, and invoke it.
The trimmer can see the exemplar constructor, so the IL2072 suppression
is removed. The IL2055 (`MakeGenericType()`) suppression stays, and the
IL3050 justification now covers only `MakeGenericType()`.

Add `FromJniHandle_IDictionaryStringInt32` to cover the reference-key
mixed dictionary path.

Co-authored-by: Copilot App <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 23, 2026 12:44

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

The test overstates exemplar-only template preservation because another test roots the same generic template, and runtime category filtering does not isolate that root.

1 open issue
What changed in this PR

This PR applies the constructor-mapping approach from #13721 to mixed reference/value-type dictionaries in Mono.Android, removing the IL2072 suppression while retaining the roots needed for trimming and NativeAOT.

Changes:

  • Resolve the activation constructor on a preserved exemplar, map it to the requested dictionary type, and invoke it.
  • Retain the closed exemplar roots and separate MakeGenericType() suppressions.
  • Add reference-key/value-type dictionary conversion coverage alongside the existing opposite-direction test.
File Description
tests/​Mono.Android-Tests/​Mono.Android-Tests/​Java.Interop/​JavaConvertTest.cs Adds IDictionary<string, int> conversion coverage.
src/​Mono.Android/​Java.Interop/​ValueTypeFactory.cs Replaces Activator.CreateInstance() with exemplar-based constructor mapping and removes IL2072 suppression.

Review effort: Balanced

simonrozsival and others added 2 commits November 24, 2026 09:10
The int template is also rooted by another test, so this case demonstrates conversion and constructor mapping rather than exemplar-only preservation.

Co-authored-by: Copilot App <[email protected]>
Use a nullable Boolean value with a reference key so this case does not share the independently rooted int template used by JavaDictionaryTest.

NativeAOT and trimmed CoreCLR test packages build successfully. Device execution remains unverified because the emulator crashes during boot.

Co-authored-by: Copilot App <[email protected]>
@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13723

@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.

✅ LGTM — code review

0 errors · 0 warnings · 1 non-blocking suggestion.

The constructor is selected from the statically rooted closed exemplar and mapped onto the requested closed dictionary type. The exact value-type exemplar roots remain intact, and removing the IL2072 suppression is consistent with no longer discovering constructors on the runtime-constructed type. Both mixed argument orientations use this helper. The new string/bool? case avoids the independent string/int construction in JavaDictionaryTest, while checking nullable element conversion and the resulting generic arguments.

All 38 GitHub checks report success, including the aggregate dotnet-android check for Azure build 1696678. Direct Azure build/timeline verification was unavailable: the build query required authentication and the timeline query failed during CLI initialization. The CoreCLR/NativeAOT device results and negative-control experiment are documented in the PR description; I did not independently rerun them.

Generated by Android PR Reviewer for #13723 · copilot · gpt61 · 32 AIC · ⌖ 7.86 AIC · ⊞ 20.3K
Comment /review to run again

source.Add ("present", true);
source.Add ("null", null);

var converted = InvokeJavaConvertFromJniHandle (typeof (IDictionary<string, bool?>), source.Handle, JniHandleOwnership.DoNotTransfer);

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.

🤖 💡 Testing — Consider adding a TransferLocalRef variant of this exemplar-only case, using a fresh local reference rather than transferring source.Handle, and checking that the local-reference count returns to baseline while the converted dictionary remains readable. Both new tests currently use DoNotTransfer; a transferred-reference case would also cover ownership consumption through the newly mapped constructor without introducing an independent closed-wrapper root.

{Rule: Test edge cases; JNI reference lifecycle}

@simonrozsival simonrozsival added the ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). label Nov 24, 2026
@simonrozsival
simonrozsival enabled auto-merge (squash) November 24, 2026 20:03
@simonrozsival
simonrozsival merged commit fb44aa1 into main Nov 24, 2026
38 checks passed
@simonrozsival
simonrozsival deleted the simonrozsival-valuetypefactory-constructor-mapping branch November 24, 2026 21:12
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