Repository navigation
[TrimmableTypeMap] Avoid assembly reflection during peer lookup - #13526
simonrozsival wants to merge 10 commits into
Conversation
NativeAOT repeatedly constructs reflection assembly metadata while checking whether a sealed target belongs to Mono.Android. Move that eligibility check into typemap generation and encode it in a marker proxy base class, without adding state to each proxy instance. Keep external peers on the Java hierarchy lookup path because they may use a different class loader. Include the generated base in typemap fingerprints and cover aliases, generic targets, and runtime fallback. Fixes #13421. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
🟡 Changes recommended
The alias test cases emit no proxies, so their assertions never run and base-class and constructor selection remain untested.
1 open issue
What changed in this PR
Addresses #13421 by moving sealed-framework peer eligibility checks from runtime reflection into generated proxy types. This reduces NativeAOT peer-lookup overhead while preserving hierarchy lookup for external peers that may use different class loaders.
Changes:
- Adds a marker base for sealed
Mono.Androidpeers and uses it during runtime lookup. - Propagates eligibility through scanning, generation, constructor emission, and both typemap fingerprints.
- Adds regression tests and updates the public API baseline and interop documentation.
| File | Description |
|---|---|
tests/Mono.Android-Tests/Mono.Android-Tests/Java.Interop/TrimmableTypeMapTypeManagerTests.cs |
Extends device tests for marker eligibility and hierarchy lookup. |
src/Mono.Android/PublicAPI/API-37/PublicAPI.Unshipped.txt |
Records the new marker base API. |
src/Mono.Android/Microsoft.Android.Runtime/TrimmableTypeMap.cs |
Replaces reflection-based eligibility checks with marker detection. |
src/Mono.Android/Java.Interop/JavaPeerProxy.cs |
Defines the marker base without additional instance fields. |
src/Microsoft.Android.Sdk.TrimmableTypeMap/Scanner/JavaPeerScanner.cs |
Captures sealed-type metadata. |
src/Microsoft.Android.Sdk.TrimmableTypeMap/Scanner/JavaPeerInfo.cs |
Stores sealed status in scanner results. |
src/Microsoft.Android.Sdk.TrimmableTypeMap/Generator/TypeMapAssemblyEmitter.cs |
Emits the selected base and matching constructor reference. |
src/Microsoft.Android.Sdk.TrimmableTypeMap/Generator/ModelBuilder.cs |
Restricts marker eligibility to sealed Mono.Android types. |
src/Microsoft.Android.Sdk.TrimmableTypeMap/Generator/Model/TypeMapAssemblyData.cs |
Carries eligibility in the generation model. |
src/Microsoft.Android.Sdk.TrimmableTypeMap/Generator/MetadataHelper.cs |
Includes eligibility in both fingerprints. |
src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/TrimmableTypeMapIncrementalTests.cs |
Tests invalidation and deterministic identity changes. |
src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/GenerateTrimmableTypeMapTests.cs |
Adds parameterized base-class and constructor checks. |
Documentation/guides/internals/JavaJNI_Interop.md |
Explains marker-based lookup and class-loader restrictions. |
Review effort: Balanced
|
/review |
|
✅ Android PR Reviewer completed successfully!
|
The sealed-peer generator test used alias peers without activation constructor metadata. Alias groups therefore emitted no proxies, making the loop over generated proxy types vacuous for those cases. Give both peers activation metadata and assert that the expected proxies are emitted before checking their base and constructor references. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
Findings: 0 ❌ errors · 0
The scanner-to-model-to-emitter path consistently limits the marker base to sealed Mono.Android targets, and the emitted constructor calls the selected base. Including eligibility in both fingerprints correctly covers incremental invalidation and deterministic MVID changes. The runtime retains the existing remapping, assignability check, and JNI-reference cleanup. The latest test-only commit c315011017 also fixes the previously vacuous alias cases by supplying activation metadata and asserting the proxy count.
CI: GitHub reports five Azure DevOps checks in progress, the aggregate check queued, and CLA passing for the current head. Azure build 1678182 is not confirmed green; the direct Azure build query requires authentication, so deeper pipeline status was unavailable. The PR's reported local test and benchmark results were not independently rerun during this review.
Generated by Android PR Reviewer for #13526 · copilot · gpt61 · 63.6 AIC · ⌖ 7.58 AIC · ⊞ 19.5K
Comment /review to run again
Context: #13526 The existing external-peer test created its Java object through the runtime loader, so it did not cover duplicate class identity across loaders. Load the fixture from the app APK using a PathClassLoader with a null parent, assert the object is not an instance of the runtime-loader class, and verify typemap lookup still chooses the unmarked external proxy. The Release on-device runtime suite passed: 1,057 passed, 8 skipped. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
CA1422 fails the build because `Class.NewInstance()` is obsoleted on API-34+. Use `Class.GetConstructor().NewInstance()` instead. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
/review |
|
✅ Android PR Reviewer completed successfully!
|
There was a problem hiding this comment.
Code assessment: no blocking findings. 0 ❌ errors, 0
The scanner-to-model-to-emitter change consistently selects the marker base and its constructor only for sealed Mono.Android targets. The runtime retains the class-loader safeguard for external peers, and the eligibility bit participates in both incremental and content fingerprints. The generated-base/constructor matrix, incremental invalidation checks, and on-device class-loader and generic cases provide useful coverage. The documented NativeAOT measurements support the narrowly stated performance claim; the description appropriately avoids claiming a demonstrated CoreCLR or whole-app speedup.
CI verification is incomplete: all 40 GitHub checks report success, including the aggregate dotnet-android check for Azure build 1679658. Direct Azure build/timeline verification was blocked: the build query required authentication, and the timeline query failed during CLI initialization. I therefore cannot independently confirm the Azure result or per-stage evidence. This was a static review of head d758a06740f800b81fc2e055fa0c51465bcff580; host/device tests and benchmarks were not rerun.
Generated by Android PR Reviewer for #13526 · copilot · gpt61 · 59.1 AIC · ⌖ 4.74 AIC · ⊞ 20.2K
Comment /review to run again
…sSealed (#13526) Context: #13526 (comment) Review feedback asked whether the `JavaPeerProxyForSealedFrameworkClass` marker base class was necessary, or whether a `JavaPeerProxy.IsSealed` property could be used instead. A property works without the per-instance cost that originally motivated the marker class: `JavaPeerProxy.IsSealed` is a virtual property that returns `false`, and the generator emits an override returning a constant `true` only for proxies of sealed Mono.Android targets. No field is added to any proxy. `IsSealed` intentionally stays `false` for sealed app and library types. Those Java classes can be loaded by a different class loader, so resolving them by name via `FindClass` could incorrectly reject a valid object; they keep using the object's Java class hierarchy. `TrimmableTypeMap.TryGetSealedTargetProxy()` now checks `proxy.IsSealed`, and the generator, on-device tests, PublicAPI, and internals documentation are updated accordingly. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Context: #13526 (comment) Removing the `Type.Assembly` check also removed the cheap `!targetType.IsSealed` early return, so every nonsealed target (e.g. `Java.Lang.Object`) performed a `GetProxyForManagedType()` lookup -- including generic normalization and, on a cold cache, attribute instantiation -- before falling back to hierarchy traversal. Restore the `Type.IsSealed` check ahead of the proxy lookup. Behavior is unchanged: the generator only emits `IsSealed => true` overrides for sealed targets, so a nonsealed target could never take the sealed fast path. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Context: #13526 (comment) The previous commit made `JavaPeerProxy.IsSealed` a virtual property, with a generated constant-`true` override on every proxy for a sealed Mono.Android target. That avoided a per-proxy field, but it meant emitting ~2,950 extra getter methods and property rows into `_Mono.Android.TypeMap.dll`. Make `IsSealed` a non-virtual, get-only property backed by a field, set through a new `protected JavaPeerProxy(string, Type, bool)` constructor. The generator now passes `CanResolveFromSealedTargetType` as the third constructor argument instead of emitting a `get_IsSealed` override. The existing two-argument constructor remains and passes `false`. We compared the marker-class, virtual-property, and field-backed shapes by publishing `dotnet new maui --sample-content` (Release, android-arm64) with each variant. Signed APK sizes: | Variant | NativeAOT | CoreCLR | | --------------- | ---------- | ---------- | | Marker class | 21,183,598 | 22,081,296 | | Virtual | 21,187,694 | 22,081,296 | | Field-backed | 21,187,694 | 22,081,296 | The field-backed variant keeps `_Mono.Android.TypeMap.dll` at the marker-class size (293,888 bytes vs. 296,448 for the virtual variant), and the NativeAOT APK difference against the marker class is a single 4 KiB ZIP alignment step. These are package-size measurements only; the sample also produced an unrelated ILC warning from Syncfusion.Maui.Toolkit, and no runtime measurements were taken for these variants. `IsSealed` still remains `false` for sealed app and library types, because their Java classes can be loaded by a different class loader. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Context: #13526 (comment) The nonsealed guard prevents managed-proxy lookups for common target types before walking the Java hierarchy. Verify that resolving a string with Java.Lang.Object as its target does not populate the managed-proxy cache, while still returning the expected peer. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
/review |
|
✅ Android PR Reviewer completed successfully!
|
There was a problem hiding this comment.
✅ LGTM — no correctness issues found. 0 errors · 0 warnings · 1 non-blocking testing suggestion inline.
The scanner → model → emitted constructor → runtime flag is wired consistently. The Mono.Android restriction preserves the class-loader safeguard, the nonsealed early return remains ahead of managed-proxy lookup, and the eligibility bit participates in both incremental and content fingerprints. Retaining the two-argument constructor preserves existing callers. The alias/generic constructor checks and separate-class-loader regression are good coverage.
CI: GitHub reports all 40 checks successful, including the aggregate dotnet-android check for Azure build 1680695. An independent Azure build-status query required authentication, so detailed Azure results were not verified. This was a static review; no local builds or device tests were run. The description correctly limits its timing evidence to the earlier marker-class implementation rather than claiming measurements of the final bool-backed version.
Generated by Android PR Reviewer for #13526 · copilot · gpt61 · 69.8 AIC · ⌖ 7.39 AIC · ⊞ 20.3K
Comment /review to run again
Context: #13526 (comment) The emitter and fingerprint tests set `JavaPeerInfo.IsSealed` by hand, so they would keep passing if `JavaPeerScanner` stopped recording it. Scan the built `Mono.Android.dll` reference assembly and assert that sealed `Java.Lang.String` and nonsealed `Java.Lang.Object` report the expected `IsSealed` values. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Context: #13526 (comment) The scanner regression test depends on a locally built Mono.Android reference assembly, so it skips in standalone test runs. Generate a small assembly with sealed and nonsealed registered peers instead, ensuring the scanner's sealed metadata is checked without a local Android SDK. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
/review |
|
✅ Android PR Reviewer completed successfully!
|
There was a problem hiding this comment.
⚠️ Needs Changes — performance validation
Findings: 0 errors, 1 warning, 0 suggestions. No correctness defect identified; the inline warning asks for matching performance measurements of the final bool-backed implementation rather than the earlier marker-class variant.
The scanner → model → emitted constructor → runtime flag is consistently wired. Both incremental and content fingerprints include eligibility, the existing two-argument constructor remains available, and the nonsealed early return and external-peer class-loader safeguard are preserved. The scanner regression, constructor-shape matrix, fingerprint coverage, and separate-class-loader test provide useful complementary coverage. Previously resolved review concerns are addressed in the current source.
CI: GitHub reports all 40 head-commit checks successful, including the aggregate dotnet-android check for Azure DevOps build 1681205. Direct Azure build/timeline verification was blocked because az devops invoke required authentication, so I could not independently inspect its build result or non-gating device-test results. This review used source inspection; I did not run local builds or device tests.
Generated by Android PR Reviewer for #13526 · copilot · gpt61 · 60.8 AIC · ⌖ 7.5 AIC · ⊞ 20.3K
Comment /review to run again
|
/review |
|
✅ Android PR Reviewer completed successfully! Warning Firewall blocked 1 domainThe following domain was blocked by the firewall during workflow execution:
To allow these domains, add them to the network:
allowed:
- defaults
- "169.254.169.254"See Network Configuration for more information.
|
There was a problem hiding this comment.
✅ LGTM — code assessment
0 errors · 0 warnings · 1 nonblocking suggestion. Reviewed the 13 changed files at 910114ecbc, including the full changed C# sources, runtime callers, alias resolution, project configuration, and existing review threads. No merge-blocking correctness issue found.
The generator preserves the sealed-Mono.Android restriction without runtime assembly reflection, and the nonsealed early return remains ahead of managed-proxy lookup. Eligibility is included in both fingerprints; scanner/emitter tests cover the metadata-to-constructor path, and the separate-class-loader test exercises the external-peer safeguard. The updated performance evidence explicitly distinguishes final bool-backed NativeAOT measurements from inconclusive CoreCLR timings. One inline suggestion would include the nonsealed cache regression in the documented focused device runs.
CI evidence: All 40 GitHub checks report success, including the aggregate dotnet-android check for Azure build 1681205. Direct Azure build/timeline verification was unavailable because the CLI encountered initialization/authentication errors; I could not independently confirm those details.
Local validation: Attempted the focused host tests for SealedFrameworkProxiesPassIsSealedToBase, ScannerRecordsIsSealedFromTypeMetadata, and ChangingFrameworkSealednessRegeneratesTypeMap. Execution was blocked by NETSDK1045: this checkout targets .NET 12, but the available SDK is 11.0.100. The initial --no-restore invocation did not discover/run tests and is not counted as a pass. No device tests or benchmarks were rerun during this review.
Warning
Firewall blocked 1 domain
The following domain was blocked by the firewall during workflow execution:
169.254.169.254
To allow these domains, add them to the network.allowed list in your workflow frontmatter:
network:
allowed:
- defaults
- "169.254.169.254"See Network Configuration for more information.
Generated by Android PR Reviewer for #13526 · copilot · gpt61 · 79.9 AIC · ⌖ 8.08 AIC · ⊞ 20.3K
Comment /review to run again
| } | ||
|
|
||
| [Test] | ||
| public void GetProxyForJavaObject_NonSealedTarget_DoesNotCacheManagedTarget () |
There was a problem hiding this comment.
🤖 💡 Testing — Consider adding [Category ("NativeAOTTrimmable")] to this regression, as on the neighboring lookup tests. The documented focused device commands use -p:IncludeCategories=NativeAOTTrimmable, so those NativeAOT/CoreCLR runs exclude the test that specifically proves nonsealed targets do not populate the managed-proxy cache. Including it would protect the restored early-return behavior in the same focused runs used to validate this optimization.
{Rule: Cover regressions in the relevant runtime test selection}

Fixes #13421.
Context: #12644.
The sealed-peer shortcut checks
Type.Assemblyon every lookup. NativeAOT resolves this through runtime metadata, making the check disproportionately expensive. Replace it with a bool-backedJavaPeerProxy.IsSealedproperty set by the generator only for sealed types defined inMono.Android. Keep the existing early return for nonsealed targets before looking up the managed proxy.The
Mono.Androidrestriction preserves the existing class-loader safeguard.FindClasscan resolve an app class using a loader different from the one that created the Java object; classes with the same name from different loaders have different identities. AnIsInstanceOfmismatch can therefore be inconclusive for external peers, which continue to use hierarchy lookup. Android normally uses separate framework and app loaders, and additional loaders can be created at runtime, so build inputs cannot generally establish which class identities will be involved in a lookup.CanResolveFromSealedTargetTypeis generator-model metadata, not a second runtime marker. It selects the emitted constructor argument and is included in both the incremental-build fingerprint and the deterministic MVID content fingerprint: changing a peer's eligibility changes the emitted assembly even when its type name is unchanged. This prevents a stale incremental output and gives different emitted content a different MVID.Cover generated constructors across framework/external, sealed/unsealed, alias, and generic shapes; incremental invalidation and deterministic MVIDs; and on-device sealed success/mismatch, nonsealed hierarchy lookup, external peers, and closed generics. A new on-device regression checks that nonsealed targets do not populate the managed-proxy cache; it has not yet been run.
Package-size comparison
Release
android-arm64MAUI sample-content app, signed APK sizes in bytes:The bool-backed property adds 4,096 bytes to the NativeAOT APK and does not change the CoreCLR APK size relative to the marker. These measurements establish package size only, not runtime correctness or performance. The NativeAOT sample also emitted a Syncfusion ILC warning that
SfButton.ChangeVisualState()will always throw becauseVisualStateManager.GetVisualStateGroupsis missing.Final bool-backed peer-lookup measurements
A fully trimmed Release
android-arm64instrumentation app ran on the Android 15 ARM64 emulator on Apple Silicon, comparing baselinea008bb3473bfa512f9f6ce5823ea2bf01d82981fwith final head910114ecbc463ace6f02434876221903d1d679cd. The same sealed framework and app-peer workloads used 4,096 retained JNI references, 20 warmup batches and 80 measured batches per process; GC and wrapper disposal were outside the timed regions. For each runtime, six processes ran inbefore, final, final, before, before, finalorder, interleaved with the other runtime. Each pooled median below covers 240 measured batches per case/variant. All 12 instrumentation runs passed.Java.Lang.StringJava.Lang.StringNativeAOT per-run medians do not overlap; CoreCLR ranges overlap, so the latter do not establish a speedup. No foreign build was detected in the load-gate pair or per-run snapshots; these snapshots do not establish continuous idle. These are indicative emulator microbenchmarks, not measurements of nonsealed lookups or whole-app performance.
The NativeAOT final APK's library hash matched the freshly linked output and the ILC response referenced the verified final runtime pack. The CoreCLR APKs contained
libcoreclr.so; their packaged runtime and typemap assemblies matched the corresponding publish outputs, and the final linked runtime contained the bool-backedIsSealedguard. Instrumentation checked dynamic-code support and the trimmable typemap value manager. The baseline CoreCLR packaging documentation workaround is described below.Earlier NativeAOT measurements (marker-class implementation)
A fully trimmed Release
android-arm64instrumentation app repeatedly creates managed peers usingJava.Lang.Object.GetObject<T>from retained JNI references, disposing the wrappers between batches. Android 15 ARM64 emulator on Apple Silicon; baselinea008bb3473bfa512f9f6ce5823ea2bf01d82981fversus the earlier marker-class implementation, same app source and build settings. Each case uses 20 warmup batches and 80 measured batches of 4,096 lookups per process. Six interleaved installs/runs (before, after, after, before, before, after), without profiling during timing: 240 measured batches per case/variant. GC and disposal are outside the timed regions.Java.Lang.StringPer-run medians do not overlap: framework 4,879–5,046 ns before versus 1,955–2,051 ns after; app peer 4,016–4,234 ns versus 2,401–2,531 ns. Separate 4 kHz
cpu-clocksimpleperf captures with native symbols showNativeFormatRuntimeNamedTypeInfo.get_Assemblyat 34.29% inclusive samples before and no sampled calls after. Both APKs contain the NativeAOT library, and instrumentation asserts that dynamic code is unsupported.Earlier CoreCLR measurements (marker-class implementation)
The same app and workload, rebuilt with
PublishAot=falseandAndroidRuntime=CoreCLR, ran twice with the same six-run interleaving above: six processes and 480 measured batches per case/variant in total. The APKs containlibcoreclr.so; instrumentation verifies dynamic-code support and the trimmable typemap value manager.Java.Lang.StringThe ranges overlap substantially, so these CoreCLR results do not establish a measurable speedup. The first before run was especially variable; the second round's pooled framework medians were 1,997 ns before and 1,935 ns after.
For this CoreCLR baseline,
make prepare CONFIGURATION=Releasepassed. A cleanIncludeAndroidJavadoc=True make leeroy CONFIGURATION=Releasefailed in Javadoc generation due to missing copyright metadata.IncludeAndroidJavadoc=False make leeroy CONFIGURATION=Releasebuilt the baseline binaries and extra API levels but failed packaging becauseMono.Android.xmlwas absent. Copying that documentation XML from the changed SDK and runningIncludeAndroidJavadoc=False ./bin/Release/dotnet/dotnet build -p:Configuration=Release -t:ConfigureLocalWorkload build-tools/create-packs/Microsoft.Android.Sdk.projcompleted packaging. Thus the baseline used its own runtime and generator binaries but differs in documentation-generation settings; the copied XML is packaging input, not benchmark code.These earlier measurements are peer-lookup microbenchmarks of the marker-class implementation, not measurements of the final bool-backed implementation, nonsealed lookups, PoolMath, MAUI scrolling, physical-device, or whole-app speedup claims.
Local validation of final head
22a9a3b150e40ebb0aed5b6d69af33b0f8269231The following serial Release commands used private caches, TMP, and CLI home; PublicAPI and API compatibility checks remained enabled. The first attempt failed because the private cache lacked the ApiCompat and GenAPI packages; after copying the exact already-cached versions into the private cache, the retry passed:
The new nonsealed regression was not run on-device; the approved host-only validation did not include a device or SDK refresh. The host checks do not experimentally validate nonsealed runtime performance.
Earlier validation (marker-class implementation)
make prepare CONFIGURATION=Release— passed.IncludeAndroidJavadoc=True make leeroy CONFIGURATION=Release— passed before and after, including extra API levels and local workload configuration. The initial invocation without documentation enabled failed because packaging requiredMono.Android.xml; enabling the existing documentation option resolved it without build-file changes.On-device commands: NativeAOT 20 passed; CoreCLR 20 passed
Both configurations built, installed, and passed all 20 selected tests on the ARM64 emulator with the earlier marker-class implementation. Existing SourceLink and trim/AOT-analysis warnings remain visible.