Repository navigation
Conversation
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 37056Or
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 37056" |
|
Azure Pipelines: Successfully started running 1 pipeline(s). There may be pipelines that require an authorized user to comment /azp run to run. |
|
Hey there @@jpd21122012! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed. |
|
Hey there @jpd21122012! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed. |
There was a problem hiding this comment.
Pull request overview
This PR fixes an Android-specific edge case in Essentials permissions where off-main-thread calls to Permissions.RequestAsync<T>() could leave stale entries in the pending request dictionary, eventually causing request-code collisions and duplicate-key failures on later valid requests.
Changes:
- Move the Android main-thread validation in
BasePlatformPermission.DoRequestto occur before registering a pending request. - Add Android device tests to ensure background-thread failures don’t leak pending requests and don’t poison later calls.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
| src/Essentials/src/Permissions/Permissions.android.cs | Validates main-thread requirement before creating/adding pending request state to avoid stale entries. |
| src/Essentials/test/DeviceTests/Tests/Android/Permissions_Tests.cs | Adds regression coverage for background-thread request failures and verifies the pending request table stays clean. |
Enhance Device Test without loop spin ups
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.
Suppressed comments (1)
src/Essentials/src/Permissions/Permissions.android.cs:128
requests.Add(requestCode, tcs)occurs beforeGetCurrentActivity(true)/RequestPermissions. IfGetCurrentActivity(true)throws (e.g., no current Activity), the entry will remain in the staticrequestsdictionary indefinitely (and can later cause request-code collisions). Consider ensuring the dictionary entry is removed on any exception thrown before the permission request is successfully launched.
requestCode = PlatformUtils.NextRequestCode();
requests.Add(requestCode, tcs);
}
This comment has been minimized.
This comment has been minimized.
MauiBot
left a comment
There was a problem hiding this comment.
Expert Review — 3 findings
See inline comments for details.
| { | ||
| TaskCompletionSource<PermissionResult> tcs; | ||
|
|
||
| if (!MainThread.IsMainThread) |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[moderate] Logic and Correctness / Regression Prevention — Moving the main-thread guard here fixes the reported path, but the same stale-entry failure mode remains after registration. ActivityStateManager.Default.GetCurrentActivity(true) throws NullReferenceException ("The current Activity cannot be detected...", ActivityStateManager.android.cs:138) when no activity is attached, and ActivityCompat.RequestPermissions can throw as well — both after requests.Add(requestCode, tcs) on line 126. Concrete scenario: an app calls RequestAsync on the main looper while no activity is current (backgrounded/teardown, or before Init). Each failure leaks one entry; because PlatformUtils.NextRequestCode() cycles over only 999 codes (12000–12998), after ~999 such failures the next legitimate request hits requests.Add with a duplicate key and throws ArgumentException — exactly the poisoning this PR set out to eliminate, and exactly what the new RepeatedBackgroundThreadFailures_DoNotPoisonFutureRequests test proves is reachable. Suggest resolving the current activity before registration and making native dispatch failure-safe, removing this call's matching entry before rethrowing.
|
|
||
| Assert.Equal(initialPendingRequestCount, GetPendingRequestCount()); | ||
|
|
||
| var status = await MainThread.InvokeOnMainThreadAsync( |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[moderate] Regression Prevention and Test Coverage — This step does not verify what the test name claims. Permissions.NetworkState on Android declares ACCESS_NETWORK_STATE as non-runtime (Permissions.android.cs:412-425), and CHANGE_NETWORK_STATE (the only runtime entry) is not declared in Platforms/Android/AndroidManifest.xml. So BasePlatformPermission.RequestAsync returns Granted from the CheckStatusAsync() short-circuit at Permissions.android.cs:89 and never reaches DoRequest — the requests dictionary and NextRequestCode() are never touched. Both assertions on lines 49-50 therefore pass even if the table were fully poisoned; they are not discriminating. The real discriminators in this test are the pending-count assertion on line 44 and the fact that a duplicate request code makes requests.Add throw ArgumentException instead of PermissionException inside the loop. Recommend either dropping lines 46-50 (they add device-test time and false confidence) or replacing them with an assertion that actually re-enters DoRequest (e.g. driving the wrapped request code through Permissions.OnRequestPermissionsResult and asserting the pending entry is consumed).
| [Collection("AndroidPermissions")] | ||
| public class Android_Permissions_Tests | ||
| { | ||
| const int RequestCodeRange = 1000; |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[minor] Regression Prevention and Test Coverage — RequestCodeRange = 1000 is a magic value that is silently coupled to PlatformUtils.requestCodeStart (12000) and the >= 12999 wrap bound in PlatformUtils.NextRequestCode() — i.e. a 999-code cycle. It is chosen so the loop is guaranteed to wrap and reproduce the duplicate-key collision regardless of the starting offset. If that internal range is ever widened, this constant stops reproducing the collision scenario and the test quietly degrades to only checking dictionary growth. A short comment stating the dependency (or deriving the bound from the platform constants) would keep the regression intent intact.
MauiBot
left a comment
There was a problem hiding this comment.
Expert Review — 3 findings
See inline comments for details.
|
|
||
| requests.Add(requestCode, tcs); | ||
| currentRequestCode = PlatformUtils.NextRequestCode(); | ||
| requests.Add(currentRequestCode, tcs); |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[moderate] Logic and Correctness — requests.Add on a wrapped request code still throws ArgumentException, so the reported symptom is only partly closed. PlatformUtils.NextRequestCode() wraps (if (++requestCode >= 12999) requestCode = requestCodeStart;), and the stated root cause of #35861 is exactly "the wrapped code collides with a stale key". This PR removes one leak source (the off-main-thread throw), but the collision path stays reachable from a leak source it does not address: a request that legitimately registers here and never receives OnRequestPermissionsResult — e.g. the activity is destroyed/recreated (config change, process death, user backs out) while the system permission dialog is up. That entry stays in the dictionary forever, and ~12.9k requests later Add throws ArgumentException out of RequestAsync, not a PermissionException, so callers cannot handle it. Suggested hardening on this line: use requests[currentRequestCode] = tcs and complete/cancel any displaced TCS, or loop NextRequestCode() until an unused key is found. Without it the "poisoned later requests" failure mode can still recur through a different path.
| namespace Microsoft.Maui.Essentials.DeviceTests | ||
| { | ||
| [Category("Permissions")] | ||
| [Collection("AndroidPermissions")] |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[moderate] Regression Prevention and Test Coverage — [Collection("AndroidPermissions")] does not give this test the isolation its assertion requires. A collection that contains a single class only serializes that class against itself; xUnit still runs different collections in parallel, and this assembly has no CollectionBehavior(DisableTestParallelization = true). The assertion compares a delta of the process-global BasePlatformPermission.requests count, and other test classes in other collections drive real requests through the same dictionary: Microphone_Tests (MainThread.InvokeOnMainThreadAsync(Permissions.RequestAsync<Permissions.Microphone>)), Geolocation_Tests (RequestAsync<Permissions.LocationWhenInUse>), Contacts_Tests, and the shared Permissions_Tests. Each of those leaves an entry in requests for the whole time the OS dialog is pending. If one is in flight when GetPendingRequestCount() is sampled before/after, the delta is non-zero and this test fails spuriously — or, in the opposite interleaving, an added entry cancels out a leaked one and the test passes while the bug is present. Prefer asserting on the specific outcome of this call (e.g. capture the key set before and assert no new key was added) instead of a global Count delta, or add every permission-touching test class to the same collection.
| public class Android_Permissions_Tests | ||
| { | ||
| [Fact] | ||
| public async Task RequestAsync_FromBackgroundThread_ThrowsPermissionException() |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[moderate] Regression Prevention and Test Coverage — this is the only added test, and it covers just one of the three behaviors changed in DoRequest. Uncovered: (1) the reorder that resolves the activity before registering (var activity = ActivityStateManager.Default.GetCurrentActivity(true);, line 117) — when no current activity exists that call throws, which under the old ordering leaked an entry exactly like the off-main-thread path; a main-thread test with no current activity would discriminate the same way this one does; (2) the new catch block (lines 134-146) that removes the pending entry when ActivityCompat.RequestPermissions throws — reachable by overriding DoRequest/using a permission string the platform rejects, and today nothing proves the cleanup runs or that the original exception is rethrown unchanged; (3) no assertion that the happy path still completes after the reorder and the switch from the shared static requestCode to a per-call local — the existing Microphone_Tests only cover that incidentally and depend on device permission state. Adding at least (1) would materially raise confidence that all leak paths, not just the reported one, are closed.
This comment has been minimized.
This comment has been minimized.
MauiBot
left a comment
There was a problem hiding this comment.
Expert Review — 4 findings
See inline comments for details.
|
|
||
| requests.Add(requestCode, tcs); | ||
| currentRequestCode = PlatformUtils.NextRequestCode(); | ||
| requests.Add(currentRequestCode, tcs); |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[moderate] Logic and Correctness / Regression Prevention — requests.Add(...) still throws ArgumentException on a request-code collision, which is the exact user-visible crash this PR is trying to prevent.
PlatformUtils.NextRequestCode() increments and wraps at 12999 back to requestCodeStart, so any pending entry that is never resolved will eventually collide with a freshly issued code and poison an otherwise valid request. This PR removes one source of stale entries (the off-main-thread throw) and one more (GetCurrentActivity(true) throwing), but other paths still leak permanently: if the hosting Activity is destroyed while the system permission dialog is up, OnRequestPermissionsResult never fires for that request code and the TaskCompletionSource stays in the dictionary for the process lifetime. The next wrap-around then hits Add and throws.
Suggested hardening (one line, inside the existing lock) so the failure class is closed rather than narrowed:
currentRequestCode = PlatformUtils.NextRequestCode();
requests[currentRequestCode] = tcs; // overwrite an abandoned entry instead of throwingIf silently dropping an abandoned request is undesirable, prefer completing/cancelling the displaced TCS before overwriting rather than leaving Add to throw.
| throw new PermissionException("Permission request must be invoked on main thread."); | ||
|
|
||
| var activity = ActivityStateManager.Default.GetCurrentActivity(true); | ||
| var tcs = new TaskCompletionSource<PermissionResult>(); |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[minor] Async and Threading Safety — Consider new TaskCompletionSource<PermissionResult>(TaskCreationOptions.RunContinuationsAsynchronously).
This PR correctly moved TrySetResult outside the locker in OnRequestPermissionsResult (good — that removes the risk of user continuations executing while holding the static lock). However, the completion still runs the awaiting continuation inline on the thread that delivers Activity.OnRequestPermissionsResult, i.e. arbitrary app code after await Permissions.RequestAsync<T>() executes inside the Android permission-result callback. Opting into RunContinuationsAsynchronously makes the hand-off explicit and keeps the platform callback short. Non-blocking, but this is the natural place to do it since the allocation is already being touched.
| { | ||
| lock (locker) | ||
| { | ||
| if (requests.TryGetValue(currentRequestCode, out var pendingRequest) && |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[minor] Complexity Reduction — The TryGetValue + ReferenceEquals guard in the catch block is unreachable defensive code.
currentRequestCode is allocated under locker and is unique to this call; the only other code that mutates requests is OnRequestPermissionsResult, which cannot have run for this code before ActivityCompat.RequestPermissions returns (it throws before dispatching, and permissions is guaranteed non-empty by the !runtimePermissions.Any() early-return in RequestAsync). A plain requests.Remove(currentRequestCode); inside the lock is equivalent and easier to reason about. Not a defect — flagging only because the extra branch implies a race that does not exist and will read as meaningful to future maintainers.
| public class Android_Permissions_Tests | ||
| { | ||
| [Fact] | ||
| public async Task RequestAsync_FromBackgroundThread_ThrowsPermissionException() |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[moderate] Regression Prevention and Test Coverage — The new test covers only the positive (guard-trips) case; there is no discriminating test for the negative case.
RequestAsync_FromBackgroundThread_ThrowsPermissionException asserts (a) a PermissionException is thrown off the main thread and (b) the pending-request count is unchanged. Both assertions would still pass if DoRequest were accidentally changed to throw unconditionally — e.g. an inverted MainThread.IsMainThread condition, or a future refactor that moved the guard above a case it should not block. The test therefore cannot distinguish "the guard was moved before registration" (intended) from "permission requests are now broken for everyone" (catastrophic over-blocking).
Cheapest discriminating addition, no dialog or UI automation required: a main-thread test using a permission whose CheckStatusAsync returns Granted, asserting Permissions.RequestAsync<T>() returns Granted without throwing and without incrementing GetPendingRequestCount(). That proves the main-thread path is still reachable and that the tightened guard is not over-blocking, which is the risk this restructuring actually introduces.
MauiBot
left a comment
There was a problem hiding this comment.
AI Review Summary
@jpd21122012 — new AI review results are available based on this last commit:
a09bd60.
🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix
Gate Result: ✅ PASSED
Platform: ANDROID · Base: main · Merge base: f27ca83a
| Test | Without Fix (expect FAIL) | With Fix (expect PASS) |
|---|---|---|
📱 Android_Permissions_Tests (RequestAsync_FromBackgroundThread_ThrowsPermissionException) Category=Permissions |
✅ FAIL — 362s | ✅ PASS — 362s |
🔴 Without fix — 📱 Android_Permissions_Tests (RequestAsync_FromBackgroundThread_ThrowsPermissionException): FAIL ✅ · 362s
(no coded error found; showing last 1200 chars)
:26:21.362 16989 17027 I DOTNET : === TEST EXECUTION SUMMARY ===
08-08 00:26:21.362 16989 17027 I DOTNET : Tests run: 184 Passed: 0 Inconclusive: 0 Failed: 1 Ignored: 183 Skipped: 0
fail: Non-success instrumentation exit code: 1, expected: 0
info: <<XHARNESS_RESULT_START>>
{
"version": 1,
"machineName": "runnervmtroe5",
"exitCode": 1,
"exitCodeName": "TESTS_FAILED",
"platform": "android",
"instrumentationExitCode": 1,
"device": "emulator-5554",
"deviceOsVersion": "API 30",
"architecture": "x86_64",
"files": [
{
"name": "testResults-fa0a78ba7ac54305ada0f3c847d0ddd9.xml",
"type": "test-results"
},
{
"name": "adb-logcat-com.microsoft.maui.essentials.devicetests-default.log",
"type": "logcat"
}
]
}
<<XHARNESS_RESULT_END>>
info: Attempting to remove apk 'com.microsoft.maui.essentials.devicetests'..
info: Successfully uninstalled com.microsoft.maui.essentials.devicetests
XHarness exit code: 1 (TESTS_FAILED)
Passed: 0
Failed: 1
Skipped: 0
Total: 1
Tests completed with exit code: 1
🟢 With fix — 📱 Android_Permissions_Tests (RequestAsync_FromBackgroundThread_ThrowsPermissionException): PASS ✅ · 362s
(no coded error found; showing last 1200 chars)
8 17461 17496 I DOTNET : Xml file was written to the provided writer.
08-08 00:32:23.858 17461 17496 I DOTNET : === TEST EXECUTION SUMMARY ===
08-08 00:32:23.858 17461 17496 I DOTNET : Tests run: 184 Passed: 1 Inconclusive: 0 Failed: 0 Ignored: 183 Skipped: 0
info: <<XHARNESS_RESULT_START>>
{
"version": 1,
"machineName": "runnervmtroe5",
"exitCode": 0,
"exitCodeName": "SUCCESS",
"platform": "android",
"instrumentationExitCode": 0,
"device": "emulator-5554",
"deviceOsVersion": "API 30",
"architecture": "x86_64",
"files": [
{
"name": "testResults-db566308e04d4e9681a45995f160d0e7.xml",
"type": "test-results"
},
{
"name": "adb-logcat-com.microsoft.maui.essentials.devicetests-default.log",
"type": "logcat"
}
]
}
<<XHARNESS_RESULT_END>>
info: Attempting to remove apk 'com.microsoft.maui.essentials.devicetests'..
info: Successfully uninstalled com.microsoft.maui.essentials.devicetests
XHarness exit code: 0
Passed: 1
Failed: 0
Skipped: 0
Total: 1
Tests completed successfully
📁 Fix files reverted (1 files)
src/Essentials/src/Permissions/Permissions.android.cs
📋 Pre-Flight — Context & Validation
PR #37056 Pre-Flight
Context
- PR: Fix stale Android permission requests after off-main-thread failures
- Issue: #35861
- Platform: Android
- Base:
origin/mainatf27ca83a47 - Materialized PR commit:
0f01f0f571 - Gate: Passed previously; do not rerun baseline gate verification.
Permissions.RequestAsync<T>() can reach BasePlatformPermission.DoRequest from a background thread after status checking reports a denied runtime permission. On the base implementation, DoRequest allocates a request code and inserts a TaskCompletionSource into the static requests dictionary before checking MainThread.IsMainThread. The expected PermissionException therefore leaves a stale entry. Repeated invalid calls eventually wrap the request-code ring and poison later valid requests with a duplicate-key ArgumentException.
Existing PR Approach
The PR changes src/Essentials/src/Permissions/Permissions.android.cs to:
- Validate the main thread before obtaining the activity or registering pending state.
- Keep the request code local instead of in a shared static field.
- Remove the pending entry if
ActivityCompat.RequestPermissionsthrows. - Remove the dictionary entry under the lock, then complete its task outside the lock.
It adds src/Essentials/test/DeviceTests/Tests/Android/Permissions_Tests.cs, whose regression test invokes a denied runtime permission request via Task.Run and verifies, using reflection under the production lock, that the pending request count is unchanged.
Bounded Verification
Use only:
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Essentials -Platform android -TestFilter "Category=Permissions"The gate already demonstrated that RequestAsync_FromBackgroundThread_ThrowsPermissionException fails without the fix and passes with the PR fix. No additional mandatory regression test was specified, so no broader suite may be run.
Candidate Constraints
- Each candidate must use a different root-cause strategy from the PR and from earlier candidates.
- One implementation/test pass is allowed, plus at most one focused correction/retest.
- Preserve the PR's test file as the verifier; candidate source changes must be restored through
EstablishBrokenBaseline.ps1 -Restore. - Existing unrelated dirty workflow/script changes are out of scope and must not be modified or reverted.
🔬 Code Review — Deep Analysis
Expert Evaluation — Raw PR Fix
Verdict: LGTM (non-blocking hardening and coverage suggestions)
Confidence: High for the source fix; medium-high for test adequacy. Live GitHub review threads and required checks could not be retrieved because gh was unauthenticated, so those surfaces remain uncertain.
Independent assessment
The Android-only change correctly moves main-thread and current-activity validation ahead of pending-request registration. This prevents a thrown PermissionException or GetCurrentActivity(true) failure from leaving an entry that can never be removed. Localizing the request code also removes the prior race in which a shared static field could be overwritten between registration and dispatch. OnRequestPermissionsResult now performs one lookup and completes the task outside the dictionary lock; removing permissions.ToArray() is safe because the value is already a string[].
The new Android device test is correctly isolated from other permission tests and the trusted Gate proves it is discriminating for the reported leak: it fails without the source fix and passes with it.
Findings
- Moderate, non-blocking:
requests.Add(currentRequestCode, tcs)can still throw after the bounded request-code sequence wraps if any pending request was abandoned for another reason, such as activity destruction before a permission result. Replacing an abandoned entry would close the duplicate-key crash class rather than only removing known stale-entry producers. - Moderate, non-blocking: The regression test does not independently prove that a valid main-thread request remains reachable. A lightweight granted-permission case could cover that negative/over-blocking scenario.
- Minor: The catch-block
TryGetValue/ReferenceEqualsguard appears more defensive than necessary because this call uniquely owns the newly registered code until dispatch. - Minor:
TaskCompletionSource<PermissionResult>could useRunContinuationsAsynchronouslyto avoid running continuations inline in the Android result callback.
Blast radius and failure-mode assessment
The production change is confined to Permissions.android.cs, adds no public API, changes no startup path, and reduces rather than adds static state. Lock scope is narrower and no platform call or task completion occurs while holding the lock. The remaining concrete failure mode is an abandoned pending request surviving until the request-code ring wraps; this is pre-existing and not introduced by the PR.
Reconciliation
The implementation matches the stated off-main-thread stale-registration root cause. It additionally fixes stale state when current-activity lookup throws and removes a shared-request-code race, so the existing narrative understates rather than misrepresents the improvement. No blocking defect was found in the submitted fix.
Consolidated reviewer recommendation
For a single pr-plus-reviewer refinement, harden registration against an abandoned entry at request-code wraparound. Treat the extra valid-path test and the two minor findings as follow-up suggestions rather than merge blockers.
🛠️ Try-Fix — Analysis & Comparison
Alternative Fix Candidates for PR #37056
Candidate 1 — Scoped Request Lifetime
Model: claude-opus-5
Result: Pass on the first implementation/test pass; no correction round.
Detailed artifacts: CustomAgentLogsTmp/PRState/37056/PRAgent/try-fix/attempt-1/
Candidate narrative: CustomAgentLogsTmp/PRState/37056/PRAgent/try-fix-1/content.md
Approach
Treat pending-request cleanup as an ownership problem rather than a registration-order problem. Keep the broken baseline's registration ordering, but scope each dictionary entry to the awaiting DoRequest frame: wrap main-thread validation, activity acquisition, the Android request, and the await in try/finally; identity-check and remove the entry under the lock from finally. The Android callback only looks up and completes the task outside the lock. This covers every exceptional exit, including activity lookup failures not covered by the PR's narrower catch.
Diff
diff --git a/src/Essentials/src/Permissions/Permissions.android.cs b/src/Essentials/src/Permissions/Permissions.android.cs
index 618fb76ce2..68995e8f8b 100644
--- a/src/Essentials/src/Permissions/Permissions.android.cs
+++ b/src/Essentials/src/Permissions/Permissions.android.cs
@@ -64,7 +64,6 @@ namespace Microsoft.Maui.ApplicationModel
new Dictionary<int, TaskCompletionSource<PermissionResult>>();
static readonly object locker = new object();
- static int requestCode;
public virtual (string androidPermission, bool isRuntime)[] RequiredPermissions { get; }
@@ -112,24 +111,40 @@ namespace Microsoft.Maui.ApplicationModel
protected virtual async Task<PermissionResult> DoRequest(string[] permissions)
{
- TaskCompletionSource<PermissionResult> tcs;
+ var tcs = new TaskCompletionSource<PermissionResult>();
+ int currentRequestCode;
lock (locker)
{
- tcs = new TaskCompletionSource<PermissionResult>();
-
- requestCode = PlatformUtils.NextRequestCode();
+ currentRequestCode = PlatformUtils.NextRequestCode();
- requests.Add(requestCode, tcs);
+ requests.Add(currentRequestCode, tcs);
}
- if (!MainThread.IsMainThread)
- throw new PermissionException("Permission request must be invoked on main thread.");
+ // The pending entry's lifetime is scoped to this call. Every exit path - success,
+ // exception, or cancellation - unregisters it in the finally block, so no individual
+ // throw site needs its own cleanup and no stale entry can survive a failed request.
+ try
+ {
+ if (!MainThread.IsMainThread)
+ throw new PermissionException("Permission request must be invoked on main thread.");
- ActivityCompat.RequestPermissions(ActivityStateManager.Default.GetCurrentActivity(true), permissions.ToArray(), requestCode);
+ ActivityCompat.RequestPermissions(ActivityStateManager.Default.GetCurrentActivity(true), permissions.ToArray(), currentRequestCode);
- var result = await tcs.Task;
- return result;
+ var result = await tcs.Task;
+ return result;
+ }
+ finally
+ {
+ lock (locker)
+ {
+ if (requests.TryGetValue(currentRequestCode, out var pendingRequest) &&
+ ReferenceEquals(pendingRequest, tcs))
+ {
+ requests.Remove(currentRequestCode);
+ }
+ }
+ }
}
public override void EnsureDeclared()
@@ -194,15 +209,19 @@ namespace Microsoft.Maui.ApplicationModel
internal static void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
+ TaskCompletionSource<PermissionResult> tcs;
+
lock (locker)
{
- if (requests.ContainsKey(requestCode))
- {
- var result = new PermissionResult(permissions, grantResults);
- requests[requestCode].TrySetResult(result);
- requests.Remove(requestCode);
- }
+ if (!requests.TryGetValue(requestCode, out tcs))
+ return;
}
+
+ // Removal is owned by the awaiting DoRequest frame's finally block, so this callback
+ // only completes the task - and does so outside the lock to avoid running
+ // continuations while holding it.
+ var result = new PermissionResult(permissions, grantResults);
+ tcs.TrySetResult(result);
}
}Test Results
Command:
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Essentials -Platform android -TestFilter "Category=Permissions"XHarness exited 0 on emulator-5554 (API 30). The regression test passed; summary reported 306 tests discovered, 276 passed, 0 failed, and 30 ignored.
Analysis and Self-Review
The finally makes cleanup independent of which pre-callback operation throws, so the tested off-main-thread failure leaves the pending count unchanged. Inline expert self-review recorded one minor finding: successful entries remain present until the await continuation runs, creating a theoretical request-code-wrap collision window. No critical or major findings were recorded.
Candidate 2 — Task-Completion-Driven Registry Eviction
Model: gpt-5.6-sol
Result: Pass on the first implementation/test pass; no correction round.
Detailed artifacts: CustomAgentLogsTmp/PRState/37056/PRAgent/try-fix/attempt-2/
Candidate narrative: CustomAgentLogsTmp/PRState/37056/PRAgent/try-fix-2/content.md
Approach
Treat each pending task's terminal state as the request-lifetime boundary. Register an ExecuteSynchronously continuation that identity-checks and removes the task's dictionary entry whenever it succeeds, faults, or is canceled. Convert failures before the Android callback, including the off-main-thread contract violation, into task faults so eviction occurs before the exception reaches the caller. This differs from the PR's pre-registration validation and per-launch cleanup and from Candidate 1's awaiting-frame try/finally ownership.
Diff
diff --git a/src/Essentials/src/Permissions/Permissions.android.cs b/src/Essentials/src/Permissions/Permissions.android.cs
index 618fb76ce2..ab7baccea0 100644
--- a/src/Essentials/src/Permissions/Permissions.android.cs
+++ b/src/Essentials/src/Permissions/Permissions.android.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
+using System.Threading;
using System.Threading.Tasks;
using Android;
using Android.App;
@@ -64,7 +65,6 @@ namespace Microsoft.Maui.ApplicationModel
new Dictionary<int, TaskCompletionSource<PermissionResult>>();
static readonly object locker = new object();
- static int requestCode;
public virtual (string androidPermission, bool isRuntime)[] RequiredPermissions { get; }
@@ -112,21 +112,42 @@ namespace Microsoft.Maui.ApplicationModel
protected virtual async Task<PermissionResult> DoRequest(string[] permissions)
{
- TaskCompletionSource<PermissionResult> tcs;
+ var tcs = new TaskCompletionSource<PermissionResult>();
+ int currentRequestCode;
lock (locker)
{
- tcs = new TaskCompletionSource<PermissionResult>();
-
- requestCode = PlatformUtils.NextRequestCode();
-
- requests.Add(requestCode, tcs);
+ currentRequestCode = PlatformUtils.NextRequestCode();
+ requests.Add(currentRequestCode, tcs);
}
- if (!MainThread.IsMainThread)
- throw new PermissionException("Permission request must be invoked on main thread.");
+ _ = tcs.Task.ContinueWith(
+ _ =>
+ {
+ lock (locker)
+ {
+ if (requests.TryGetValue(currentRequestCode, out var pendingRequest) &&
+ ReferenceEquals(pendingRequest, tcs))
+ {
+ requests.Remove(currentRequestCode);
+ }
+ }
+ },
+ CancellationToken.None,
+ TaskContinuationOptions.ExecuteSynchronously,
+ TaskScheduler.Default);
+
+ try
+ {
+ if (!MainThread.IsMainThread)
+ throw new PermissionException("Permission request must be invoked on main thread.");
- ActivityCompat.RequestPermissions(ActivityStateManager.Default.GetCurrentActivity(true), permissions.ToArray(), requestCode);
+ ActivityCompat.RequestPermissions(ActivityStateManager.Default.GetCurrentActivity(true), permissions.ToArray(), currentRequestCode);
+ }
+ catch (Exception ex)
+ {
+ tcs.TrySetException(ex);
+ }
var result = await tcs.Task;
return result;Test Results
Command:
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Essentials -Platform android -TestFilter "Category=Permissions"XHarness exited 0 on emulator-5554. The regression test passed; summary reported 306 tests discovered, 276 passed, 0 failed, and 30 ignored.
Analysis and Self-Review
Synchronous terminal-state cleanup evicts the identity-matched request before a fault is observed, so the tested background-thread exception leaves no stale entry. Inline expert self-review was clean with zero findings.
📝 PR Finalize — Recommended Title & Description
Assessment: ✏️ Recommend updating — the current metadata accurately explains the reported failure but the title lacks the required platform/component form and the description omits several material parts of the winning implementation.
Recommended title
[Android] Permissions: Prevent stale requests after off-main-thread failures
Recommended description
## Description
Fixes #35861.
When `Permissions.RequestAsync<T>()` is invoked from a background thread on Android, the request was being registered in the pending request table before validating that the call was running on the main thread.
If the main-thread validation failed, a `PermissionException` was thrown, but the pending request remained in the static request table because no Android permission request was ever launched and `OnRequestPermissionsResult` was never invoked.
After enough failures, the request-code sequence wrapped and collided with stale entries, causing subsequent valid permission requests to fail with:
System.ArgumentException:
An item with the same key has already been added.
This change prevents stale pending state by:
- validating the main thread and obtaining the current activity before registering the request;
- keeping each request code local instead of sharing a mutable static request-code field;
- removing the pending entry if `ActivityCompat.RequestPermissions` throws; and
- removing completed entries under the lock before completing their tasks outside the lock.
This preserves the existing behavior for valid permission requests while ensuring failed pre-launch requests do not remain registered.
### Validation
- Reproduced the issue on current `main` (.NET MAUI 10.0.90).
- Verified that repeated background-thread calls still throw the expected `PermissionException`.
- Verified that a subsequent valid main-thread permission request correctly displays the Android permission dialog instead of failing with a duplicate-key exception.
- Added Android device tests covering the regression.
🏁 Report — Final Recommendation
✅ Final Recommendation: APPROVE
Winner: pr
The submitted PR is the most focused correct fix. The trusted Gate proves the regression test fails without the fix and passes with it, and the expert review found no blocking error or discussion item. All three alternatives also passed their recorded targeted regression runs, so no candidate was demoted for a test failure; the ranking is based on correctness, scope, and residual risk.
Comparative ranking
| Rank | Candidate | Targeted validation | Assessment |
|---|---|---|---|
| 1 | pr |
Gate ✅ PASS | Prevents invalid off-main-thread calls and activity lookup failures from registering state, cleans up launch failures, localizes the request code, and completes callbacks outside the lock. It fixes the demonstrated root cause with the smallest state machine and no new failure mode. |
| 2 | try-fix-1 |
✅ PASS — 276 passed, 0 failed | try/finally gives one cleanup owner for synchronous failures and successful callbacks, but it registers invalid calls unnecessarily and moves callback removal to an await continuation. Its claim to cover every abandoned request is too broad: if Android never returns a result, the task never completes and the finally never runs. |
| 3 | try-fix-2 |
✅ PASS — 276 passed, 0 failed | Terminal-task cleanup is coherent and promptly removes completed entries, but it adds a continuation and converts pre-launch synchronous failures into task faults through a broad catch. Like Candidate 1, it cannot evict a request whose Android callback never arrives because that task never becomes terminal. |
| 4 | pr-plus-reviewer |
✅ PASS — 276 passed, 0 failed | Replacing Add with the dictionary indexer avoids a duplicate-key exception, but cannot distinguish an abandoned entry from a live request. On a live collision it silently orphans the old task; an old Android result can then complete and remove the new request, cross-routing permission results. The passing regression test does not exercise this collision path. |
Why pr wins
The raw PR validates all operations that can fail before registration, then gives each registered request an explicit launch-failure cleanup path and callback removal path. This preserves the useful invariant that duplicate request codes fail loudly rather than silently replacing potentially live work. Its Android-only implementation has no public API impact and the added device test directly proves that off-main-thread failures no longer grow the static pending-request table.
The expert's additional valid-path test and continuation-scheduling suggestions are non-blocking follow-ups. The proposed collision overwrite is not safe enough to include, so pr-plus-reviewer does not improve on the submitted fix.
Evidence and uncertainty
- Raw PR Gate: ✅ tests fail without the fix and pass with it.
try-fix-1: ✅ first run passed.try-fix-2: ✅ first run passed.pr-plus-reviewer: ✅ the single required Android Permissions run passed (276passed,0failed).- Live GitHub review threads and required-check state were unavailable to the expert because
ghwas unauthenticated. This report relies on the trusted Gate and materialized PR/candidate artifacts supplied by the pipeline.
📱 UI Tests — Button,Label,Layout
Detected UI test categories: Button,Label,Layout
✅ Deep UI tests — 366 passed, 0 failed, 7 skipped across 3 categories on platform-pool agent (replaces in-process counts above).
🧪 UI Test Execution Results (deep, platform pool)
| Category | Tests | Snapshot diffs |
|---|---|---|
Button |
71/73 (2 skipped) ✓ | — |
Label |
96/98 (2 skipped) ✓ | — |
Layout |
199/202 (3 skipped) ✓ | — |
📎 Download drop-deep-uitests artifact (TRX + snapshot diffs) |
🧭 Next Steps — review latest findings
No alternative fix was selected for this run. Review the session findings and CI results before merging.
This comment has been minimized.
This comment has been minimized.
…37056) ## Description Fixes #35861. When `Permissions.RequestAsync<T>()` is invoked from a background thread on Android, the request was being registered in the pending request table before validating that the call was running on the main thread. If the main-thread validation failed, a `PermissionException` was thrown, but the pending request remained in the static request table because no Android permission request was ever launched and `OnRequestPermissionsResult` was never invoked. After enough failures, the request-code sequence wrapped and collided with stale entries, causing subsequent valid permission requests to fail with: System.ArgumentException: An item with the same key has already been added. This change validates the main thread before creating the pending request state, preventing stale entries from ever being created while preserving the existing behavior for valid permission requests. ### Validation - Reproduced the issue on current `main` (.NET MAUI 10.0.90). - Verified that repeated background-thread calls still throw the expected `PermissionException`. - Verified that a subsequent valid main-thread permission request correctly displays the Android permission dialog instead of failing with a duplicate-key exception. - Added Android device tests covering the regression.
…37056) ## Description Fixes #35861. When `Permissions.RequestAsync<T>()` is invoked from a background thread on Android, the request was being registered in the pending request table before validating that the call was running on the main thread. If the main-thread validation failed, a `PermissionException` was thrown, but the pending request remained in the static request table because no Android permission request was ever launched and `OnRequestPermissionsResult` was never invoked. After enough failures, the request-code sequence wrapped and collided with stale entries, causing subsequent valid permission requests to fail with: System.ArgumentException: An item with the same key has already been added. This change validates the main thread before creating the pending request state, preventing stale entries from ever being created while preserving the existing behavior for valid permission requests. ### Validation - Reproduced the issue on current `main` (.NET MAUI 10.0.90). - Verified that repeated background-thread calls still throw the expected `PermissionException`. - Verified that a subsequent valid main-thread permission request correctly displays the Android permission dialog instead of failing with a duplicate-key exception. - Added Android device tests covering the regression.
…37056) ## Description Fixes #35861. When `Permissions.RequestAsync<T>()` is invoked from a background thread on Android, the request was being registered in the pending request table before validating that the call was running on the main thread. If the main-thread validation failed, a `PermissionException` was thrown, but the pending request remained in the static request table because no Android permission request was ever launched and `OnRequestPermissionsResult` was never invoked. After enough failures, the request-code sequence wrapped and collided with stale entries, causing subsequent valid permission requests to fail with: System.ArgumentException: An item with the same key has already been added. This change validates the main thread before creating the pending request state, preventing stale entries from ever being created while preserving the existing behavior for valid permission requests. ### Validation - Reproduced the issue on current `main` (.NET MAUI 10.0.90). - Verified that repeated background-thread calls still throw the expected `PermissionException`. - Verified that a subsequent valid main-thread permission request correctly displays the Android permission dialog instead of failing with a duplicate-key exception. - Added Android device tests covering the regression.
…37056) ## Description Fixes #35861. When `Permissions.RequestAsync<T>()` is invoked from a background thread on Android, the request was being registered in the pending request table before validating that the call was running on the main thread. If the main-thread validation failed, a `PermissionException` was thrown, but the pending request remained in the static request table because no Android permission request was ever launched and `OnRequestPermissionsResult` was never invoked. After enough failures, the request-code sequence wrapped and collided with stale entries, causing subsequent valid permission requests to fail with: System.ArgumentException: An item with the same key has already been added. This change validates the main thread before creating the pending request state, preventing stale entries from ever being created while preserving the existing behavior for valid permission requests. ### Validation - Reproduced the issue on current `main` (.NET MAUI 10.0.90). - Verified that repeated background-thread calls still throw the expected `PermissionException`. - Verified that a subsequent valid main-thread permission request correctly displays the Android permission dialog instead of failing with a duplicate-key exception. - Added Android device tests covering the regression.
…37056) ## Description Fixes #35861. When `Permissions.RequestAsync<T>()` is invoked from a background thread on Android, the request was being registered in the pending request table before validating that the call was running on the main thread. If the main-thread validation failed, a `PermissionException` was thrown, but the pending request remained in the static request table because no Android permission request was ever launched and `OnRequestPermissionsResult` was never invoked. After enough failures, the request-code sequence wrapped and collided with stale entries, causing subsequent valid permission requests to fail with: System.ArgumentException: An item with the same key has already been added. This change validates the main thread before creating the pending request state, preventing stale entries from ever being created while preserving the existing behavior for valid permission requests. ### Validation - Reproduced the issue on current `main` (.NET MAUI 10.0.90). - Verified that repeated background-thread calls still throw the expected `PermissionException`. - Verified that a subsequent valid main-thread permission request correctly displays the Android permission dialog instead of failing with a duplicate-key exception. - Added Android device tests covering the regression.
…37056) ## Description Fixes #35861. When `Permissions.RequestAsync<T>()` is invoked from a background thread on Android, the request was being registered in the pending request table before validating that the call was running on the main thread. If the main-thread validation failed, a `PermissionException` was thrown, but the pending request remained in the static request table because no Android permission request was ever launched and `OnRequestPermissionsResult` was never invoked. After enough failures, the request-code sequence wrapped and collided with stale entries, causing subsequent valid permission requests to fail with: System.ArgumentException: An item with the same key has already been added. This change validates the main thread before creating the pending request state, preventing stale entries from ever being created while preserving the existing behavior for valid permission requests. ### Validation - Reproduced the issue on current `main` (.NET MAUI 10.0.90). - Verified that repeated background-thread calls still throw the expected `PermissionException`. - Verified that a subsequent valid main-thread permission request correctly displays the Android permission dialog instead of failing with a duplicate-key exception. - Added Android device tests covering the regression.
…37056) ## Description Fixes #35861. When `Permissions.RequestAsync<T>()` is invoked from a background thread on Android, the request was being registered in the pending request table before validating that the call was running on the main thread. If the main-thread validation failed, a `PermissionException` was thrown, but the pending request remained in the static request table because no Android permission request was ever launched and `OnRequestPermissionsResult` was never invoked. After enough failures, the request-code sequence wrapped and collided with stale entries, causing subsequent valid permission requests to fail with: System.ArgumentException: An item with the same key has already been added. This change validates the main thread before creating the pending request state, preventing stale entries from ever being created while preserving the existing behavior for valid permission requests. ### Validation - Reproduced the issue on current `main` (.NET MAUI 10.0.90). - Verified that repeated background-thread calls still throw the expected `PermissionException`. - Verified that a subsequent valid main-thread permission request correctly displays the Android permission dialog instead of failing with a duplicate-key exception. - Added Android device tests covering the regression.
…37056) ## Description Fixes #35861. When `Permissions.RequestAsync<T>()` is invoked from a background thread on Android, the request was being registered in the pending request table before validating that the call was running on the main thread. If the main-thread validation failed, a `PermissionException` was thrown, but the pending request remained in the static request table because no Android permission request was ever launched and `OnRequestPermissionsResult` was never invoked. After enough failures, the request-code sequence wrapped and collided with stale entries, causing subsequent valid permission requests to fail with: System.ArgumentException: An item with the same key has already been added. This change validates the main thread before creating the pending request state, preventing stale entries from ever being created while preserving the existing behavior for valid permission requests. ### Validation - Reproduced the issue on current `main` (.NET MAUI 10.0.90). - Verified that repeated background-thread calls still throw the expected `PermissionException`. - Verified that a subsequent valid main-thread permission request correctly displays the Android permission dialog instead of failing with a duplicate-key exception. - Added Android device tests covering the regression.
…37056) ## Description Fixes #35861. When `Permissions.RequestAsync<T>()` is invoked from a background thread on Android, the request was being registered in the pending request table before validating that the call was running on the main thread. If the main-thread validation failed, a `PermissionException` was thrown, but the pending request remained in the static request table because no Android permission request was ever launched and `OnRequestPermissionsResult` was never invoked. After enough failures, the request-code sequence wrapped and collided with stale entries, causing subsequent valid permission requests to fail with: System.ArgumentException: An item with the same key has already been added. This change validates the main thread before creating the pending request state, preventing stale entries from ever being created while preserving the existing behavior for valid permission requests. ### Validation - Reproduced the issue on current `main` (.NET MAUI 10.0.90). - Verified that repeated background-thread calls still throw the expected `PermissionException`. - Verified that a subsequent valid main-thread permission request correctly displays the Android permission dialog instead of failing with a duplicate-key exception. - Added Android device tests covering the regression.
…37056) ## Description Fixes #35861. When `Permissions.RequestAsync<T>()` is invoked from a background thread on Android, the request was being registered in the pending request table before validating that the call was running on the main thread. If the main-thread validation failed, a `PermissionException` was thrown, but the pending request remained in the static request table because no Android permission request was ever launched and `OnRequestPermissionsResult` was never invoked. After enough failures, the request-code sequence wrapped and collided with stale entries, causing subsequent valid permission requests to fail with: System.ArgumentException: An item with the same key has already been added. This change validates the main thread before creating the pending request state, preventing stale entries from ever being created while preserving the existing behavior for valid permission requests. ### Validation - Reproduced the issue on current `main` (.NET MAUI 10.0.90). - Verified that repeated background-thread calls still throw the expected `PermissionException`. - Verified that a subsequent valid main-thread permission request correctly displays the Android permission dialog instead of failing with a duplicate-key exception. - Added Android device tests covering the regression.
…37056) ## Description Fixes #35861. When `Permissions.RequestAsync<T>()` is invoked from a background thread on Android, the request was being registered in the pending request table before validating that the call was running on the main thread. If the main-thread validation failed, a `PermissionException` was thrown, but the pending request remained in the static request table because no Android permission request was ever launched and `OnRequestPermissionsResult` was never invoked. After enough failures, the request-code sequence wrapped and collided with stale entries, causing subsequent valid permission requests to fail with: System.ArgumentException: An item with the same key has already been added. This change validates the main thread before creating the pending request state, preventing stale entries from ever being created while preserving the existing behavior for valid permission requests. ### Validation - Reproduced the issue on current `main` (.NET MAUI 10.0.90). - Verified that repeated background-thread calls still throw the expected `PermissionException`. - Verified that a subsequent valid main-thread permission request correctly displays the Android permission dialog instead of failing with a duplicate-key exception. - Added Android device tests covering the regression.
Note
Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!
Description
Fixes #35861.
When
Permissions.RequestAsync<T>()is invoked from a background thread on Android, the request was being registered in the pending request table before validating that the call was running on the main thread.If the main-thread validation failed, a
PermissionExceptionwas thrown, but the pending request remained in the static request table because no Android permission request was ever launched andOnRequestPermissionsResultwas never invoked.After enough failures, the request-code sequence wrapped and collided with stale entries, causing subsequent valid permission requests to fail with:
System.ArgumentException:
An item with the same key has already been added.
This change validates the main thread before creating the pending request state, preventing stale entries from ever being created while preserving the existing behavior for valid permission requests.
Validation
main(.NET MAUI 10.0.90).PermissionException.