Repository navigation
[Mono.Android] Cancel every pending post of an Action - #13312
simonrozsival wants to merge 18 commits into
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
Active findings identify cancellation failures across drawable forwarding and disposed aliases, quadratic cancellation costs, and unintended retention of owners and contexts.
5 open issues
Avoid quadratic cancellation scans for unrelated tokens · New Avoid retaining drawable owners through pending callbacks · New Preserve Java identity across disposed wrapper aliases · New Match drawable scheduling and cancellation forwarding paths · New Retire successfully canceled handler registrations · New
What changed in this PR
This PR addresses #13309 by tracking every pending registration of an Action, allowing repeated callbacks to be canceled across .NET for Android’s Handler, View, and drawable helpers.
Changes:
- Replaces single-runnable tracking with weak-reference lists and per-registration disposal cleanup.
- Adds scheduling-owner and drawable-context matching without eagerly disposing unscheduled callbacks.
- Adds 30 regression cases covering cancellation, ownership, collection, and posting/execution scaling. Reported validation passed on Debug/CoreCLR, Android 15 ARM64.
| File | Description |
|---|---|
| tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj | Includes the new callback tests. |
| tests/Mono.Android-Tests/Mono.Android-Tests/Android.OS/ActionCallbackTests.cs | Adds cancellation, lifetime, ownership, and scaling regressions. |
| src/Mono.Android/Java.Lang/Thread.cs | Tracks multiple registrations and cleans up individual runnables. |
| src/Mono.Android/Android.Views/View.cs | Uses owner-aware cancellation for View and drawable callbacks. |
| src/Mono.Android/Android.OS/Handler.cs | Removes matching registrations while retaining native token filtering. |
| src/Mono.Android/Android.Graphics.Drawables/ScaleDrawable.cs | Adds receiver and child context to callback tracking. |
| src/Mono.Android/Android.Graphics.Drawables/RotateDrawable.cs | Adds receiver and child context to callback tracking. |
| src/Mono.Android/Android.Graphics.Drawables/LayerDrawable.cs | Adds receiver and child context to callback tracking. |
| src/Mono.Android/Android.Graphics.Drawables/InsetDrawable.cs | Adds receiver and child context to callback tracking. |
| src/Mono.Android/Android.Graphics.Drawables/DrawableContainer.cs | Adds receiver and child context to callback tracking. |
| src/Mono.Android/Android.Graphics.Drawables/Drawable.cs | Uses owner-aware tracking for self-scheduled callbacks. |
| src/Mono.Android/Android.Graphics.Drawables/ClipDrawable.cs | Adds receiver and child context to callback tracking. |
Review effort: Balanced
Context: #13312 The runtime test fixture does not enable nullable annotations. Its optional Action? hook triggers CS8632, which CI promotes to an error in all package-test configurations. Initialize the hook to a no-op delegate instead, preserving the default behavior without changing the nullable context for the rest of the fixture. Validated the local test build with -warnaserror:CS8632 and all 40 ActionCallbacks device tests on API35 ARM64/CoreCLR. Co-authored-by: Copilot App <[email protected]>
Context: #13312 Both CoreCLR Debug and NativeAOT package tests in Azure build 1666161 abort in HandlerCancellationDoesNotScaleQuadratically(True): JNI ERROR (app bug): weak global reference table overflow (max=51200). The abort dumps contain 19,211 and 22,876 android.os.Message peers alongside the runnable owner/token identities. RecordingHandler creates a managed Message peer whenever Java forwards a post through SendMessageAtTime. Dispose that temporary peer after forwarding the message; the Java queue continues to own the message and runnable. Keep the original 4,000/16,000 workloads and scaling thresholds rather than hiding the failure by reducing coverage. The 40 callback cases pass on API35 ARM64 using the private SDK: once on Debug/CoreCLR and twice on Release/NativeAOT. Co-authored-by: Copilot App <[email protected]>
Context: https://dev.azure.com/dnceng-public/public/_build/results?buildId=1667641 Release and NoAab each fail 12 callback cases in NUnit MethodWrapper.get_Name(). The test helper invokes assertions on a Java-created HandlerThread without flowing the NUnit AsyncLocal execution context. NUnit falls back to AdhocContext, whose reflection-only AdhocTestMethod has been removed by trimming. The same trimmed Release stack reproduces locally, including an unhandled assertion from the later queued execution callback. Capture the test ExecutionContext and run the Handler test body inside it. Keep the separately queued execution callback free of NUnit calls and assert its post result back on the test thread. Do not change production callback context semantics or preserve unused NUnit metadata as a workaround. Add regressions for NUnit/AsyncLocal identity on the Handler thread and nested Task.Run, plus propagation of a genuine failed assertion to the test thread. Isolate that expected failure from the outer NUnit test result. All 42 callback cases pass on API35 ARM64 with the private SDK in Debug/CoreCLR, trimmed Release AAB, trimmed Release NoAab APK, and Release/NativeAOT. Co-authored-by: Copilot App <[email protected]>
|
/review |
|
✅ Android PR Reviewer completed successfully!
|
There was a problem hiding this comment.
✅ LGTM — code review
0 errors · 0 warnings · 1 non-blocking suggestion. Reviewed all 12 changed files in full, the shared RunnableImplementor callers, and the peer-disposal/reference-management paths. No merge-blocking code issues found. The per-registration unlinking, weak Java identities, token filtering, and posted-state snapshot address the repeated-cancellation problem without eagerly disposing callbacks that another queue or custom callback may still own. The regression coverage is substantial, including disposed aliases, drawable forwarding/sibling isolation, collection, failed posts, exception cleanup, and an in-flight posting race. One inline suggestion asks for execution-based View cancellation coverage.
CI evidence: All 40 GitHub checks report success, including the overall dotnet-android check for Azure build 1672089. Independent Azure build/timeline verification was blocked by Azure CLI authentication, so the Azure result and non-gating test outcomes were not independently confirmed. No local builds or device tests were run for this review.
Generated by Android PR Reviewer for #13312 · copilot · gpt61 · 41.6 AIC · ⌖ 4.74 AIC · ⊞ 20.1K
Comment /review to run again
|
@dalexsoto review |
dalexsoto
left a comment
There was a problem hiding this comment.
Reviewed head 3fd17d8 in full, including ActionCallbackTests. Per-registration weak tracking, weak JNI identities, token/owner filtering and retire-after-remove match the tests' claims; prior review threads are addressed. Other RunnableImplementor consumers use the unregistered constructor and are unaffected, and the base delta since pinning does not overlap this PR. No blocking issues found. Optional: an execution-based View cancellation test as previously suggested. Static read only; nothing was built or run.
jonathanpeppers
left a comment
There was a problem hiding this comment.
Just looking at the breadth of changes, I think we should do a pass and try to get copilot to simplify.
Context: #13312 (comment) Use a HashSet of resurrection-tracking weak references instead of linked-list nodes and manual traversal. Each runnable removes its exact registration in constant time. Consolidate the five Handler post-completion paths into CompletePost(). Keep registration before native posting and retain the posted-state snapshot. Deferring registration until posting returns misses cancellation performed by a Handler override after enqueueing but before returning. Add regressions for that cancellation and for execution completing before Post returns; the cancellation regression failed against the deferred-registration experiment. Rebuilt the private SDK with make leeroy. All 44 ActionCallbacks cases passed on Debug/CoreCLR, trimmed Release AAB, trimmed NoAab APK, and Release/NativeAOT on API35 ARM64. Co-authored-by: Copilot App <[email protected]>
Protect the callback registry and posting state with System.Threading.Lock instead of using the ConditionalWeakTable as a monitor. Keep all five critical sections on the same lock and preserve native callback removal outside it. Validation: NUGET_PACKAGES="$PWD/bin/nuget" make leeroy passed. Repeated all four build/install and no-build test commands documented in PR #13312 with -warnaserror:CS8632: Debug/CoreCLR, trimmed Release AAB, trimmed NoAab APK, and Release/NativeAOT each passed all 44 ActionCallbacks tests on API35 ARM64. Co-authored-by: Copilot App <[email protected]>
|
/review |
|
✅ Android PR Reviewer completed successfully!
|
There was a problem hiding this comment.
f9c98c7db5e6bab0896d95f3c7011a2ff0480e19, including the shared runnable lifecycle and its callers. No new blocking correctness issues found: 0 errors, 0 warnings, 1 suggestion (inline).
The exact-registration HashSet cleanup, independent weak JNI identities, token filtering, and pre-post registration guard address the earlier ownership and cancellation concerns. The regression coverage is substantial, including disposed aliases, drawable forwarding, ignored unscheduling, posting-boundary races, and scaling.
CI: GitHub reports the dotnet-android checks for Azure build 1675098 still running/queued, with no failures reported in the retrieved checks. Completed macOS build, Android tooling tests, and CLA checks passed. Direct Azure build/timeline queries were blocked by an authentication requirement and a CLI initialization error, so the overall pipeline result and detailed stage status remain unverified; this is not a green-CI verdict. This was a source review; I did not independently rerun the device tests reported in the PR.
Generated by Android PR Reviewer for #13312 · copilot · gpt61 · 30.2 AIC · ⌖ 4.91 AIC · ⊞ 20.2K
Comment /review to run again
dalexsoto
left a comment
There was a problem hiding this comment.
Requesting changes for one concrete issue found in a full review of this head.
View.RemoveCallbacks(Action) never retires cancelled registrations, so repeated post/cancel scales quadratically until a GC.
src/Mono.Android/Android.Views/View.cs:67-72:RemoveCallbackscallsRemove (action, this, …)withoutretire: true.View.cs:47-65:Post/PostDelayednever callCompletePost, sopostedstays false for View registrations. Passingretire: truealone would therefore still not retire them.src/Mono.Android/Java.Lang/Thread.cs:canRetire(line 117) requiresretire && runnable.posted, andUnregister()otherwise runs only fromDispose(bool)(lines 89-96), i.e. after finalization.Handler.RemoveCallbackscannot retire View entries, because they record the View as owner.
Impact: until a GC, every view.RemoveCallbacks (a) re-matches all earlier cancelled runnables for that Action that still have a handle, making one JNI IsSameObject call and one native View.removeCallbacks call each (Thread.cs:111-127). A debounce loop (post, cancel, repeat) becomes O(N²). On main, View.RemoveCallbacks removes the single table entry and disposes the runnable in O(1).
Test gap: the only post/cancel scaling test, HandlerCancellationDoesNotScaleQuadratically (tests 446-496), covers Handler only.
Suggested fix: call CompletePost from View.Post/PostDelayed (as the Handler path does), pass retire: true from View.RemoveCallbacks, and add a View equivalent of the Handler scaling test.
This is a review-completeness miss on my part: View.cs is unchanged since 3fd17d8, which I approved, and the retire design there had the same gap.
A fresh-eyes pass over all 12 changed files found no other blocker: HashSet mutation stays under instancesLock, weak global references are freed in Unregister, and the disposed-handle race already exists on main. Pending CI is not part of this finding.
Static source review only; no repository code or tests were executed.
|
@dalexsoto Fixed the View cancellation scaling finding in f27d55c.
Added four regression cases covering both Post overloads: repeated post/cancel scaling with every runnable held strongly reachable, plus cancellation before Post returns followed by retirement after completion. Before the fix, all four new cases failed; 128 post/cancel operations made 8,256 native removal calls. With the fix, each operation makes exactly one removal, and the 1,000/4,000-operation timing checks pass. The original 46 cases also remain green. Local validation on the privately rebuilt SDK, arm64 Android 15/API 35:
export NUGET_PACKAGES="$PWD/bin/nuget"
export ADB_SERVER_SOCKET=tcp:localhost:5074 ANDROID_ADB_SERVER_PORT=5074 ANDROID_SERIAL=emulator-5584
./dotnet-local.sh build -t:Install -c CONFIG tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -p:IncludeCategories=ActionCallbacks -p:RuntimeIdentifier=android-arm64 PROPERTIES '-p:AdbTarget=-s emulator-5584' -warnaserror:CS8632 -nr:false
(
cd tests/Mono.Android-Tests/Mono.Android-Tests
../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --no-build -c CONFIG -p:IncludeCategories=ActionCallbacks -p:RuntimeIdentifier=android-arm64 PROPERTIES '-p:AdbTarget=-s emulator-5584' --device emulator-5584 --report-trx --results-directory ../../../bin/TestCONFIG/TestResults
)The exact CONFIG/PROPERTIES substitutions, applied identically to build and test:
Verified that the NativeAOT APK contains the test native library and no CoreCLR/MonoVM runtime libraries. The local framework's informational version still carries its earlier |
Fixes: #13309 Posting the same `Action` repeatedly and then cancelling it removes only the most recent post: Action action = () => DoWork (); handler.PostDelayed (action, 1000); handler.PostDelayed (action, 1000); handler.RemoveCallbacks (action); // the first post still runs Each `Handler`, `View`, and `Drawable` `Action` overload created a new `RunnableImplementor`, and `RunnableImplementor.Remove()` looked it up in a `ConditionalWeakTable<Action, RunnableImplementor>` populated with `AddOrUpdate()`. The table therefore held only the newest wrapper, so `RemoveCallbacks()` could only cancel that one. Every earlier wrapper stayed in the Java queue, kept its delegate, its captured state, and a JNI global reference alive, and later ran even though it had been "cancelled". In the issue's reproduction, 7,500 post/cancel operations retained 7,500 extra JNI global references and 33,044,000 managed bytes. Instead, create one `RunnableImplementor` per `Action` via `ConditionalWeakTable.GetValue()` and reuse it for every removable post. Java's `removeCallbacks()` and `unscheduleDrawable()` already remove *every* queued instance of a `Runnable`, scoped by the handler, view, token, or drawable passed to them, so no managed bookkeeping is needed. Because a shared runnable may still be queued elsewhere, it is no longer disposed in `Run()`, on removal, or after a failed post. The table ties its lifetime to the `Action`, so both are collected once Java no longer references the runnable. Non-removable uses such as `new Thread (Action)` and `Activity.RunOnUiThread (Action)` keep their own instances and still dispose after `Run()`. The `removable` constructor is now private so `GetOrCreate()` is the only way to create a removable runnable; the type is `internal`, so this is not an API change. One behavior change: if the same `Action` is scheduled for two children of one `LayerDrawable`, unscheduling it for one child now also cancels it for the other. Both children forward through the same outer drawable callback with the same `Runnable`, which matches Java semantics for a shared `Runnable`. Previously this case cancelled only the most recent post, which might belong to the other child. Add `HandlerTest` cases for repeated post/cancel, handler and token scoping, re-posting after cancellation, and collection of executed `Action`s. Co-authored-by: Copilot App <[email protected]>
2795e6e to
bc03fd1
Compare
|
@jonathanpeppers @dalexsoto I rewrote this PR from scratch as a single commit, bc03fd1, rebased onto current What changedBefore (previous revisions): each post still created a new
Now: one Why this is better
Tradeoffs
Tests and validationTests are now two focused
The full All review threads are resolved. Could you take another look? |
dalexsoto
left a comment
There was a problem hiding this comment.
I understand the accepted nested LayerDrawable tradeoff, but sharing one runnable per Action also loses isolation without nesting:
- In
src/Mono.Android/Android.Views/View.cs:52-62, with attached sibling views, post the same action on B and then A;A.RemoveCallbacks(action)also removes B's post. The views share a window handler, and Android matches handler + runnable, not view identity. - In
src/Mono.Android/Android.Graphics.Drawables/Drawable.cs:9-16, schedule the same action first on a detached view's foreground drawable and then its background; unscheduling the background also removes the foreground's pending action. The detached view queue stores only the runnable, not the drawable token. - On an attached view, schedule an action on its background drawable, then post that action through the view and call
View.RemoveCallbacks(action). Android also removes the drawable's animation callback because the choreographer removal uses a null token as a wildcard.
For each ordering, the base implementation creates separate runnables and retains the unrelated callback. Please preserve view, drawable, and cross-API cancellation boundaries while still removing repeated posts for the intended owner. The View, detached queue, and choreographer sources show the matching behavior.
This is a static source review; I did not run tests, builds, or devices.
Posting an Action through a wrapper, disposing that wrapper, and then cancelling through a replacement wrapper for the same Java object missed the queued runnables, because owners were keyed by managed wrapper identity. Key owners by JniIdentityHashCode + IsSameObject over weak global references, pruning collected owners in amortized sweeps. Also release blocked loopers and quit HandlerThreads in finally blocks, with a bounded join, in the new Handler tests. Co-authored-by: Copilot App <[email protected]>
|
/review |
|
✅ Android PR Reviewer completed successfully!
|
There was a problem hiding this comment.
⚠️ Needs Changes
Reviewed all 13 changed files in full and traced the shared runnable lookup against the base revision. 0 errors, 1 warning, 1 suggestion are attached inline. The warning identifies a same-View cancellation compatibility regression between the direct ScheduleDrawable(Action) and RemoveCallbacks(Action) helpers; the suggestion requests persistent coverage for the new owner-sweep cleanup path.
Reusing runnables addresses repeated-post cancellation without disposing peers that remain queued. The Java-identity lookup, replacement-wrapper regression, sibling isolation cases, and unconditional HandlerThread cleanup are valuable improvements.
CI: GitHub reports 40/40 checks successful, including the aggregate dotnet-android check for Azure build 1681395. Direct Azure build/timeline verification was blocked because az devops invoke requires authentication in this environment, so no independent Azure failed-test analysis is claimed. This was a source review; device tests were not rerun locally.
Generated by Android PR Reviewer for #13312 · copilot · gpt61 · 39.7 AIC · ⌖ 7.94 AIC · ⊞ 20.3K
Comment /review to run again
…13312) View.ScheduleDrawable (who, Action, long) keys its runnable by the drawable, so View.RemoveCallbacks (Action) on the same View no longer found it; before the owner-keyed table, the Action-keyed lookup did. Record the drawable runnables each View schedules through this helper and cancel them from View.RemoveCallbacks (Action), keeping sibling Views and other drawables isolated. Add an execution-based regression for that path, and a regression that keeps an Action rooted while transient Handler owners are collected, checking that sweeping releases their cached runnables and that a surviving owner's pending posts stay cancelable. Co-authored-by: Copilot App <[email protected]>
A long-lived View that scheduled a rooted Action for many transient drawables kept every drawable's runnable in its strong per-Action list. Track them in a ConditionalWeakTable instead: each runnable is owned by its drawable's entry (or the Java queue), entries disappear once it is collected, adds are deduplicated by reference without calling Java equals(), and the table is safe to enumerate concurrently. Co-authored-by: Copilot App <[email protected]>
Addressed: the PR was rewritten from scratch as a minimal fix (one shared runnable per owner and Action), replacing the original registries/bookkeeping this review asked to simplify. See #13312 (comment).
|
/review |
|
✅ Android PR Reviewer completed successfully!
|
There was a problem hiding this comment.
⚠️ Needs Changes
Findings: 1 ❌ error, 0 View.RemoveCallbacks(Action) cancel new Drawable.ScheduleSelf(Action) work after the original direct schedule was cancelled. This is based on source-path analysis; I did not run a local device reproduction.
The per-owner runnable reuse addresses repeated-post cancellation directly, and the replacement-wrapper, owner-sweep, sibling-isolation, and collection regressions cover important interop boundaries. I read all 13 changed files in full and traced the shared helper callers and project configuration.
CI: All 38 reported GitHub check runs succeeded, including the overall dotnet-android check for Azure build 1685198. Direct Azure build/timeline verification was unavailable because the CLI queries failed during initialization/authentication, so I could not independently inspect the Azure build result or non-gating test outcomes.
Generated by Android PR Reviewer for #13312 · copilot · gpt61 · 33.9 AIC · ⌖ 7.37 AIC · ⊞ 20.3K
Comment /review to run again
View.ScheduleDrawable (who, Action, long) reused the drawable's own runnable and recorded it on the View. That record outlived the callback, so once a View had scheduled and cancelled an Action for a drawable, every later View.RemoveCallbacks (Action) also cancelled the drawable's unrelated ScheduleSelf posts. A shared runnable cannot tell which entry point queued it, so the record could not be cleared on execution. Give View.ScheduleDrawable a runnable per (View, drawable, Action) that only that helper queues; a stale record then cancels nothing. View.UnscheduleDrawable and Drawable.UnscheduleSelf also cancel it, so cross-entry cancellation keeps working. Co-authored-by: Copilot App <[email protected]>
The runtime test suite now uses MSTest, so convert the callback test fixtures and parameterized cases to match. This fixes missing NUnit types when building the merged PR. Validation: Not run locally while another full SDK build is active. Co-authored-by: Copilot App <[email protected]>
Fixes: #13309 Posting the same `Action` repeatedly and then cancelling it removes only the most recent post: Action action = () => DoWork (); handler.PostDelayed (action, 1000); handler.PostDelayed (action, 1000); handler.RemoveCallbacks (action); // the first post still runs Each `Handler`, `View`, and `Drawable` `Action` overload created a new `RunnableImplementor`, and `RunnableImplementor.Remove()` looked it up in a `ConditionalWeakTable<Action, RunnableImplementor>` populated with `AddOrUpdate()`. The table therefore held only the newest wrapper, so `RemoveCallbacks()` could only cancel that one. Every earlier wrapper stayed in the Java queue, kept its delegate, its captured state, and a JNI global reference alive, and later ran even though it had been "cancelled". In the issue's reproduction, 7,500 post/cancel operations retained 7,500 extra JNI global references and 33,044,000 managed bytes. Instead, create one `RunnableImplementor` per `Action` via `ConditionalWeakTable.GetValue()` and reuse it for every removable post. Java's `removeCallbacks()` and `unscheduleDrawable()` already remove *every* queued instance of a `Runnable`, scoped by the handler, view, token, or drawable passed to them, so no managed bookkeeping is needed. Because a shared runnable may still be queued elsewhere, it is no longer disposed in `Run()`, on removal, or after a failed post. The table ties its lifetime to the `Action`, so both are collected once Java no longer references the runnable. Non-removable uses such as `new Thread (Action)` and `Activity.RunOnUiThread (Action)` keep their own instances and still dispose after `Run()`. The `removable` constructor is now private so `GetOrCreate()` is the only way to create a removable runnable; the type is `internal`, so this is not an API change. One behavior change: if the same `Action` is scheduled for two children of one `LayerDrawable`, unscheduling it for one child now also cancels it for the other. Both children forward through the same outer drawable callback with the same `Runnable`, which matches Java semantics for a shared `Runnable`. Previously this case cancelled only the most recent post, which might belong to the other child. Add `HandlerTest` cases for repeated post/cancel, handler and token scoping, re-posting after cancellation, and collection of executed `Action`s. Co-authored-by: Copilot App <[email protected]>
Context: #13312 (review) Sharing one `RunnableImplementor` per `Action` cancelled every pending post, but Android matches some queues by runnable alone, so it also cancelled posts made by *other* owners: * Attached sibling `View`s share the window `Handler`; `A.RemoveCallbacks(action)` removed B's post. * A detached `View` queues drawable callbacks in `HandlerActionQueue` without the drawable; unscheduling the background removed the foreground's callback. * `View.removeCallbacks()` removes Choreographer callbacks with a `null` (wildcard) token, so it removed the view's drawable animation callback. * Children of one `LayerDrawable` forward through the same parent callback, so unscheduling one child removed its sibling's callback. Key the shared runnable by owner as well: the `Handler`, the `View` for `View.Post*()`, the drawable for `Drawable.ScheduleSelf()`, and `who` for every `ScheduleDrawable(who, …)` overload. Each owner gets its own runnable, so Java removal stays within that owner while still cancelling every repeated post. `ScheduleSelf()` and `ScheduleDrawable(who, …)` for the same drawable still share a runnable, so either entry point can cancel the other. Add `ViewActionCallbackTests` covering each case on an attached Activity. All five cases failed against the previous revision and pass now. Co-authored-by: Copilot App <[email protected]>
Posting an Action through a wrapper, disposing that wrapper, and then cancelling through a replacement wrapper for the same Java object missed the queued runnables, because owners were keyed by managed wrapper identity. Key owners by JniIdentityHashCode + IsSameObject over weak global references, pruning collected owners in amortized sweeps. Also release blocked loopers and quit HandlerThreads in finally blocks, with a bounded join, in the new Handler tests. Co-authored-by: Copilot App <[email protected]>
…13312) View.ScheduleDrawable (who, Action, long) keys its runnable by the drawable, so View.RemoveCallbacks (Action) on the same View no longer found it; before the owner-keyed table, the Action-keyed lookup did. Record the drawable runnables each View schedules through this helper and cancel them from View.RemoveCallbacks (Action), keeping sibling Views and other drawables isolated. Add an execution-based regression for that path, and a regression that keeps an Action rooted while transient Handler owners are collected, checking that sweeping releases their cached runnables and that a surviving owner's pending posts stay cancelable. Co-authored-by: Copilot App <[email protected]>
A long-lived View that scheduled a rooted Action for many transient drawables kept every drawable's runnable in its strong per-Action list. Track them in a ConditionalWeakTable instead: each runnable is owned by its drawable's entry (or the Java queue), entries disappear once it is collected, adds are deduplicated by reference without calling Java equals(), and the table is safe to enumerate concurrently. Co-authored-by: Copilot App <[email protected]>
View.ScheduleDrawable (who, Action, long) reused the drawable's own runnable and recorded it on the View. That record outlived the callback, so once a View had scheduled and cancelled an Action for a drawable, every later View.RemoveCallbacks (Action) also cancelled the drawable's unrelated ScheduleSelf posts. A shared runnable cannot tell which entry point queued it, so the record could not be cleared on execution. Give View.ScheduleDrawable a runnable per (View, drawable, Action) that only that helper queues; a stale record then cancels nothing. View.UnscheduleDrawable and Drawable.UnscheduleSelf also cancel it, so cross-entry cancellation keeps working. Co-authored-by: Copilot App <[email protected]>
6a9c60b to
96b5b60
Compare
The runtime test project uses MSTest, so the callback tests must use its test attributes instead of NUnit. This restores compilation after the branch was rebased onto main. Co-authored-by: Copilot App <[email protected]>
|
/review |
|
✅ Android PR Reviewer completed successfully!
|
There was a problem hiding this comment.
⚠️ Needs Changes
Findings: 0 errors, 1 warning, 1 suggestion. The warning concerns timing-dependent synchronization in the new View tests; the suggestion adds permanent coverage for collection of cancelled capturing Actions. Both are posted inline. I found no blocking production-code defect in the reviewed changes.
The shared runnable correctly lets native cancellation remove every pending post for an owner, while Java-identity matching preserves replacement-wrapper cancellation. The separate View/drawable registration path preserves cross-helper cancellation without conflating ordinary drawable posts. The owner sweep and execution-based sibling/token tests are useful coverage; the documented retention of rooted Actions until a later sweep is an explicit tradeoff, not a newly discovered finding.
CI: All 38 check runs reported for head 50d6af0fff3d56aa0dd4f70384d9944a4afab65a are completed successfully, including the aggregate dotnet-android check linked to Azure build 1693567. Independent Azure build/timeline verification could not be completed: the CLI build query failed during initialization, and the timeline query required authentication. I therefore cannot independently certify the Azure result or non-gating device-test results. The description's statement that the MSTest conversion has not had a new CI run is stale relative to these successful check runs.
Scope: Read the GitHub diff and all 13 changed files in full, traced runnable callers and JNI reference handling, and checked the product/test project configuration and existing review threads. No local build or device tests were run as part of this review. The local three-dot diff was unavailable because the checkout has no merge base with origin/main; review line locations were checked against the GitHub diff.
Generated by Android PR Reviewer for #13312 · copilot · gpt61 · 37.4 AIC · ⌖ 8.18 AIC · ⊞ 20.3K
Comment /review to run again
A fixed delay and a Handler message do not guarantee that drawable animation callbacks have run. Wait for ordered Handler and animation sentinels before checking the results. Also verify that repeatedly posted, canceled capturing Actions can be collected while their Handler remains alive. Validation: git diff --check passed. Local build and device tests were blocked by other active work on the shared host. Co-authored-by: Copilot App <[email protected]>
A rooted Action kept canceled runnable peers alive, and sweeping a collected drawable could lose the lookup needed to cancel a callback queued on a detached View. Use synchronized weak runnable caches and keep a separate Action-indexed lookup for View-scheduled drawable callbacks. CoreCLR and NativeAOT Release device suites passed on API 35 ARM64 after full rebuilds. CoreCLR: 1,106 passed, 8 skipped. NativeAOT: 1,043 passed, 8 skipped. Co-authored-by: Copilot App <[email protected]>
Preserve the published PR history while retaining the validated callback implementation and tests. Co-authored-by: Copilot App <[email protected]>
Keep focused behavioral coverage for repeated cancellation, Java owner identity, callback collection, and View and Drawable ownership while removing overlapping stress and implementation-detail tests. Co-authored-by: Copilot App <[email protected]>

Fixes: #13309
Posting the same
Actionrepeatedly and then cancelling it removes only the most recent post:Each
Handler,View, andDrawableActionoverload created a newRunnableImplementor, andRunnableImplementor.Remove()looked it up in aConditionalWeakTable<Action, RunnableImplementor>populated withAddOrUpdate(). The table therefore held only the newest wrapper, soRemoveCallbacks()could only cancel that one. Every earlier wrapper stayed in the Java queue, kept its delegate, its captured state, and a JNI global reference alive, and later ran even though it had been "cancelled". In the issue's reproduction, 7,500 post/cancel operations retained 7,500 extra JNI global references and 33,044,000 managed bytes.Instead, create one
RunnableImplementorper owner andActionand reuse it for every removable post:Handler.Post*/RemoveCallbacksHandlerView.Post*/RemoveCallbacksViewDrawable.ScheduleSelf/UnscheduleSelfScheduleDrawable(who, …)/UnscheduleDrawable(who, …)whoView.ScheduleDrawable(who, …)/UnscheduleDrawable(who, …)ViewandwhoJava's
removeCallbacks()andunscheduleDrawable()remove every queued instance of aRunnable, so repeated posts by one owner are all cancelled. Owners matter because some Android queues match by runnable alone. Attached siblingViews share the windowHandler, and a detachedView'sHandlerActionQueuestores no drawable. The Choreographer removesViewcallbacks with a wildcardnulltoken, andLayerDrawablechildren forward through the same parent callback. A per-owner runnable keeps cancellation within its owner. Drawable callback helpers use the drawable-owned runnable;View.ScheduleDrawable()uses a separate runnable so a View can cancel its own posts without cancelling the drawable's unrelated posts.Owners are matched by Java identity, not by managed wrapper. A post made through one wrapper can then be cancelled through a replacement wrapper for the same Java object, for example after
Dispose(), or fromGetObject<T>(),FindViewById()orView.Handler. The table isDictionary<JniIdentityHashCode, List<Owner>>, compared withIsSameObject()under aLock. EachOwnerholds a weak global reference plus aConditionalWeakTable<Action, RunnableImplementor>. Owners whose Java objects were collected are pruned in amortized sweeps once the owner count reachesmax(256, 2 × live). Limitation: a collected owner whoseActions stay rooted, such as cached static lambdas, keeps its runnables until the next sweep.View.ScheduleDrawable(who, Action, long)uses its own runnable per (View, drawable,Action), which only that helper queues.View.RemoveCallbacks(Action)cancels it, as onmain, without touching the drawable's ownScheduleSelfposts, even after earlier schedule/cancel cycles.View.UnscheduleDrawable(who, Action)andDrawable.UnscheduleSelf(Action)cancel it too. The table is keyed by the drawable's identity entry and goes away when that entry is swept, so a long-lived View does not retain runnables of transient drawables. AScheduleDrawablethat racesRemoveCallbackson another thread may or may not be cancelled; View APIs are UI-thread only.Because a shared runnable may still be queued, it is no longer disposed in
Run(), on removal, or after a failed post. The per-ownerConditionalWeakTableties its lifetime to itsAction, and the owner entry is dropped once its Java object is collected, so the runnable is collected once these are unreachable and Java no longer references it. Non-removable uses such asnew Thread (Action)andActivity.RunOnUiThread (Action)keep their own instances and still dispose afterRun(). Theremovableconstructor is now private soGetOrCreate()is the only way to create a removable runnable; the type isinternal, so this is not an API change.Tests
HandlerTest.RemoveCallbacksCancelsEveryPendingPost: repeated post/cancel, other handlers and tokens unaffected, and posting again after cancellation.HandlerTest.ExecutedActionCallbacksAreCollectible: executed capturingActions are collected.HandlerTest.RemoveCallbacksThroughReplacementWrapper: posts through a wrapper, disposes it, then cancels through a new wrapper of the same JavaHandler.HandlerTest.CollectedOwnersReleaseRunnablesOfRootedActions: with a rootedAction, runnables of collected transient owners become collectible after the owner sweep, and a surviving owner's pending posts stay cancelable.HandlerTestcases release blocked loopers and quit theirHandlerThreadinfinally, with a bounded join.ViewActionCallbackTests, using an attached Activity:RemoveCallbacksPreservesSiblingViewPosts: sibling views share the windowHandler.UnscheduleSelfPreservesOtherDrawablesOnView: foreground and background drawables, detached and attached.RemoveCallbacksPreservesDrawableCallbacks:View.RemoveCallbacksand a drawable callback, with and without an earlierView.ScheduleDrawable/RemoveCallbackscycle.UnscheduleCancelsViewScheduledDrawable:View.UnscheduleDrawableandDrawable.UnscheduleSelfcancelView.ScheduleDrawable(who, Action, …)posts.UnscheduleSelfPreservesNestedSiblings: two children of oneLayerDrawable.RemoveCallbacksCancelsScheduledDrawable:View.ScheduleDrawable(who, Action, …)is cancelled byView.RemoveCallbacks(Action), detached and attached, without touching a sibling View.ScheduledDrawableRunnablesDoNotAccumulateOnView: a long-lived View does not retain runnables of transient drawables.The callback tests use MSTest to match the runtime test project on
main.Four of the five
ViewActionCallbackTestscases failed against the previous revision, which shared one runnable perAction. The attached foreground/background variant passed there, because the Choreographer filters by drawable token.Action lifetime stress investigation
A temporary stress fixture (not included in the PR) exercised executed and cancelled captured Actions, transient Handler/Action cycles, and rooted Actions on Android 15 (API 35) arm64. The current implementation passed on CoreCLR and NativeAOT; a controlled NativeAOT run using the earlier per-Action table also passed. Across the three current-implementation runs, 270,000 measured posts finalized all 120,000 captured payloads, with zero surviving tracked delegates, payloads, or transient owners and no JNI global-reference growth. CoreCLR gcdumps showed six
System.Actioninstances at baseline, midpoint, and end, with no stress closures retained; NativeAOT whole-workloaddotnet-counterscaptures showed stable post-GC heap sizes. Repeated UI cancellation cases also passed alongside the original finalizer assertions.These targeted ARM64 experiments did not reproduce or establish the cause of the original x64 CI finalizer failures; full CI test ordering and the x64 environment were not reproduced. NativeAOT
dotnet-gcdumpcollection failed with a serializationOverflowException, so no NativeAOT dump is claimed as evidence.Validation
Ran the full
Mono.Android.NET-Testssuite against a locally rebuilt SDK on an Android 15 (API 35) arm64 emulator:TestsFlavor=NoAab)The NativeAOT APK contains
libMono.Android.NET-Tests.soand no CoreCLR/MonoVM libraries.Re-validated the Java-identity change,
2136314425, with the full suite on an Android 10 (API 29) arm64 emulator. The checks confirmed that both apps consumed the rebuiltMono.Android.dll. For NativeAOT, the binlog shows ILC ran against it.The follow-up commits for the
View.ScheduleDrawablepath and the owner-sweep regression (dec5817446,09f3db5f87,b468d5e377), and the MSTest conversion, have not been run locally. CI build 1687868 onb468d5e377failed to compile the APK tests because the runtime test project had migrated to MSTest. The conversion has not yet been validated locally or by a new CI run; another full SDK build was active on the host.