Skip to content

[Xamarin.Android.Build.Tasks] Remove remaining shared API-version state - #13201

Merged
simonrozsival merged 1 commit into
mainfrom
jonathanpeppers-api-version-state-isolation
Oct 20, 2026
Merged

simonrozsival merged 1 commit into
mainfrom
jonathanpeppers-api-version-state-isolation

Conversation

@jonathanpeppers

Copy link
Copy Markdown
Member

Xamarin.Android.Tasks.MonoAndroidHelper.SupportedVersions is a mutable process-wide value. One project can replace the API data that another task uses. Remove that value and RefreshSupportedVersions, and pass ReferenceAssemblyPaths to each consumer.

SDK discovery, Java validation, and legacy-tool cleanup are already merged in #13145, #13133, and #13161. This PR does not repeat those changes. It is the lower prerequisite for a separate nested-build optimization. SDK and Java resolution call counts are unchanged, including inner builds.

Cache read-only AndroidVersions data through IBuildEngine4 with RegisteredTaskObjectLifetime.Build. The key includes the task assembly identity and the absolute, original input directory list. The cache holds no task logger or mutable current-context pointer. Concurrent creation for an equal key is harmless; correctness does not depend on a cache shared across worker processes or assembly load contexts.

All API-data consumers use explicit inputs: platform JAR and tooling resolution, manifests, aapt2, D8/R8, signing, jar2xml, launch activity/instrumentation, library resources, and dependency calculation. ManifestDocument keeps its own version resolver, with a known-version default for standalone use. Aapt2Link and library-resource generation resolve API metadata on the calling thread before yielding.

The concurrency test runs 64 tasks against two different SDK/API datasets that map the same preview ID Z to API levels 127 and 128. It checks both JAR paths and API outputs. The aapt2 tests link two ABIs and require exactly one API lookup before Yield, with relative reference paths resolved from the task's captured working directory. Tests also check cache reuse, separate build engines, manifest resolver isolation, and library-resource metadata access before Yield.

Local validation

Used this worktree's built SDK, 12.0.100-alpha.1.26509.101, targeting Android on .NET 11. Used Visual Studio 18 Insiders for the native build and Microsoft OpenJDK 21.0.8 for the tests. No other session's SDK or installed Android workload was used.

Process-only settings:

$env:DOTNET_CLI_USE_MSBUILD_SERVER='0'
$env:MSBUILDDISABLENODEREUSE='1'
$env:DOTNET_CLI_TELEMETRY_OPTOUT='1'
$env:TEST_ANDROID_JDK_PATH='C:\Program Files\Android\openjdk\jdk-21.0.8'
Command Result
dotnet msbuild Microsoft.Android.slnx -t:Prepare -nodeReuse:false -v:minimal Passed.
.\dotnet-local.cmd build Microsoft.Android.slnx -nodeReuse:false -v:minimal Passed: 57 warnings, 0 errors.
.\dotnet-local.cmd build Microsoft.Android.slnx --no-restore -nodeReuse:false -v:minimal Passed after the final source changes: 30 warnings, 0 errors.
.\dotnet-local.cmd build Microsoft.Android.slnx -t:PackDotNet -nodeReuse:false -v:minimal Passed: 62 warnings, 0 errors.
.\dotnet-local.cmd build build-tools\create-packs\Microsoft.Android.Sdk.proj -t:ConfigureLocalWorkload -nodeReuse:false -v:minimal Passed: 0 warnings, 0 errors, after restoring the local templates as described below.

Build warnings are in unchanged generated Android bindings, metadata, public-API files, and the existing duplicate NullableAttributes.cs input. No warnings were introduced in the changed source.

The first real-app test run found missing local workload manifests (NETSDK1147). Local workload configuration then found a missing Microsoft.Android.Templates 37.99.0 package. Built it with .\dotnet-local.cmd pack src\Microsoft.Android.Templates\Microsoft.Android.Templates.csproj -c Debug -p:TemplatePackVersion=37.99.0 -p:IncludeSymbols=False -p:OutputPath=..\..\bin\Debug\lib\template-packs -v:minimal, restored android-deps using the local template/package sources plus NuGet.config, and completed ConfigureLocalWorkload. No source changes were needed for this setup.

Focused host command:

.\dotnet-local.cmd test bin\TestDebug\net10.0\Xamarin.Android.Build.Tests.dll --filter "FullyQualifiedName~ResolveSdksTaskTests|FullyQualifiedName~ValidateJavaVersionTests|FullyQualifiedName~GetDependenciesTest|FullyQualifiedName~GenerateLibraryResourcesTests|FullyQualifiedName~GetAndroidInstrumentationNameTests|FullyQualifiedName~CheckGoogleSdkRequirementsTests|FullyQualifiedName~D8Tests|FullyQualifiedName~R8Tests|FullyQualifiedName~Aapt2Tests|FullyQualifiedName~ManifestDocumentTest|FullyQualifiedName~ManifestTest|FullyQualifiedName~GeneratePackageManagerJavaTests"

Result: 230 passed, 17 skipped, 8 failed. All API-isolation, two-ABI aapt2, and library-resource thread checks passed. The skips are 5 unsupported NativeAOT Debug cases and 12 cases whose ABI test data needs updates.

The 8 failures were test-environment constraints: DebuggerAttribute cases share output directories across parallel runtimes, an empty release DebugType conflicts with source embedding (CS2044/CS2045), and one 297-character APK path fails in zipalign although the file exists. Retried all debugger cases and the long-path case with a short, isolated staging directory, one test worker, and source embedding disabled:

$env:BUILD_STAGINGDIRECTORY='D:\a885805ca'
$env:NUNIT_MSBUILD_ARGS='/p:EnableSourceLink=false /p:EmbedAllSources=false /p:EmbedUntrackedSources=false'
.\dotnet-local.cmd test bin\TestDebug\net10.0\Xamarin.Android.Build.Tests.dll --filter "FullyQualifiedName~ManifestTest.DebuggerAttribute|(FullyQualifiedName~ManifestTest.AllForegroundServiceTypes&Name~TypeCamera&Name~CoreCLR)" -- NUnit.NumberOfTestWorkers=1

Result: 16 passed, 5 skipped, 0 failed. All 8 failed host cases passed on this retry.

Real-app publish/binding command, without the manifest-retry settings:

.\dotnet-local.cmd test bin\TestDebug\net10.0\Xamarin.Android.Build.Tests.dll --filter "(FullyQualifiedName~XASdkTests.DotNetPublish&Name~android37.0)|FullyQualifiedName~BindingBuildTest.DotNetBuildBinding|FullyQualifiedName~BindingBuildTest.MergeAndroidManifest" -- NUnit.NumberOfTestWorkers=1

Result: 6 passed, 1 skipped, 1 failed. CoreCLR Debug/Release publish and CoreCLR/NativeAOT binding/manifest tests passed. NativeAOT Release publish completed and produced signed APK/AAB files, but its zero-warning assertion failed on the existing IL3053 AOT-analysis warning from Mono.Android.dll. NativeAOT Debug is unsupported and was skipped.

Retried the NativeAOT publish assertions with only that known warning excluded:

$env:NoWarn='IL3053'
.\dotnet-local.cmd test bin\TestDebug\net10.0\Xamarin.Android.Build.Tests.dll --filter "FullyQualifiedName~XASdkTests.DotNetPublish&Name~android37.0&Name~NativeAOT" -- NUnit.NumberOfTestWorkers=1

Result: 1 passed, 1 skipped, 0 failed, including the output-pack and signed APK/AAB checks. Build and failure binlogs were inspected with binlogtool. Device tests were not run: this change only changes host task state and input wiring.


Pull Request
title and
description
should follow the
commit-messages.md workflow documentation, and in particular should include:

  • Useful description of why the change is necessary.
  • Links to issues fixed
  • Unit tests

No issue is closed by this prerequisite PR.

The process-wide MonoAndroidHelper.SupportedVersions value lets one
project replace the API metadata used by another project.  Pass explicit
reference directories to consumers instead of relying on ResolveSdks to
set a current API context.

Cache read-only AndroidVersions by task assembly and absolute input
paths through IBuildEngine4 for the current build only.  Keep manifest
resolvers bound to their own API data.  Resolve Aapt2Link and library
resource metadata once on the calling thread before yielding.

Keep SDK and Java resolution calls unchanged.  Their earlier discovery,
Java validation, and legacy-tool cleanup is already merged.

Add concurrent preview API isolation coverage and check that both ABI
links share one metadata lookup before Yield.  Check library resource
metadata access before Yield, separate engine caches, relative paths,
and manifest resolver isolation.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 885805ca-6360-41ec-99e8-d789e1b522e2

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.

🔵 Needs a closer look

Cross-task cache lifetime, concurrency behavior, and widespread input wiring warrant final human verification.

No open issues 🎉

What changed in this PR

Removes remaining process-wide API-version state from Android build tasks, completing the isolation work begun by the SDK-discovery cleanup without changing SDK or Java resolution call counts.

Changes:

  • Caches API metadata by explicit reference paths for the build lifetime.
  • Passes metadata inputs through tasks and targets, resolving asynchronous consumers’ metadata before yielding.
  • Adds concurrency, cache-isolation, manifest-resolver, and multi-ABI coverage.
File Description
src/​Xamarin.Android.Build.Tasks/​Xamarin.Android.Tooling.targets Passes reference paths to platform-JAR resolution.
src/​Xamarin.Android.Build.Tasks/​Xamarin.Android.D8.targets Passes reference paths to D8/R8.
src/​Xamarin.Android.Build.Tasks/​Xamarin.Android.Common.targets Wires metadata inputs into shared tasks.
src/​Xamarin.Android.Build.Tasks/​Utilities/​MonoAndroidHelper.Nullable.cs Adds build-scoped API metadata caching.
src/​Xamarin.Android.Build.Tasks/​Utilities/​MonoAndroidHelper.cs Removes shared state; requires explicit metadata.
src/​Xamarin.Android.Build.Tasks/​Utilities/​ManifestDocument.cs Gives each manifest its own version resolver.
src/​Xamarin.Android.Build.Tasks/​Tests/​Xamarin.Android.Build.Tests/​Tasks/​ResolveSdksTaskTests.cs Tests concurrent isolation and cache reuse.
src/​Xamarin.Android.Build.Tasks/​Tests/​Xamarin.Android.Build.Tests/​Tasks/​GetDependenciesTests.cs Supplies explicit reference paths.
src/​Xamarin.Android.Build.Tasks/​Tests/​Xamarin.Android.Build.Tests/​Tasks/​GetAndroidInstrumentationNameTests.cs Replaces shared fixture state with task inputs.
src/​Xamarin.Android.Build.Tasks/​Tests/​Xamarin.Android.Build.Tests/​Tasks/​GeneratePackageManagerJavaTests.cs Removes unnecessary shared-state setup.
src/​Xamarin.Android.Build.Tasks/​Tests/​Xamarin.Android.Build.Tests/​Tasks/​GenerateLibraryResourcesTests.cs Checks metadata access before yielding.
src/​Xamarin.Android.Build.Tasks/​Tests/​Xamarin.Android.Build.Tests/​Tasks/​CheckGoogleSdkRequirementsTests.cs Supplies task-specific metadata paths.
src/​Xamarin.Android.Build.Tasks/​Tests/​Xamarin.Android.Build.Tests/​Tasks/​Aapt2Tests.cs Tests two-ABI linking with one pre-yield lookup.
src/​Xamarin.Android.Build.Tasks/​Tasks/​ResolveSdksTask.cs Initializes cached metadata instead of shared state.
src/​Xamarin.Android.Build.Tasks/​Tasks/​ResolveAndroidTooling.cs Resolves versions from explicit inputs.
src/​Xamarin.Android.Build.Tasks/​Tasks/​ReadAndroidManifest.cs Uses local metadata for manifest/platform lookup.
src/​Xamarin.Android.Build.Tasks/​Tasks/​ManifestMerger.cs Passes metadata to manifest processing.
src/​Xamarin.Android.Build.Tasks/​Tasks/​JarToXml.cs Uses explicit metadata for platform-JAR lookup.
src/​Xamarin.Android.Build.Tasks/​Tasks/​GetJavaPlatformJar.cs Uses one resolver for JAR and API outputs.
src/​Xamarin.Android.Build.Tasks/​Tasks/​GetAndroidInstrumentationName.cs Loads manifests with explicit metadata.
src/​Xamarin.Android.Build.Tasks/​Tasks/​GetAndroidActivityName.cs Loads manifests with explicit metadata.
src/​Xamarin.Android.Build.Tasks/​Tasks/​GenerateLibraryResources.cs Resolves metadata before asynchronous work.
src/​Xamarin.Android.Build.Tasks/​Tasks/​D8.cs Uses explicit metadata for minimum-API parsing.
src/​Xamarin.Android.Build.Tasks/​Tasks/​CheckGoogleSdkRequirements.cs Supplies a task-specific manifest resolver.
src/​Xamarin.Android.Build.Tasks/​Tasks/​CalculateProjectDependencies.cs Uses local metadata for dependency calculation.
src/​Xamarin.Android.Build.Tasks/​Tasks/​AndroidApkSigner.cs Uses local metadata for signing API bounds.
src/​Xamarin.Android.Build.Tasks/​Tasks/​Aapt2Link.cs Shares pre-yield metadata across ABI links.
src/​Xamarin.Android.Build.Tasks/​MSBuild/​Xamarin/​Android/​Xamarin.Android.Bindings.JarToXml.targets Wires binding-task metadata inputs.
src/​Xamarin.Android.Build.Tasks/​MSBuild/​Xamarin/​Android/​Xamarin.Android.Aapt2.targets Wires both linking calls’ metadata inputs.
src/​Xamarin.Android.Build.Tasks/​Microsoft.Android.Sdk/​targets/​Microsoft.Android.Sdk.Tooling.targets Wires tooling and SDK-check metadata inputs.
src/​Xamarin.Android.Build.Tasks/​Microsoft.Android.Sdk/​targets/​Microsoft.Android.Sdk.Application.targets Wires activity/instrumentation metadata inputs.
src/​Xamarin.Android.Build.Debugging.Tasks/​Xamarin.Android.Common.Debugging.targets Wires test-launch metadata inputs.

Review effort: Balanced

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

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13201

@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 — 0 errors, 0 warnings, 1 non-blocking suggestion.

The change consistently replaces process-wide API-version state with explicit, build-scoped metadata keyed by normalized inputs. All product task invocations are wired with @(_AndroidApiInfoDirectories), async tasks resolve metadata before yielding, and manifest consumers retain isolated resolvers. CI is green across all 42 checks. I left one inline suggestion to make the concurrency regression test deterministic.

Generated by Android PR Reviewer for #13201 · copilot · gpt56 · 390.3 AIC · ⌖ 11 AIC · ⊞ 26.4K
Comment /review to run again

Assert.AreEqual (128, secondManifest.VersionResolver.GetApiLevelFromId ("Z"));
Assert.IsNull (new ManifestDocument (null).VersionResolver.GetApiLevelFromId ("Z"));
var concurrentEngine = new MockBuildEngine (TextWriter.Synchronized (new StringWriter ()));
System.Threading.Tasks.Parallel.For (0, 64, i => {

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 — Parallel.For provides parallelism opportunities but does not guarantee that the two SDK contexts overlap while API metadata is being resolved. This regression can therefore pass with an implementation that temporarily restores shared mutable state if the relevant iterations happen to execute serially. Please coordinate workers from both contexts with a barrier around metadata resolution so the isolation race is exercised deterministically.

Rule: Deterministic concurrency tests

@simonrozsival
simonrozsival merged commit 266bfca into main Oct 20, 2026
42 checks passed
@simonrozsival
simonrozsival deleted the jonathanpeppers-api-version-state-isolation branch October 20, 2026 06:55
jonathanpeppers added a commit that referenced this pull request Oct 22, 2026
Depends on #13201. This is the second PR in the stack: `main` -> API-version state removal -> nested-build reuse. Its diff contains seven target/test files; the API-state changes belong to the lower PR.

RID-specific nested builds create new MSBuild project instances. Their reference-resolution dependencies run `ResolveSdks`, `ResolveAndroidTooling` and `ValidateJavaVersion` again, even when the outer build has already resolved and validated the same inputs. `SkipCompilerExecution` does not skip those dependencies.

Pass the resolved outputs through private properties at the assembly-resolution and trimmable-typemap MSBuild call sites. Reuse them only when the original project, configuration, target framework, API metadata, SDK inputs, tooling overrides and Java validation settings match. Compare escaped input values with ordinal equality, including paths with apostrophes, semicolons and equals signs. Keep the outer build's resolved NDK and escape its direct nested-property assignment.

Pass the common escaped values through the MSBuild task's `Properties` parameter, not `AdditionalProperties` item metadata, which can unescape and split semicolon-containing paths. Keep only the per-RID assignment in item metadata. Both `_ResolveAssemblies` and the NativeAOT R8 relink receive the common properties.

Skip only the three resolution/validation tasks, not their target bodies. RID-to-ABI conversion and the other per-inner-build work still run. Standalone resolution, changed inputs, design-time builds, missing-tooling mode, explicit NDK-resolution skipping and different referenced projects retain normal resolution/validation. The compression and NativeAOT R8 nested builds also receive the resolved values. No new public build property or initializer task is added. This PR does not claim a measured build-time improvement.

Co-authored-by: Copilot App <[email protected]>
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 19, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

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