Skip to content

[Xamarin.Android.Build.Tasks] Move library tasks to MABT - #13615

Open
simonrozsival wants to merge 4 commits into
mainfrom
simonrozsival-modernize-three-msbuild-tasks-3a6
Open

simonrozsival wants to merge 4 commits into
mainfrom
simonrozsival-modernize-three-msbuild-tasks-3a6

Conversation

@simonrozsival

Copy link
Copy Markdown
Member

Xamarin.Android.Build.Tasks targets netstandard2.0, which prevents these tasks from using modern .NET APIs and participating in in-process multithreaded MSBuild execution. Move <ProcessAssemblies/>, <ResolveLibraryProjectImports/>, and <GenerateLibraryResources/> into Microsoft.Android.Build.Tasks while preserving task identity, hosting, and behavior.

The migrated tasks use TaskEnvironment-relative paths and task-specific file-write retry settings. Duplicate Java libraries and jars retain first-wins metadata, while GenerateLibraryResources continues to add a value only after SetValue succeeds. XABT consumers share the metadata contract without duplicating the moved tasks.

Validation

  • bin/Debug/dotnet/dotnet build src/Microsoft.Android.Build.Tasks/Microsoft.Android.Build.Tasks.csproj -c Debug --no-restore --nologo -v:minimal -p:EnableSourceLink=false -p:EnableSourceControlManagerQueries=false — passed, 0 warnings/errors.
  • ./dotnet-local.sh build src/Xamarin.Android.Build.Tasks/Xamarin.Android.Build.Tasks.csproj -c Debug --no-restore --nologo -v:minimal -p:EnableSourceLink=false -p:EnableSourceControlManagerQueries=false — passed, 0 warnings/errors.
  • bin/Debug/dotnet/dotnet test src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/Microsoft.Android.Build.Tasks.Tests.csproj -c Debug --no-restore --nologo -v:minimal -p:EnableSourceLink=false -p:EnableSourceControlManagerQueries=false --filter 'FullyQualifiedName~ProcessAssembliesTests|FullyQualifiedName~GenerateLibraryResourcesTests|FullyQualifiedName~ResolveLibraryProjectImportsTests|Name~HostCoverageCollectorArtifactsAreExcludedFromAndroidPublish|Name~InnerBuildReturnsExactProducerPaths' — passed 47/47, including strict -mt coverage.
  • git diff --check — passed.

make prepare CONFIGURATION=Debug completed. make leeroy CONFIGURATION=Debug was attempted, but the worktree had incomplete generated native/pack outputs (a zero-byte libruntime-base-release.a followed by a missing Mono.Android.xml), so the full SDK build did not complete.

Copilot AI balanced review requested due to automatic review settings November 18, 2026 12:50

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

Concurrent execution retains process-directory dependencies and shares a non-thread-safe TaskEnvironment across workers, risking incorrect path resolution that the existing tests cannot detect.

3 open issues
What changed in this PR

Moves three library-processing tasks from Xamarin.Android.Build.Tasks to Microsoft.Android.Build.Tasks, enabling modern .NET APIs and in-process multithreaded MSBuild execution.

Changes:

  • Migrates task implementations and registrations, with project-relative paths and task-specific file-write retry settings.
  • Shares assembly helpers and library-import metadata across both task assemblies.
  • Migrates and extends tests for path handling, duplicate metadata, and framework assembly recognition.
File Description
src/​Xamarin.Android.Build.Tasks/​Xamarin.Android.EmbeddedResource.targets Registers the migrated import-resolution task.
src/​Xamarin.Android.Build.Tasks/​Xamarin.Android.Common.targets Registers the migrated resource-generation task.
src/​Xamarin.Android.Build.Tasks/​Xamarin.Android.Build.Tasks.csproj Removes the relocated symbol writer compilation.
src/​Xamarin.Android.Build.Tasks/​Utilities/​MonoAndroidHelper.Linker.cs Reuses shared framework-name detection.
src/​Xamarin.Android.Build.Tasks/​Utilities/​MonoAndroidHelper.cs Removes relocated assembly helpers.
src/​Xamarin.Android.Build.Tasks/​Utilities/​LibraryProjectImportsMetadata.cs Defines shared import metadata and serialization.
src/​Xamarin.Android.Build.Tasks/​Utilities/​AssemblyIdentityMap.cs Adds project-relative map loading and saving.
src/​Xamarin.Android.Build.Tasks/​Tasks/​GetImportedLibraries.cs Uses the shared metadata contract.
src/​Xamarin.Android.Build.Tasks/​Tasks/​ConvertResourcesCases.cs Uses shared resource-processing metadata constants.
src/​Xamarin.Android.Build.Tasks/​Tasks/​CollectNonEmptyDirectories.cs Uses the shared skip-processing constant.
src/​Xamarin.Android.Build.Tasks/​Microsoft.Android.Sdk/​targets/​Microsoft.Android.Sdk.AssemblyResolution.targets Registers the migrated assembly-processing task.
src/​Microsoft.Android.Build.Tasks/​Utilities/​MonoAndroidHelper.Assemblies.cs Hosts shared assembly classification helpers.
src/​Microsoft.Android.Build.Tasks/​Tests/​Microsoft.Android.Build.Tasks.Tests/​TypeMapProguardTargetsTests.cs Supplies the new task assembly property.
src/​Microsoft.Android.Build.Tasks/​Tests/​Microsoft.Android.Build.Tasks.Tests/​Tasks/​ResolveLibraryProjectImportsTests.cs Tests first-wins metadata for duplicate jars.
src/​Microsoft.Android.Build.Tasks/​Tests/​Microsoft.Android.Build.Tasks.Tests/​Tasks/​ProcessAssembliesTests.cs Migrates execution tests and adds duplicate/name coverage.
src/​Microsoft.Android.Build.Tasks/​Tests/​Microsoft.Android.Build.Tasks.Tests/​Tasks/​GenerateLibraryResourcesTests.cs Adapts resource-generation tests to the new assembly.
src/​Microsoft.Android.Build.Tasks/​Tasks/​ResolveLibraryProjectImports.cs Migrates extraction to project-scoped task execution.
src/​Microsoft.Android.Build.Tasks/​Tasks/​ProcessAssemblies.cs Migrates assembly processing and simplifies deduplication.
src/​Microsoft.Android.Build.Tasks/​Tasks/​GenerateLibraryResources.cs Adds multithreaded-task support and project-relative paths.
src/​Microsoft.Android.Build.Tasks/​Microsoft.Android.Build.Tasks.csproj Links shared metadata and symbol-writer sources.
src/​Microsoft.Android.Build.BaseTasks/​Files.cs Adds extraction with task-specific retry settings.
src-ThirdParty/​android-platform-tools-base/​SymbolWriter.cs Uses the migrated namespace and task-aware file writes.

Review effort: Balanced

writer.Flush ();
var r_java = Path.Combine (output_directory, package.Name.Replace ('.', Path.DirectorySeparatorChar), "R.java");
if (Files.CopyIfStreamChanged (writer.BaseStream, r_java)) {
if (Files.CopyIfStreamChanged (writer.BaseStream, r_java, TaskEnvironment)) {
Comment on lines +18 to +19
[MSBuildMultiThreadableTask]
public partial class GenerateLibraryResources : AsyncTask, IMultiThreadableTask
{
public override string TaskPrefix => "GLR";

public TaskEnvironment TaskEnvironment { get; set; } = TaskEnvironment.Fallback;
simonrozsival and others added 4 commits November 21, 2026 08:03
Xamarin.Android.Build.Tasks targets netstandard2.0, which prevents these tasks from using modern .NET APIs and participating in in-process multithreaded MSBuild execution. Move <ProcessAssemblies/>, <ResolveLibraryProjectImports/>, and <GenerateLibraryResources/> into Microsoft.Android.Build.Tasks and preserve their task names, registration, and behavior.

The migrated tasks use TaskEnvironment-relative paths and task-specific file write retry settings. Duplicate Java libraries and jars retain first-wins metadata, while GenerateLibraryResources continues to add a value only after SetValue succeeds. Shared XABT metadata remains linked rather than duplicating the moved tasks.

Validation:
  * bin/Debug/dotnet/dotnet build src/Microsoft.Android.Build.Tasks/Microsoft.Android.Build.Tasks.csproj -c Debug --no-restore --nologo -v:minimal -p:EnableSourceLink=false -p:EnableSourceControlManagerQueries=false — passed, 0 warnings/errors.
  * ./dotnet-local.sh build src/Xamarin.Android.Build.Tasks/Xamarin.Android.Build.Tasks.csproj -c Debug --no-restore --nologo -v:minimal -p:EnableSourceLink=false -p:EnableSourceControlManagerQueries=false — passed, 0 warnings/errors.
  * bin/Debug/dotnet/dotnet test src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/Microsoft.Android.Build.Tasks.Tests.csproj -c Debug --no-restore --nologo -v:minimal -p:EnableSourceLink=false -p:EnableSourceControlManagerQueries=false --filter FullyQualifiedName~ProcessAssembliesTests|FullyQualifiedName~GenerateLibraryResourcesTests|FullyQualifiedName~ResolveLibraryProjectImportsTests|Name~HostCoverageCollectorArtifactsAreExcludedFromAndroidPublish|Name~InnerBuildReturnsExactProducerPaths — passed 47/47, including strict -mt coverage.
  * git diff --check — passed.

make prepare CONFIGURATION=Debug completed. make leeroy CONFIGURATION=Debug was attempted, but the worktree had incomplete generated native/pack outputs (a zero-byte libruntime-base-release.a followed by a missing Mono.Android.xml), so the full SDK build did not complete.

Co-authored-by: Copilot App <[email protected]>
GenerateLibraryResources implemented IMultiThreadableTask but still derived from AsyncTask, whose constructor captures the process working directory. The migration guard failed on Windows and macOS because that base is unsafe for in-process multithreaded MSBuild.

Extract the async execution and logging lifecycle into AsyncTaskBase, retain AsyncTask as the compatibility base which captures its working directory, and add MultithreadedAsyncTask with TaskEnvironment and IMultiThreadableTask. GenerateLibraryResources now derives from the multithreaded base while preserving Yield/Reacquire and queued logging.

Validation:
  * dotnet test tests/Microsoft.Android.Build.BaseTasks-Tests/Microsoft.Android.Build.BaseTasks-Tests.csproj -c Debug --no-restore -p:EnableSourceLink=false -p:EnableSourceControlManagerQueries=false — passed 167, skipped 4.
  * ./dotnet-local.sh test bin/TestDebug/net11.0/Xamarin.Android.Build.Tests.dll --filter FullyQualifiedName~MultiThreadedMigrationTests.MigratedTasksHaveDirectAttribute — passed 1/1.
  * Focused Microsoft.Android.Build.Tasks suite — passed 47/47, including strict -mt coverage.
  * MABT and XABT builds — 0 warnings/errors.
  * git diff --check — passed.

Co-authored-by: Copilot App <[email protected]>
Make the TaskEnvironment dependency explicit in MultithreadedAsyncTask exception logging instead of relying on overload selection to obtain it.

Validation: BaseTasks tests passed 167 with 4 skipped; git diff --check passed.

Co-authored-by: Copilot App <[email protected]>
@simonrozsival
simonrozsival force-pushed the simonrozsival-modernize-three-msbuild-tasks-3a6 branch from c64c1cc to adfdc33 Compare November 21, 2026 07:03
@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

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 #13615

@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

Reviewed all 25 changed files and the affected callers at adfdc336c2414b8a443cc8f3d26ea37595d1e883.

New findings: 0 ❌ errors, 0 ⚠️ warnings, 1 💡 suggestion, posted inline.

The existing TaskEnvironment concurrency concern remains applicable: WhenAll runs package generation concurrently, and those workers still share the task's TaskEnvironment through GenerateJava, LoadValues, and the file-write retry helper. I have not duplicated that inline finding. The earlier constructor/exception-context concern is addressed by the new MultithreadedAsyncTask base.

The task registrations and linked-source dependencies are consistently migrated, and the duplicate-library tests explicitly preserve first-wins metadata. The async base also retains queued logging and the Yield/Reacquire try/finally contract.

CI: All 38 GitHub checks report success, including the aggregate Azure dotnet-android check for build 1693459. The direct Azure build-result query required authentication, so its result/timeline could not be independently inspected. This was a source review; no local builds or tests were run.

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 #13615 · copilot · gpt61 · 72.5 AIC · ⌖ 4.23 AIC · ⊞ 21K
Comment /review to run again

public static Task WhenAll<TSource> (this AsyncTaskBase asyncTask, IEnumerable<TSource> source, Action<TSource> body) =>
asyncTask.WhenAll (source, body, maxConcurrencyLevel: DefaultMaxConcurrencyLevel);

public static Task WhenAll<TSource> (this AsyncTaskBase asyncTask, IEnumerable<TSource> source, Action<TSource> body, int maxConcurrencyLevel, TaskCreationOptions creationOptions = TaskCreationOptions.LongRunning)

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.

🤖 💡 Code organization — This copies the existing WhenAll(AsyncTask, ...) implementation below, and the new RunTask overloads similarly duplicate the legacy ones. Could the legacy overloads forward to these AsyncTaskBase overloads (by explicitly upcasting the receiver)? That preserves their public signatures while keeping scheduling, cancellation, and exception handling in one implementation for both task families.

Rule: Centralize duplicate algorithms; preserve existing API compatibility.

jonathanpeppers pushed a commit that referenced this pull request Nov 24, 2026
…3756)

Context: #13465
Context: #13480
Context: #13504
Context: #13512
Context: #13615

`.github/skills/code-review/references/msbuild-rules.md` (loaded by `.github/workflows/android-reviewer.md` during automated pull request reviews) still instructed reviewers to prefer `AndroidTask` and `AsyncTask` for MSBuild tasks. That contradicts `.github/copilot-instructions.md` and `Documentation/guides/MSBuildBestPractices.md` after `#13465` and `#13504`, where new and migrated tasks must use `MultithreadedAndroidTask` or `MultithreadedAndroidToolTask` and declare `[MSBuildMultiThreadableTask]` directly on each concrete class because `AndroidTask`, `AsyncTask`, and `AndroidToolTask` capture the process working directory in their constructors.

An audit of recent inline review comments surfaced four multithreaded-task review gaps in these rules:

  * Task base classes and path canonicalization: flag new tasks on `AndroidTask`, `AsyncTask`, or `AndroidToolTask`, and flag `[MSBuildMultiThreadableTask]` added to tasks still inheriting those bases (`#13615`), while allowing unmigrated legacy tasks to keep their base until all code paths are thread-safe. Document `TaskEnvironment.GetAbsolutePath(path).GetCanonicalForm()` for collapsing `.`/`..` segments rather than `Path.GetFullPath(TaskEnvironment.GetAbsolutePath(...))`, which fails `MSBuildTask0002` in this repository (`#13480`).
  * Background logging and `TaskEnvironment` thread safety: migrating an `AsyncTask` to `MultithreadedAndroidTask` switches `CreateTaskLogger()` from the queued `AsyncTask` overload to `MSBuildExtensions.CreateTaskLogger(this Task)`, which calls `task.Log.*` directly on background threads (`#13512`). Document keeping background logging marshaled to the executing thread, preserving `Yield()`/`Reacquire()` in `try`/`finally`, and resolving `TaskEnvironment` paths/settings before `Task.WhenAll` fan-out (`#13615`).
  * `RegisterTaskObject` cache keys under `-mt`: `RegisteredTaskObjectLifetime.Build` entries are shared across concurrent inner builds of the same project (such as different RIDs or TFMs), and `MultithreadedAndroidTask` omits `ProjectSpecificTaskObjectKey` (`#13480`). Require a configuration-specific discriminator such as the resolved absolute intermediate output directory, with matching key type, value, and lifetime across producer and consumer.

Validation: Markdown-only review skill update under `.github/skills/`; no SDK build or test execution required per `.github/skills/tests/SKILL.md`. Verified all referenced task types, methods, and analyzer settings against `src/Microsoft.Android.Build.BaseTasks/` and `.editorconfig`.

Co-authored-by: PureWeen <[email protected]>

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