Skip to content

[Mono.Android] Cancel every pending post of an Action - #13312

Open
simonrozsival wants to merge 18 commits into
mainfrom
simonrozsival-fix-repeated-action-callback-cancellatio
Open

simonrozsival wants to merge 18 commits into
mainfrom
simonrozsival-fix-repeated-action-callback-cancellatio

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Oct 29, 2026 •

Copy link
Copy Markdown
Member

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 owner and Action and reuse it for every removable post:

API Owner
Handler.Post* / RemoveCallbacks the Handler
View.Post* / RemoveCallbacks the View
Drawable.ScheduleSelf / UnscheduleSelf the drawable itself
Drawable callback ScheduleDrawable(who, …) / UnscheduleDrawable(who, …) who
View.ScheduleDrawable(who, …) / UnscheduleDrawable(who, …) the View and who

Java's removeCallbacks() and unscheduleDrawable() remove every queued instance of a Runnable, so repeated posts by one owner are all cancelled. Owners matter because some Android queues match by runnable alone. Attached sibling Views share the window Handler, and a detached View's HandlerActionQueue stores no drawable. The Choreographer removes View callbacks with a wildcard null token, and LayerDrawable children 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 from GetObject<T>(), FindViewById() or View.Handler. The table is Dictionary<JniIdentityHashCode, List<Owner>>, compared with IsSameObject() under a Lock. Each Owner holds a weak global reference plus a ConditionalWeakTable<Action, RunnableImplementor>. Owners whose Java objects were collected are pruned in amortized sweeps once the owner count reaches max(256, 2 × live). Limitation: a collected owner whose Actions 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 on main, without touching the drawable's own ScheduleSelf posts, even after earlier schedule/cancel cycles. View.UnscheduleDrawable(who, Action) and Drawable.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. A ScheduleDrawable that races RemoveCallbacks on 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-owner ConditionalWeakTable ties its lifetime to its Action, 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 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.

Tests

  • HandlerTest.RemoveCallbacksCancelsEveryPendingPost: repeated post/cancel, other handlers and tokens unaffected, and posting again after cancellation.
  • HandlerTest.ExecutedActionCallbacksAreCollectible: executed capturing Actions are collected.
  • HandlerTest.RemoveCallbacksThroughReplacementWrapper: posts through a wrapper, disposes it, then cancels through a new wrapper of the same Java Handler.
  • HandlerTest.CollectedOwnersReleaseRunnablesOfRootedActions: with a rooted Action, runnables of collected transient owners become collectible after the owner sweep, and a surviving owner's pending posts stay cancelable.
  • The HandlerTest cases release blocked loopers and quit their HandlerThread in finally, with a bounded join.
  • ViewActionCallbackTests, using an attached Activity:
    • RemoveCallbacksPreservesSiblingViewPosts: sibling views share the window Handler.
    • UnscheduleSelfPreservesOtherDrawablesOnView: foreground and background drawables, detached and attached.
    • RemoveCallbacksPreservesDrawableCallbacks: View.RemoveCallbacks and a drawable callback, with and without an earlier View.ScheduleDrawable/RemoveCallbacks cycle.
    • UnscheduleCancelsViewScheduledDrawable: View.UnscheduleDrawable and Drawable.UnscheduleSelf cancel View.ScheduleDrawable(who, Action, …) posts.
    • UnscheduleSelfPreservesNestedSiblings: two children of one LayerDrawable.
    • RemoveCallbacksCancelsScheduledDrawable: View.ScheduleDrawable(who, Action, …) is cancelled by View.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 ViewActionCallbackTests cases failed against the previous revision, which shared one runnable per Action. 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.Action instances at baseline, midpoint, and end, with no stress closures retained; NativeAOT whole-workload dotnet-counters captures 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-gcdump collection failed with a serialization OverflowException, so no NativeAOT dump is claimed as evidence.

Validation

Ran the full Mono.Android.NET-Tests suite against a locally rebuilt SDK on an Android 15 (API 35) arm64 emulator:

Configuration Total Passed Failed Skipped
Debug / CoreCLR 1070 1062 0 8
Release / CoreCLR, trimmed AAB 1070 1062 0 8
Release / CoreCLR, trimmed APK (TestsFlavor=NoAab) 1070 1062 0 8
Release / NativeAOT 1007 999 0 8

The NativeAOT APK contains libMono.Android.NET-Tests.so and 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 rebuilt Mono.Android.dll. For NativeAOT, the binlog shows ILC ran against it.

Configuration Total Passed Failed Skipped
Debug / CoreCLR 1071 1063 0 8
Release / NativeAOT 1008 1000 0 8

The follow-up commits for the View.ScheduleDrawable path and the owner-sweep regression (dec5817446, 09f3db5f87, b468d5e377), and the MSTest conversion, have not been run locally. CI build 1687868 on b468d5e377 failed 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.

NUGET_PACKAGES="$PWD/bin/nuget" make leeroy
# CONFIG / PROPS:
#   Debug   / -p:PublishAot=false
#   Release / -p:PublishAot=false -p:AndroidPackageFormats=aab
#   Release / -p:PublishAot=false -p:TestsFlavor=NoAab -p:AndroidPackageFormat=apk
#   Release / -p:PublishAot=true -p:TestsFlavor=NativeAOT
./dotnet-local.sh build -t:Install -c $CONFIG tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -p:RuntimeIdentifier=android-arm64 $PROPS '-p:AdbTarget=-s emulator-5584' -nr:false
(cd tests/Mono.Android-Tests/Mono.Android-Tests && ../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --no-build -c $CONFIG -p:RuntimeIdentifier=android-arm64 $PROPS '-p:AdbTarget=-s emulator-5584' --device emulator-5584 --report-trx --results-directory ../../../bin/Test$CONFIG/TestResults)

Copilot AI balanced review requested due to automatic review settings October 29, 2026 13:27

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Active findings identify cancellation failures across drawable forwarding and disposed aliases, quadratic cancellation costs, and unintended retention of owners and contexts.

5 open issues
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

Comment thread src/Mono.Android/Android.OS/Handler.cs Resolved
Comment thread src/Mono.Android/Java.Lang/Thread.cs Resolved
Comment thread src/Mono.Android/Java.Lang/Thread.cs Resolved
Comment thread src/Mono.Android/Java.Lang/Thread.cs Resolved
Comment thread src/Mono.Android/Java.Lang/Thread.cs Resolved
simonrozsival added a commit that referenced this pull request Nov 5, 2026
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]>
simonrozsival added a commit that referenced this pull request Nov 6, 2026
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]>
simonrozsival added a commit that referenced this pull request Nov 10, 2026
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]>
@simonrozsival simonrozsival added the ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). label Nov 10, 2026
@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13312

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ LGTM — 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

@simonrozsival

Copy link
Copy Markdown
Member Author

@dalexsoto review

@dalexsoto dalexsoto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 jonathanpeppers left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just looking at the breadth of changes, I think we should do a pass and try to get copilot to simplify.

Comment thread src/Mono.Android/Java.Lang/Thread.cs Resolved
Comment thread src/Mono.Android/Java.Lang/Thread.cs Resolved
simonrozsival added a commit that referenced this pull request Nov 10, 2026
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]>
simonrozsival added a commit that referenced this pull request Nov 11, 2026
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]>
@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13312

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Review complete; CI pending. Reviewed all 12 changed files at 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

Comment thread src/Mono.Android/Java.Lang/Thread.cs Resolved
Comment thread src/Mono.Android/Java.Lang/Thread.cs Resolved

@dalexsoto dalexsoto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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: RemoveCallbacks calls Remove (action, this, …) without retire: true.
  • View.cs:47-65: Post/PostDelayed never call CompletePost, so posted stays false for View registrations. Passing retire: true alone would therefore still not retire them.
  • src/Mono.Android/Java.Lang/Thread.cs: canRetire (line 117) requires retire && runnable.posted, and Unregister() otherwise runs only from Dispose(bool) (lines 89-96), i.e. after finalization. Handler.RemoveCallbacks cannot 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.

@simonrozsival simonrozsival removed the ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). label Nov 13, 2026
@simonrozsival

Copy link
Copy Markdown
Member Author

@dalexsoto Fixed the View cancellation scaling finding in f27d55c.

View.Post(Action) and PostDelayed(Action) now use the same CompletePost helper as Handler, and View.RemoveCallbacks(Action) requests retirement of acknowledged posts. In-flight posts remain registered, and cancellation still does not dispose runnable peers. Drawable scheduling/unscheduling behavior is unchanged.

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:

  • NUGET_PACKAGES="$PWD/bin/nuget" make leeroy — passed.
  • Build/install and device tests below — 50 passed, 0 failed, 0 skipped in each of four configurations. Existing build/trim/AOT warnings remain.
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:

CONFIG PROPERTIES Result
Debug -p:PublishAot=false Build passed; 50/50 tests passed
Release -p:PublishAot=false -p:AndroidPackageFormats=aab Build passed; 50/50 tests passed
Release -p:PublishAot=false -p:TestsFlavor=NoAab -p:AndroidPackageFormat=apk Build passed; 50/50 tests passed
Release -p:PublishAot=true -p:TestsFlavor=NativeAOT Build passed; 50/50 tests passed

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 37.99.0.296/9124cba stamp; the four-case red/green run confirms the rebuilt View implementation is exercised rather than relying on that stamp as revision evidence.

@simonrozsival simonrozsival changed the title [Mono.Android] Cancel all repeated Action callbacks [Mono.Android] Share one Runnable per Action Nov 13, 2026
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]>
@simonrozsival
simonrozsival force-pushed the simonrozsival-fix-repeated-action-callback-cancellatio branch from 2795e6e to bc03fd1 Compare November 13, 2026 10:13
@simonrozsival simonrozsival changed the title [Mono.Android] Share one Runnable per Action [Mono.Android] Cancel every pending post of an Action Nov 13, 2026
@simonrozsival

Copy link
Copy Markdown
Member Author

@jonathanpeppers @dalexsoto I rewrote this PR from scratch as a single commit, bc03fd1, rebased onto current main. The diff is now +114/−94 across 11 files, down from about 1,100 lines. This supersedes my f27d55c reply above and the explanations in the earlier (now resolved) review threads.

What changed

Before (previous revisions): each post still created a new RunnableImplementor, and managed code tracked all of them:

  • a ConditionalWeakTable<Action, HashSet<WeakReference<RunnableImplementor>>> registry protected by a Lock;
  • weak JNI global references to the owner, the drawable context and the token for each registration, compared with JNIEnv.IsSameObject;
  • a posted flag with CompletePost(bool), plus "retirement" after successful removal, to avoid quadratic re-scans;
  • 44 dedicated tests, about 1,000 lines.

Now: one RunnableImplementor per Action, created with ConditionalWeakTable.GetValue() and reused for every removable Handler/View/Drawable post. Remove became a lookup (Find), and the callers simply pass that one runnable to the Java removeCallbacks()/unscheduleDrawable(). Shared runnables are no longer disposed in Run(), on removal, or after a failed post. Their lifetime is tied to the Action through the existing table. Non-removable uses (new Thread (Action), RunOnUiThread, …) are unchanged.

Why this is better

  • Java already does the matching. Handler.removeCallbacks(r[, token]) removes every queued message whose callback is r, optionally filtered by token. View.removeCallbacks() and Drawable.unscheduleDrawable(who, r) likewise scope by view and drawable. Sharing one runnable means every post is found, and handler/view/token/who isolation comes from Android instead of our own reimplementation.
  • Less state, fewer moving parts. There are no per-post registrations, weak global references, locks, posted flags, or retirement logic. That removes the races and edge cases the earlier tests had to guard against: cancellation before Post returns, disposed wrapper aliases, and unrelated-token scans.
  • Cheaper. Posting no longer allocates a new Java peer and global reference per call. Cancellation is one native call, regardless of how many times the Action was posted.
  • @dalexsoto's View finding no longer applies. No registrations accumulate, so nothing needs retiring, and repeated View.Post/RemoveCallbacks is constant cost per operation.

Tradeoffs

  • Nested drawables: if the same Action is scheduled for two children of one LayerDrawable, unscheduling it for one child now also cancels it for the other, because both go through the same outer callback with the same Runnable. That is Java's behavior for a shared Runnable. main already cancels only the most recent post here, which may belong to the wrong child.
  • Lifetime: the shared runnable stays alive as long as its Action is alive. That is one peer per live, previously posted Action, not one per post. ExecutedActionCallbacksAreCollectible verifies that executed Actions and their runnables are collected.

Tests and validation

Tests are now two focused HandlerTest cases:

  • RemoveCallbacksCancelsEveryPendingPost: repeated post/cancel, with other handlers and tokens unaffected, and posts after cancellation still running.
  • ExecutedActionCallbacksAreCollectible: executed Actions are garbage-collected.

The full Mono.Android.NET-Tests suite passed with 0 failures in Debug, trimmed AAB, trimmed APK and NativeAOT. Details are in the PR description. Those runs used the same change on aa91d32. The rebase onto ec3c1cc brought in 19 commits that don't touch the changed files, and I haven't rerun the tests since.

All review threads are resolved. Could you take another look?

@dalexsoto dalexsoto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I understand the accepted nested LayerDrawable tradeoff, but sharing one runnable per Action also loses isolation without nesting:

  1. 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.
  2. 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.
  3. 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]>
@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13312

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Needs Changes

Reviewed all 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

Comment thread src/Mono.Android/Android.Views/View.cs Resolved
Comment thread src/Mono.Android/Java.Lang/Thread.cs Resolved
simonrozsival and others added 2 commits November 17, 2026 10:40
…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]>
@simonrozsival
simonrozsival dismissed jonathanpeppers’s stale review November 17, 2026 09:50

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).

@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13312

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Needs Changes

Findings: 1 ❌ error, 0 ⚠️ warnings, 0 💡 suggestions. The inline finding identifies a stale View/drawable scheduling association that lets a later 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

Comment thread src/Mono.Android/Java.Lang/Thread.cs Resolved
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]>
simonrozsival and others added 7 commits November 19, 2026 22:08
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]>
@simonrozsival
simonrozsival force-pushed the simonrozsival-fix-repeated-action-callback-cancellatio branch from 6a9c60b to 96b5b60 Compare November 21, 2026 07:02
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]>
@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13312

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Needs Changes

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

simonrozsival and others added 4 commits November 23, 2026 16:26
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]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[net11.0-android] Handler.RemoveCallbacks(Action) leaves earlier repeated posts queued, retaining managed objects and JNI references

4 participants