Repository navigation
[Microsoft.Android.Build.Tasks] Enable multithreaded tasks - #13480
simonrozsival wants to merge 5 commits into
Conversation
Migrate 22 additional MABT tasks to engine-supplied task environments, including helper I/O, child tools, caches, and failure cleanup. Preserve the existing async logging and yield lifecycle through a multithreaded async base. Leave BuildAppBundle unmarked pending migration of its shared Java tool bases. Co-authored-by: Copilot App <[email protected]>
There was a problem hiding this comment.
🟡 Changes recommended
Active findings identify a shared cache-key collision across concurrent build configurations and lost path canonicalization that can delete Java inputs, misclassify framework assemblies, and drop remapping entries.
4 open issues
What changed in this PR
This PR extends in-process multithreaded MSBuild support across Android packaging, typemap, and native build tasks, while leaving BuildAppBundle deferred until its shared Java tool bases are converted.
Changes:
- Opts 22 additional concrete tasks into multithreaded execution and introduces a compatible async base.
- Routes filesystem and subprocess operations through
TaskEnvironment, preserves compression-cache entries, and defers legacy environment initialization. - Adds project-isolation and async lifecycle tests, plus migration guidance.
| File | Description |
|---|---|
| tests/Microsoft.Android.Build.BaseTasks-Tests/Utilites/MockBuildEngine.cs | Counts yield and reacquire calls. |
| tests/Microsoft.Android.Build.BaseTasks-Tests/AsyncTaskTests.cs | Tests async environment isolation and lifecycle handling. |
| src/Xamarin.Android.Tools.AndroidSdk/ProcessUtils.cs | Defers legacy PATHEXT initialization. |
| src/Microsoft.Android.Build.Tasks/Utilities/ZipArchiveEx.cs | Resolves archive I/O through the task environment. |
| src/Microsoft.Android.Build.Tasks/Utilities/RuntimePropertiesParser.cs | Resolves runtime configuration paths per project. |
| src/Microsoft.Android.Build.Tasks/Utilities/ReferenceAssemblyChecker.cs | Resolves assembly paths before inspection. |
| src/Microsoft.Android.Build.Tasks/Utilities/JniRemappingBinaryBlob.cs | Resolves remapping XML paths per project. |
| src/Microsoft.Android.Build.Tasks/Utilities/JniRemapping/R8Mapping.cs | Supports task-relative mapping files. |
| src/Microsoft.Android.Build.Tasks/Utilities/JniRemapping/NativeAotJniRetention.cs | Resolves native object input paths. |
| src/Microsoft.Android.Build.Tasks/Utilities/EnvironmentBuilder.cs | Reads project-relative environment files. |
| src/Microsoft.Android.Build.Tasks/Utilities/DlopenAssemblyStoreGenerator.cs | Resolves assembly-store wrapping inputs and outputs. |
| src/Microsoft.Android.Build.Tasks/Utilities/CoreClrBootstrapBuilder.cs | Resolves native library inspection paths. |
| src/Microsoft.Android.Build.Tasks/Utilities/BundleConfigSplitConfigsChecker.cs | Resolves bundle configuration paths. |
| src/Microsoft.Android.Build.Tasks/Utilities/AssemblyStoreGenerator.cs | Writes stores and manifests using project paths. |
| src/Microsoft.Android.Build.Tasks/Utilities/AssemblyStoreBuilder.cs | Propagates task context to assembly-store helpers. |
| src/Microsoft.Android.Build.Tasks/Utilities/AssemblyStoreAssemblyInfo.cs | Resolves assembly source paths. |
| src/Microsoft.Android.Build.Tasks/Utilities/AssemblyCompressor.cs | Uses task-relative compression inputs and outputs. |
| src/Microsoft.Android.Build.Tasks/Utilities/AndroidNdkTools.cs | Makes NDK discovery task-environment aware. |
| src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/ExtractTypeMapKeysFromNativeAotObjectTests.cs | Tests relative paths and failed-write cleanup. |
| src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/BuildArchiveTests.cs | Tests concurrent projects with relative archive paths. |
| src/Microsoft.Android.Build.Tasks/Tasks/WrapAssemblyStoresAsSharedLibraries.cs | Enables multithreading and passes task context. |
| src/Microsoft.Android.Build.Tasks/Tasks/ResolveAndroidNdk.cs | Enables multithreaded NDK resolution. |
| src/Microsoft.Android.Build.Tasks/Tasks/LinkNativeAotSharedLibrary.cs | Migrates async linking, subprocesses, and cleanup. |
| src/Microsoft.Android.Build.Tasks/Tasks/GetNativeAotRuntimeProviders.cs | Enables multithreading with task-relative manifest reads. |
| src/Microsoft.Android.Build.Tasks/Tasks/GenerateTypeMapProguardConfiguration.cs | Enables multithreading and resolves file I/O. |
| src/Microsoft.Android.Build.Tasks/Tasks/GenerateTypeMapMemberProguardConfiguration.cs | Marks the concrete derived task as multithreadable. |
| src/Microsoft.Android.Build.Tasks/Tasks/GenerateTrimmableTypeMap.cs | Adopts the multithreaded base and updates path handling. |
| src/Microsoft.Android.Build.Tasks/Tasks/GenerateR8JniRemapping.cs | Enables multithreading and project-relative remapping I/O. |
| src/Microsoft.Android.Build.Tasks/Tasks/GenerateNativeApplicationConfigSources.cs | Passes task context through configuration generation. |
| src/Microsoft.Android.Build.Tasks/Tasks/GenerateNativeAotDataObject.cs | Resolves data-object outputs, stamps, and cleanup. |
| src/Microsoft.Android.Build.Tasks/Tasks/GenerateNativeAotBootstrapSources.cs | Resolves generated sources and stale-provider cleanup. |
| src/Microsoft.Android.Build.Tasks/Tasks/GenerateMissingTypeMapStubs.cs | Enables multithreaded stub generation. |
| src/Microsoft.Android.Build.Tasks/Tasks/GenerateJniRemappingBinaryBlobs.cs | Resolves blob inputs, outputs, and stamps. |
| src/Microsoft.Android.Build.Tasks/Tasks/FixupAssetPackArchive.cs | Enables task-relative archive fixups. |
| src/Microsoft.Android.Build.Tasks/Tasks/ExtractTypeMapKeysFromNativeAotObject.cs | Migrates async extraction and LLVM subprocesses. |
| src/Microsoft.Android.Build.Tasks/Tasks/ExtractTypeMapKeysFromAssemblies.cs | Enables multithreading and resolves extraction I/O. |
| src/Microsoft.Android.Build.Tasks/Tasks/CreateJavaArchive.cs | Enables task-relative Java archive creation. |
| src/Microsoft.Android.Build.Tasks/Tasks/CreateAssemblyStore.cs | Enables multithreading and propagates task context. |
| src/Microsoft.Android.Build.Tasks/Tasks/CompressAssemblies.cs | Enables multithreaded assembly compression. |
| src/Microsoft.Android.Build.Tasks/Tasks/CollectCompressedAssemblyInfo.cs | Resolves assembly inputs and project cache keys. |
| src/Microsoft.Android.Build.Tasks/Tasks/CollectAssemblyFilesToCompress.cs | Reads cached compression data without unregistering it. |
| src/Microsoft.Android.Build.Tasks/Tasks/BuildArchive.cs | Enables multithreading with project-relative archive I/O. |
| src/Microsoft.Android.Build.BaseTasks/UnhandledExceptionLogger.cs | Passes async task context into exception logging. |
| src/Microsoft.Android.Build.BaseTasks/MultithreadedAsyncTask.cs | Adds the task-environment-aware async base. |
| src/Microsoft.Android.Build.BaseTasks/AsyncTask.cs | Allows working-directory selection without process capture. |
| Documentation/guides/MSBuildBestPractices.md | Documents async migration and the deferred bundle task. |
Review effort: Balanced
Canonicalize generated Java, assembly, and remapping paths before comparing them. Recognize the safe multithreaded async task base in the migration guard. Co-authored-by: Copilot App <[email protected]>
… configuration Include the canonical intermediate output directory in both compression registry keys. Cover interleaved RIDs and target frameworks on a shared engine and execute the production compression targets in ordinary and strict multithreaded builds. Co-authored-by: Copilot App <[email protected]>
Preserve both compression metadata and temporary-directory test catalog entries. Co-authored-by: Copilot App <[email protected]>
Keep nullable-enabled compression target tests buildable with warnings as errors by checking reflection type names before constructing XML attributes. Co-authored-by: Copilot App <[email protected]>
|
/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 — source review
0 errors · 0 warnings · 1 non-blocking suggestion. No additional blocking correctness issues found in the current diff. The configuration-specific compression registry key is wired through both production call sites, canonicalization is retained for path-identity comparisons, and the async base preserves the existing logging and Yield/Reacquire implementation. The added regressions address the previously reported configuration and path-alias problems. Keeping BuildAppBundle unmarked appropriately limits this migration's scope.
The inline suggestion concerns subprocess-isolation coverage; the new relative-path extraction test substitutes the LLVM execution methods.
CI and validation: All 40 GitHub checks report success, including the overall dotnet-android check for Azure build 1678732. Direct Azure build/timeline verification was unavailable because of CLI initialization/authentication errors, so that part of CI verification remains incomplete. I attempted the focused dotnet test src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/Microsoft.Android.Build.Tasks.Tests.csproj -v minimal run filtered to CompressionMetadataTests, BuildArchiveTests, ExtractTypeMapKeysFromNativeAotObjectTests, GenerateTrimmableTypeMapTests, and GenerateR8JniRemappingTests; the local .NET CLI failed during first-use initialization before any build or tests ran. No repository files were changed.
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 #13480 · copilot · gpt61 · 102.8 AIC · ⌖ 4.21 AIC · ⊞ 20.2K
Comment /review to run again
| var (task, errors) = fixture.CreateTask (); | ||
| var directory = Path.GetDirectoryName (fixture.ObjectFile) | ||
| ?? throw new InvalidOperationException ("Missing fixture directory."); | ||
| task.TaskEnvironment = TaskEnvironment.CreateWithProjectDirectoryAndEnvironment (directory, new Dictionary<string, string> ()); |
There was a problem hiding this comment.
🤖 💡 Testing — Consider adding a subprocess-isolation regression alongside this relative-path test. fixture.CreateTask() returns MetadataTask, which overrides both ReadObjectMetadataAsync() and ReadObjectRelocationsAsync(), so this test never exercises the newly migrated TaskEnvironment.GetProcessStartInfo() paths. A small fake LLVM tool that records its working directory and a project-specific environment value would let two concurrent project environments verify child-process isolation without requiring the NDK. The same coverage would be useful for LinkNativeAotSharedLibrary.
Rule: Test edge cases; review helpers in referenced assemblies.
| namespace Microsoft.Android.Build.Tasks | ||
| { | ||
| public abstract class MultithreadedAsyncTask : AsyncTask, IMultiThreadableTask |
There was a problem hiding this comment.
As I have been migrating, I have just stopped using AsyncTask completely. Did you find a case we actually NEED it?
The only benefit is the Yield()/Reacquire() call, might free up an MSBuild node during some async work. But I question if it works at all under -mt mode.
| /// Initializes the task. | ||
| /// </summary> | ||
| protected AsyncTask () | ||
| protected AsyncTask () : this (Directory.GetCurrentDirectory ()) |
There was a problem hiding this comment.
Won't Directory.GetCurrentDirectory () be wrong under -mt mode?
…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]>


Context: #13479
MSBuild can run a task in process with
-mtonly when its concrete type opts in and its filesystem, environment, subprocess and shared-state operations are safe across concurrent projects. Most Microsoft.Android.Build.Tasks tasks still relied on legacy bases that capture the process working directory, so they could not safely participate.Mark 22 additional concrete tasks and use
MultithreadedAndroidTaskorMultithreadedAsyncTask, resolving paths, environment variables and child processes against the engine-suppliedTaskEnvironment. The async base preserves the existing logging and Yield/Reacquire lifecycle. The changes also avoid unregistering shared compression-cache entries and defer process-global PATHEXT initialization away from the task-environment path.<BuildAppBundle/>remains unmarked pending conversion of its shared Java tool bases after #13479. That move also brings<ManifestMerger/>into MABT without converting it for MT.Validation
The commands used a session-local isolation wrapper
$I(heavy-slot.sh --toolchain, with private HOME, Gradle, NuGet and temporary directories), a direct-task harness$H, and an overlay-SDK runner$B.$COMMONsuppliedUseSharedCompilation=falseand the local Android SDK and JDK paths.bash "$I" dotnet build src/Microsoft.Android.Build.Tasks/Microsoft.Android.Build.Tasks.csproj --no-restore --nologo -v:quiet— passed.bash "$I" dotnet test src/Microsoft.Android.Build.Tasks/Tests/Microsoft.Android.Build.Tasks.Tests/Microsoft.Android.Build.Tasks.Tests.csproj --nologo -v:minimal— 867 passed, 13 skipped.bash "$I" dotnet test tests/Microsoft.Android.Build.BaseTasks-Tests/Microsoft.Android.Build.BaseTasks-Tests.csproj --nologo -v:minimal— 157 passed, 4 skipped.bash "$I" dotnet test tests/Xamarin.Android.Tools.AndroidSdk-Tests/Xamarin.Android.Tools.AndroidSdk-Tests.csproj -p:AndroidToolsDisableMultiTargeting=false -p:DotNetTargetFrameworkVersion=10.0 --filter 'FullyQualifiedName~ProcessUtilsTests' --nologo -v:minimal— 34 passed.bash "$I" dotnet build "$H/Probe.csproj" --nologo -v:quiet— passed.bash "$I" dotnet msbuild "$H/parallel.proj" -m -nr:false -p:ExpectedProcessId=0 -v:minimal -bl:"$H/ordinary.binlog"— passed.bash "$I" dotnet msbuild "$H/parallel.proj" -m -mt -nr:false -warnaserror:MSB4286,MSB4287,MSB4288 -v:diagnostic -bl:"$H/strict.binlog"— passed; the probes ran in the parent process.$B build -c Debug -nr:false $COMMON -bl:ordinary.binlog— passed, 0 warnings and 0 errors.$B build -c Debug -m -mt -nr:false -warnaserror:MSB4286,MSB4287,MSB4288 $COMMON -bl:strict.binlog— passed, 0 warnings and 0 errors.$B build -c Release -m -mt -nr:false -warnaserror:MSB4286,MSB4287,MSB4288 -p:PublishReadyToRun=false $COMMON -bl:strict-release.binlog— passed, 0 warnings and 0 errors.Binlog replay confirmed that the marked MABT tasks exercised by the sample ran in process; the deferred
<BuildAppBundle/>ran in a task host in Release. The sample used an existing local SDK with this branch's pack output overlaid, not a full SDK built from this branch. ReadyToRun was disabled because the preview Crossgen2 package was unavailable. A NativeAOT app and full NDK discovery were not validated; SDK-dependent typemap and NativeAOT integration tests remain among the skipped tests.