Skip to content

[tests] Add trimming regression tests for past bugs - #13658

Open
simonrozsival wants to merge 16 commits into
dev/simonrozsival/trimming-testsfrom
dev/simonrozsival/trimming-regression-tests
Open

simonrozsival wants to merge 16 commits into
dev/simonrozsival/trimming-testsfrom
dev/simonrozsival/trimming-regression-tests

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Context: #13618

Adds a TrimmingTests case for each trimming bug from the last three years that can still happen, found by scanning dotnet/android issues and PRs since November 2023. Each case starts with a comment linking the original issue or PR, and runs in all three configurations unless the bug is specific to one.

Area Cases
Activating Java-created objects is/as (#9399), casts (#13286), JavaAs<T> () (#9038), interfaces through trimmed superclasses (#11386), interface-element collections (#11770), user constructors called from Java (#11123), orphaned Java callable wrappers (#13650)
Callbacks from Java boolean/char returns (#11168, #11773), event Implementors (#10911)
Android components receivers and services referenced by name (#8940), [Application] with backup agent, manage-space activity and [MetaData] (#8914, #13175), manifest-only activities (#11037), layout-only custom views (#8954)
Java callable wrappers [Export]-only peers (#13205), @JavascriptInterface (#12542), component names in signatures (#13143), [Export (Throws)] (#12564), Unicode names (#12607)
Size auth modules (#12791), value-type dictionaries (#12793), GetObject<T> constructors (#10448)
Build layout bindings (#8807), TrimmerRootAssembly without RootMode (#10758), DefaultValueAttribute in partial mode (#9525)
Packages unused binding packages (#12045), library resource designers (#10852), compatibility listener methods (#13235)

Cases that fail today are ignored with a link to the open issue:

Not covered: #11769 (ZXing.Net.Mobile ships no net*-android assets), [Preserve] (#10449; it no longer compiles), #9008 (needs a library project), and bugs whose code was removed (#10950, #8797, #11084, #11804).

Validation

On an API 35 arm64 emulator with a locally built SDK (make leeroy), the top of this stack:

./dotnet-local.sh build tests/TrimmingTests/TrimmingTests.csproj
ADB_TARGET="-s emulator-5554" ./dotnet-local.sh test bin/TestDebug/TrimmingTests/net11.0/TrimmingTests.dll

99 tests: 88 passed and 11 skipped (ignored with links to open issues). Failure checks: turning off a fix (_DefaultValueAttributeSupport=false for #9525, UseTypeMapAttributesForJavaDictionaryValueTypeLookups=false and an extra [Removed] instantiation for #12793, treating Mono.Android as untrimmed in partial mode) makes the corresponding test fail; the ignored cases fail today for the reason in their issue.

Copilot AI balanced review requested due to automatic review settings November 19, 2026 13:28

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 regression tests bypass the failing collection-converter discovery path and incorrectly expect wrapper removal under partial trimming, leaving a coverage gap and an invalid test expectation.

3 open issues
What changed in this PR

Adds regression coverage to the .NET for Android trimming suite for historical activation, callback, component-preservation, and size regressions across CoreCLR full/partial trimming and NativeAOT.

Changes:

  • Adds isolated case apps with runtime checks and kept/removed type expectations.
  • Organizes coverage into fixtures for bindings, Java interop, Android components, build integration, and packages.
  • Links cases to their original reports and marks known failures with issue-specific ignores.
File Description
tests/​TrimmingTests/​Tests/​PackageTests.cs Runs package-related regression cases.
tests/​TrimmingTests/​Tests/​JavaPeerActivationTests.cs Extends Java-created peer activation coverage.
tests/​TrimmingTests/​Tests/​JavaCallableWrapperTests.cs Adds wrapper generation and retention tests.
tests/​TrimmingTests/​Tests/​FeatureSwitchTests.cs Tests partial-mode attribute support.
tests/​TrimmingTests/​Tests/​CallbackTests.cs Adds callback and event implementor tests.
tests/​TrimmingTests/​Tests/​BuildIntegrationTests.cs Tests layout bindings and assembly roots.
tests/​TrimmingTests/​Tests/​BindingTrimmingTests.cs Adds constructor and size-regression checks.
tests/​TrimmingTests/​Tests/​AndroidComponentTests.cs Runs manifest and layout preservation cases.
tests/​TrimmingTests/​Cases/​ValueTypeDictionaryInstantiations.cs Checks NativeAOT dictionary specialization trimming.
tests/​TrimmingTests/​Cases/​UnusedBindingPackage.cs Checks startup with an unused binding package.
tests/​TrimmingTests/​Cases/​UnicodeJavaNames.cs Tests Unicode Java names and activation.
tests/​TrimmingTests/​Cases/​TypeCheckOnJavaCreatedPeer.cs Tests type checks on Android-created peers.
tests/​TrimmingTests/​Cases/​TrimmerRootAssemblyWithoutRootMode/​TrimmerRootAssemblyWithoutRootMode.cs Exercises root items without metadata.
tests/​TrimmingTests/​Cases/​TrimmerRootAssemblyWithoutRootMode/​Case.targets Supplies a root item without RootMode.
tests/​TrimmingTests/​Cases/​OrphanedJavaCallableWrapper.cs Checks removal of orphaned Java wrappers.
tests/​TrimmingTests/​Cases/​NamedComponentInSignature.cs Checks component names in wrapper signatures.
tests/​TrimmingTests/​Cases/​ManifestOnlyActivity/​ManifestOnlyActivity.cs Launches a manifest-only activity.
tests/​TrimmingTests/​Cases/​ManifestOnlyActivity/​AndroidManifest.xml Declares the otherwise unreferenced activity.
tests/​TrimmingTests/​Cases/​ManifestComponentsByName.cs Activates a receiver and service by name.
tests/​TrimmingTests/​Cases/​LibraryResourceDesigner.cs Exercises resource access through SkiaSharp.
tests/​TrimmingTests/​Cases/​LayoutBindings/​Resources/​layout/​main.xml Supplies a layout-binding resource.
tests/​TrimmingTests/​Cases/​LayoutBindings/​LayoutBindings.cs Checks generated layout-binding access.
tests/​TrimmingTests/​Cases/​JavascriptInterfaceAnnotation.cs Verifies JavaScript bridge annotations.
tests/​TrimmingTests/​Cases/​JavaAsInterfaceOfTrimmedClass.cs Tests interface conversion after binding removal.
tests/​TrimmingTests/​Cases/​JavaActivatedUserConstructors.cs Exercises user constructors and posted callbacks.
tests/​TrimmingTests/​Cases/​InterfaceThroughTrimmedSuperclass.cs Tests interface activation through trimmed superclasses.
tests/​TrimmingTests/​Cases/​InterfaceElementCollections.cs Round-trips an interface-element collection.
tests/​TrimmingTests/​Cases/​ExportThrows/​proguard.cfg Preserves Java exception metadata.
tests/​TrimmingTests/​Cases/​ExportThrows/​ExportThrows.cs Checks exported throws declarations.
tests/​TrimmingTests/​Cases/​ExportThrows/​Case.targets Includes the exception-preservation configuration.
tests/​TrimmingTests/​Cases/​ExportOnlyPeer.cs Tests peers reachable only through exports.
tests/​TrimmingTests/​Cases/​EventImplementors.cs Checks selective event implementor retention.
tests/​TrimmingTests/​Cases/​DefaultValueAttributeInPartialMode.cs Tests serialization defaults under partial trimming.
tests/​TrimmingTests/​Cases/​CustomViewFromLayout/​Resources/​layout/​main.xml References a custom view only from XML.
tests/​TrimmingTests/​Cases/​CustomViewFromLayout/​CustomViewFromLayout.cs Checks layout-only custom view activation.
tests/​TrimmingTests/​Cases/​CustomApplication.cs Tests application metadata and associated components.
tests/​TrimmingTests/​Cases/​CompatibilityMethodListener.cs Exercises compatibility-method wrapper generation.
tests/​TrimmingTests/​Cases/​CastClassToBoundType.cs Tests casts to Android-created bound types.
tests/​TrimmingTests/​Cases/​BoundReturnTypeConstructors.cs Checks removal of unused bound constructors.
tests/​TrimmingTests/​Cases/​BooleanAndCharCallbacks.cs Exercises Java boolean and char callbacks.
tests/​TrimmingTests/​Cases/​AndroidMessageHandlerAuthModules.cs Checks unused authentication-module removal.

Review effort: Balanced

@simonrozsival
simonrozsival force-pushed the dev/simonrozsival/trimming-regression-tests branch 2 times, most recently from 2d6278f to af9f5c6 Compare November 19, 2026 16:15
@jonathanpeppers
jonathanpeppers force-pushed the dev/simonrozsival/trimming-regression-tests branch from af9f5c6 to 5faf887 Compare November 19, 2026 21:49
simonrozsival and others added 8 commits November 20, 2026 23:24
Context: #13618

Every NativeAOT app gets an IL3053 warning for Mono.Android. With `$(TrimmerSingleWarn)`=false it expands to IL3050 in `JavaConvert.GetJniHandleConverter ()`, for its call to the `[RequiresDynamicCode]` `TryMakeGenericCollectionTypeFactory ()`.

The call was guarded by `RuntimeFeature.UseTypeMapAttributesForJavaDictionaryValueTypeLookups || !RuntimeFeature.IsDynamicCodeSupported`. The Roslyn analyzer accepts that, but ILC only treats `IsDynamicCodeSupported` as a guard when it is tested on its own. The converter lookup moves into `GetGenericCollectionConverter ()`, which tests `IsDynamicCodeSupported` alone in its own `if`; behavior is unchanged.

`TryMakeGenericCollectionTypeFactory ()` becomes a static method with `[DynamicDependency]` on `FromJniHandle` of `JavaList<>`, `JavaCollection<>` and `JavaDictionary<,>`. ILLink sees the `typeof (X<>).MakeGenericType ()` calls today, so this doesn't change current output, but it keeps the reflected method alive if that code is restructured; without it `CreateDelegate ()` throws `ArgumentNullException`.

The remaining waivers on this path got justifications that match the code, as the audit in #13618 found several outdated ones:

  * `JNIEnv.GetArray ()` IL2067, `JavaConvert` IL2055/IL2067, and the `SafeJavaCollectionFactory` IL2071s now describe the actual flow: elements are activated by their generated `JavaPeerProxy`, and only closed generic peers are activated by reflection, whose constructor the generator keeps (the previous commit). The old IL2071 text claimed the wrappers never activate elements.
  * `SafeArrayFactory.MakeReferenceArrayType ()` drops an IL2055 suppression: `MakeArrayType ()` doesn't produce IL2055, and the build has no warning without it.

Co-authored-by: Copilot App <[email protected]>
Context: #13618

Every NativeAOT app gets an IL3053 warning for Mono.Android. With `$(TrimmerSingleWarn)`=false it expands to IL3050 in `JavaConvert.GetJniHandleConverter ()`, for its call to the `[RequiresDynamicCode]` `TryMakeGenericCollectionTypeFactory ()`.

The call was guarded by `RuntimeFeature.UseTypeMapAttributesForJavaDictionaryValueTypeLookups || !RuntimeFeature.IsDynamicCodeSupported`. The Roslyn analyzer accepts that, but ILC only treats `IsDynamicCodeSupported` as a guard when it is tested on its own. The converter lookup moves into `GetGenericCollectionConverter ()`, which tests `IsDynamicCodeSupported` alone in its own `if`; behavior is unchanged.

`TryMakeGenericCollectionTypeFactory ()` becomes a static method with `[DynamicDependency]` on `FromJniHandle` of `JavaList<>`, `JavaCollection<>` and `JavaDictionary<,>`. ILLink sees the `typeof (X<>).MakeGenericType ()` calls today, so this doesn't change current output, but it keeps the reflected method alive if that code is restructured; without it `CreateDelegate ()` throws `ArgumentNullException`.

The remaining waivers on this path got justifications that match the code, as the audit in #13618 found several outdated ones:

  * `JNIEnv.GetArray ()` IL2067, `JavaConvert` IL2055/IL2067, and the `SafeJavaCollectionFactory` IL2071s now describe the actual flow: elements are activated by their generated `JavaPeerProxy`, and only closed generic peers are activated by reflection, whose constructor the generator keeps (the previous commit). The old IL2071 text claimed the wrappers never activate elements.
  * `SafeArrayFactory.MakeReferenceArrayType ()` drops an IL2055 suppression: `MakeArrayType ()` doesn't produce IL2055, and the build has no warning without it.

Co-authored-by: Copilot App <[email protected]>
Context: #13618

Trimming bugs show up only at runtime in a trimmed app, and the existing device tests run inside one large test app, where any test can keep a type alive for another. TrimmingTests builds a purpose-built app for each scenario, launches it on a device, and checks both its result and what trimming kept.

### Cases

Each case is a single-file app (`dotnet build Case.cs`) in `tests/TrimmingTests/Cases/` with `#:property`/`#:package` directives; a case that needs Android resources, an `AndroidManifest.xml` or MSBuild items lives in `Cases/<Case>/` next to them (`Case.targets`). It logs `TRIMMING_TEST_RESULT: PASS` or `FAIL …` on startup. Cases are shielded from the repository's `Directory.Build.*` files and never root anything unless that is what they test.

A test calls `BuildAndRun ("Cases/<Case>.cs", configuration)` and then `AssertTrimmingExpectations (app)`:

  * Every configuration builds `SignAndroidPackage` in Release: CoreCLR with `$(TrimMode)`=full, NativeAOT, and CoreCLR with `$(TrimMode)`=partial, the CoreCLR Release default. `[TrimmingConfigurations]` runs a test in all three or in the ones it lists.
  * The build must have no warnings except the codes the test passes as `expectedWarnings`, with `$(TrimmerSingleWarn)`=false.
  * The app is installed and launched with `adb`; its result is matched by process ID in a logcat stream started before the launch, so tests in a fixture run in parallel on one device without clearing logcat.
  * Expectation attributes modelled on dotnet/runtime's `Mono.Linker.Tests.Cases.Expectations` (`[Kept]`, `[Removed]`, `[KeptMember]`, `[Kept|Removed][Type|Member]InAssembly`, `By = Tool.…`) are checked against ILLink's `linked/` assemblies or ILC's mstat file. They take only strings, so they keep nothing themselves. NativeAOT cases build with `JitNoInline=1` because the mstat omits inlined methods, and can check generic instantiations. In partial mode, assemblies ILLink doesn't trim must instead be kept whole.

`DotNetCLI` skips arguments that file-based apps reject (`/noconsolelogger`, `/flp1`, `-m`, `-nodeReuse`).

The first cases cover generic peer array activation (the bug fixed two commits ago), unused bindings being removed, a C# listener called from Java, Java exception and interface invoker activation, and boxed values. `UnusedBoxingBindings` is ignored for #13635: every app keeps `JavaConvert` and all the `Java.Lang` boxing bindings.

### CI

The MSBuild emulator stage gets a `Trimming+Emulator` job in the public pipeline and in `stage-msbuild-emulator-tests.yaml`, running the suite with two workers on one emulator.

Co-authored-by: Copilot App <[email protected]>
`am start -W` can return before the process exists, so `pidof` found nothing and the test reported a crash.

Co-authored-by: Copilot App <[email protected]>
The proxy of an open generic definition keeps its activation constructor with [DynamicDependency]. Check that this doesn't keep generic peers the app doesn't use, nor make NativeAOT compile instantiations the app doesn't use.

Co-authored-by: Copilot App <[email protected]>
Context: #13618

Adds a TrimmingTests case for each trimming bug from the last three years that can still happen, found by scanning dotnet/android issues and PRs since November 2023. Each case starts with a comment linking the original issue or PR, and runs in all three configurations unless the bug is specific to one.

| Area | Cases |
|---|---|
| Activating Java-created objects | `is`/`as` (#9399), casts (#13286), `JavaAs<T> ()` (#9038), interfaces through trimmed superclasses (#11386), interface-element collections (#11770), user constructors called from Java (#11123), orphaned Java callable wrappers (#13650) |
| Callbacks from Java | `boolean`/`char` returns (#11168, #11773), event Implementors (#10911) |
| Android components | receivers and services referenced by name (#8940), `[Application]` with backup agent, manage-space activity and `[MetaData]` (#8914, #13175), manifest-only activities (#11037), layout-only custom views (#8954) |
| Java callable wrappers | `[Export]`-only peers (#13205), `@JavascriptInterface` (#12542), component names in signatures (#13143), `[Export (Throws)]` (#12564), Unicode names (#12607) |
| Size | auth modules (#12791), value-type dictionaries (#12793), `GetObject<T>` constructors (#10448) |
| Build | layout bindings (#8807), `TrimmerRootAssembly` without `RootMode` (#10758), `DefaultValueAttribute` in partial mode (#9525) |
| Packages | unused binding packages (#12045), library resource designers (#10852), compatibility listener methods (#13235) |

Cases that fail today are ignored with a link to the open issue:

  * #13286: ILLink doesn't keep the type map entry of a `castclass` target (CoreCLR), nor of an `isinst` target in a copied assembly (partial mode).
  * #13649: `GetObject<T>` keeps every constructor of every bound return type again.
  * #13650: Java callable wrappers outlive their trimmed peers.

Not covered: #11769 (ZXing.Net.Mobile ships no `net*-android` assets), `[Preserve]` (#10449; it no longer compiles), #9008 (needs a library project), and bugs whose code was removed (#10950, #8797, #11084, #11804).

Co-authored-by: Copilot App <[email protected]>
…vation

  * DeviceTest.SetupTest () clears logcat before every test, which discarded the output of apps that tests running in parallel waited for. Skip it, and check (and restart) the device once per fixture.
  * Register each case's directory in TestOutputDirectories, so passing tests clean it up and failing ones attach its logs and binlogs.
  * JavaObjectActivation disposes its Integer wrapper before ArrayList.get (), so the case activates a new peer instead of returning the cached one.

Co-authored-by: Copilot App <[email protected]>
…ons, null checks

  * InterfaceElementCollections converts the inner lists of a JavaList<IList<ICharSequence>> from a runtime Type, so the case goes through JavaConvert's collection factories instead of a binding that constructs JavaList<ICharSequence> itself. It fails on NativeAOT when the factory rejects interface element types.
  * OrphanedJavaCallableWrapper runs only with full trimming and NativeAOT: partial trimming keeps the app assembly whole, so the peer stays activatable.
  * Replace null-forgiving operators in cases with explicit checks.

Co-authored-by: Copilot App <[email protected]>
@simonrozsival
simonrozsival force-pushed the dev/simonrozsival/trimming-regression-tests branch from 5faf887 to e6dab17 Compare November 21, 2026 07:02
simonrozsival and others added 3 commits November 21, 2026 22:50
On CI the test output directory is under $(BUILD_STAGINGDIRECTORY), outside the repository, so the case apps didn't see its NuGet.config and every restore failed with NU1102 for the 12.0.0 ILLink, ILCompiler and runtime packs. Copy NuGet.config into each case directory, as DotNetCLI.New () and XamarinProject.CopyNuGetConfig () do.

Co-authored-by: Copilot App <[email protected]>
…omments

  * TrimmerRootAssemblyWithoutRootMode runs only with NativeAOT: BuildTest.TrimmerRootAssemblyWithoutRootMode already covers CoreCLR Release builds.
  * TypeCheckOnJavaCreatedPeer and CastClassToBoundType also call a member of the object they check or cast, so say so.

Co-authored-by: Copilot App <[email protected]>
(cherry picked from commit 9d5d9a7dc4dd6ea1e9b38816476b81cbd3ead5f1)
…vert

ILLink tracks typeof (X<>).MakeGenericType () as X<>, so the
[DynamicallyAccessedMembers (PublicMethods)] parameter of
GetJniHandleConverterForType () already keeps FromJniHandle.
Explain why CoreCLR and PublishAot builds take different paths.

Co-authored-by: Copilot App <[email protected]>
simonrozsival and others added 4 commits November 23, 2026 13:44
Resolve FromJniHandle on each statically known open collection wrapper, then map its metadata definition onto the closed type. Remove the IL2067 suppression and the PublicMethods requirement without changing the existing dynamic-code guard or MakeGenericType IL2055 rationale.

Add a JavaConvert test category to run the existing conversion fixture independently.

Validation: Release make leeroy and Mono.Android build passed with no IL2067/IL3050 diagnostics from JavaConvert. Full-trim CoreCLR Release and NativeAOT Release app builds passed with TrimmerSingleWarn=false; runtime selection was confirmed from binlogs and APK contents. Device reruns were blocked by boot-time SIGSEGV in both installed emulator versions on an isolated AVD; emulator-5590 was untouched.

Co-authored-by: Copilot App <[email protected]>
…ing-tests

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

# Conflicts:
#	src/Mono.Android/Java.Interop/JavaConvert.cs
Convert untyped java.util.ArrayList, HashSet, and HashMap instances to IList<string>, ICollection<string>, and IDictionary<string, string> through JNIEnv.GetArray<T> (), which reaches JavaConvert with only a runtime Type. The app never names JavaList<T>, JavaCollection<T>, or JavaDictionary<K,V> or calls their FromJniHandle (), so only JavaConvert's open-definition mapping (#13656) can keep those methods under full trimming.

Co-authored-by: Copilot App <[email protected]>
…g-regression-tests

# Conflicts:
#	tests/TrimmingTests/Tests/JavaPeerActivationTests.cs

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.

2 participants