Skip to content

[tests] Synchronize cancellation and native loads - #13694

Merged
simonrozsival merged 7 commits into
mainfrom
dev/simonrozsival/timing-cancellation-retries
Nov 28, 2026
Merged

simonrozsival merged 7 commits into
mainfrom
dev/simonrozsival/timing-cancellation-retries

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

Cancellation and retry tests need to reach a particular state, not wait for a guessed amount of time. Replace scheduler-dependent delays with observations of the process, thread, retry, or polling state.

Keytool cancellation

Have the fake keytool signal that it has started before cancelling its task, so the test actually exercises cancellation of a running process. On Windows the batch file uses a script-relative marker, avoiding code-page corruption of a non-ASCII absolute path.

Native-library load contention

Wait until the main thread has entered its wait and the competing Java threads are blocked in Runtime.loadLibrary0 before continuing the nested load. This establishes the intended contention rather than assuming a short sleep scheduled all participants.

Directory deletion retries

Stop racing a background thread that releases a file lock after a fixed delay. Each retry test now checks one behavior:

  • DirectoryInUseWithRetry (Windows): the first deletion fails on a real locked file, the test releases the lock, and the default policy succeeds on the first retry.
  • DirectoryInUseWithCustomRetry: three injected sharing violations, then success after exactly four attempts.
  • DirectoryInUseWithNoRetry: with RetryAttempts=0, one injected sharing violation fails the task without a retry.

Emulator boot cancellation

Cancel only after emulator boot polling starts, then require the operation to finish under a generous hang watchdog. The test no longer conflates scheduler speed with cancellation correctness.

Worker JNI library load diagnostics

ExemptJniLibraryLoadsOnWorkerThreadWithBlockedMainThread(False) still failed once in CI with this change (build 1693158): no completion or failure marker appeared within 90s, and the automatic retry passed. Because the job then succeeded, no logcat was uploaded. The cause is unconfirmed; local runs on an API 29 emulator (24 test runs, 500 relaunches) did not reproduce it.

Instead of changing the assertions, make the next occurrence diagnosable:

  • The app logs WORKER_JNI_LIBRARY_LOAD_PROGRESS:<step> markers on each participating thread, and the assertion messages include the last marker seen.
  • A Java watchdog in JniLoadProbe dumps every Java thread's state and stack after 65s if the activity has not finished. This works even when managed code cannot run. The worker-join timeout path dumps the same before logging its existing failure marker.
  • On failure the host runs bounded, best-effort adb commands (pidof, ps -T, filtered dumpsys activity activities, logcat -d), attaches the full logcat, and writes a filtered excerpt to standard output. Command timeouts, non-zero exits, and exceptions are reported in that output instead of being thrown.

Standard output is used because CI task logs keep a failed first attempt's standard output even when the retry passes; build 1693158's task log contains the first attempt's assertion and standard output ahead of the retry results.

Validation

Validation was run with all five layers applied on macOS and an API 35 arm64 emulator; intermediate branch heads were not built separately.

  • ./dotnet-local.sh test bin/TestDebug/net11.0/Xamarin.Android.Build.Tests.dll --filter 'FullyQualifiedName~RemoveDirTests|Name~CancelStopsKeytool|Name~BuilderDoesNotWaitForInheritedRedirectedOutput' -v minimal — passed: 10 passed and 3 platform-skipped on macOS.
  • ./dotnet-local.sh test bin/TestDebug/Xamarin.Android.Tools.AndroidSdk-Tests.dll --filter 'Name~CancellationToken_AbortsBoot' -v minimal — passed (1 test).
  • ADB_TARGET='-s emulator-5558' ANDROID_SERIAL=emulator-5558 ./dotnet-local.sh test bin/TestDebug/MSBuildDeviceIntegration/net11.0/MSBuildDeviceIntegration.dll --filter '(Name~UnknownSystemLibraryLoadsWithoutMainThreadDispatch|Name~ExemptJniLibraryLoadsOnWorkerThreadWithBlockedMainThread|(Name~CheckTimeZoneInfoIsCorrectWithSlicer&Name~Europe/Prague))' --logger 'console;verbosity=normal' — passed (5 device cases, including 3 native-load cases and 2 timezone cases).
  • Worker JNI diagnostics, on an API 29 arm64 emulator: ADB_TARGET='-s emulator-5556' ./dotnet-local.sh test bin/TestDebug/MSBuildDeviceIntegration/net11.0/MSBuildDeviceIntegration.dll --filter "Name~ExemptJniLibraryLoadsOnWorkerThreadWithBlockedMainThread" — passed (2 tests), with all progress markers logged in order. With a temporary, uncommitted hang in the first attempt only, dotnet run build-tools/automation/scripts/RunSlicedTests.cs -- ... --retry true printed the first attempt's failure with its last progress marker, the adb diagnostics, and the watchdog's Java thread dump, then passed on retry (exit code 0).
  • The Windows batch-file marker and real locked-directory sharing violation could not be exercised on this macOS host.

@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 #13694

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

Code assessment: no merge-blocking issues found. Reviewed all four changed files in full against the actual PR base (dev/simonrozsival/timing-build-stability), including the deletion retry implementation, emulator polling/cancellation flow, native loader coordination, and host process/logcat helpers. Findings: 0 errors, 0 warnings, 1 inline suggestion about qualifying the Java blocked-state observation throughout the polling window.

The process-start marker and explicit polling handoff improve cancellation coverage without guessed sleeps. The retry tests now verify exact attempt counts and the zero-retry failure path, while the JNI diagnostics retain first-attempt evidence without replacing the original assertions.

CI verification is incomplete. All 38 GitHub checks report success, including the aggregate dotnet-android check for Azure build 1693601. Direct Azure build/timeline queries were attempted but unavailable in this environment: the build query required authentication and the timeline query failed during CLI initialization. Therefore I cannot independently confirm the Azure build result or first-attempt test history, and am withholding an unconditional ✅ LGTM verdict. No local build or device tests were run as part of this read-only review; the validation reported in the PR description was not independently reproduced.

Generated by Android PR Reviewer for #13694 · copilot · gpt61 · 43.2 AIC · ⌖ 4.26 AIC · ⊞ 21K
Comment /review to run again

}
try {
bool observed = SpinWait.SpinUntil (
() => !managedThread.IsAlive || javaThread.GetState ().Equals (Java.Lang.Thread.State.Blocked),

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.

🤖 💡 Testing — Could the polling predicate wait for both Blocked and a java.lang.Runtime.loadLibrary0 stack frame, rather than checking the stack only after the first blocked-state observation? Currently any incidental Java monitor contention ends the wait, and a stack without that frame immediately fails the test even if the reader would subsequently reach the intended loader monitor within the 20-second deadline. Keeping the stack qualification inside the bounded polling loop would make the synchronization match the exact state this test requires; thread termination should still end the wait as a failure.

Rule: Synchronize on the intended state, not incidental thread activity.

Base automatically changed from dev/simonrozsival/timing-build-stability to main November 23, 2026 14:55
simonrozsival and others added 7 commits November 23, 2026 08:55
Have the fake tool signal that it has started so cancellation exercises the running process without a fixed startup delay. Use a script-relative marker path on Windows to avoid embedding a possibly non-ASCII absolute path in the batch file.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Observe the main thread entering its wait before making the worker P/Invoke, and wait for competing Java threads to block in Runtime.loadLibrary0 before continuing the nested load, instead of assuming a short sleep is enough. Report a failure if contention is not observed.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Exercise default and custom retry counts without depending on the lock holder being scheduled within the retry window. Simulate a sharing violation on Unix, where deleting an open file succeeds, and keep the directory locked through every configured retry.

Assert the exact number of attempts, including the zero-retry case, which must fail without deleting the directory.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Observe the polling phase before cancellation and use a generous hang watchdog instead of comparing elapsed time with a tight threshold.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
`NativeLibraryLoadTests.ExemptJniLibraryLoadsOnWorkerThreadWithBlockedMainThread(False)`
failed once in CI (AzDO build 1693158, "MSBuild+Emulator 3"): neither
`WORKER_JNI_LIBRARY_LOAD_COMPLETED` nor `WORKER_JNI_LIBRARY_LOAD_FAILED`
appeared within the 90s `MonitorAdbLogcat()` timeout, and the automatic
retry passed.  The job succeeded, so no logcat artifact was uploaded,
and the only evidence was the assertion message.  The cause remains
unconfirmed: local runs on an API 29 emulator did not reproduce it.

Make the next occurrence diagnosable without changing what the test
asserts:

  * The app logs `WORKER_JNI_LIBRARY_LOAD_PROGRESS:<step>` markers on
    the main, worker, callback, and reader threads, and the assertion
    messages report the last marker seen.

  * `JniLoadProbe` starts a Java watchdog thread which, if the activity
    has not finished after 65s, logs every Java thread's state and stack
    via `Thread.getAllStackTraces()`.  This works even if managed code
    cannot run.  The worker-join timeout path dumps the same information
    before logging its existing failure marker.

  * On failure the host runs bounded, best-effort `adb` commands
    (`pidof`, `ps -T`, filtered `dumpsys activity activities`, and
    `logcat -d`), saves the full logcat as an attachment, and writes a
    filtered excerpt to the test's standard output.  Command timeouts,
    non-zero exit codes, and exceptions are reported in that output
    rather than thrown, so they cannot mask the original assertion.

Diagnostics go to standard output because CI task logs keep the
standard output of failed first attempts even when the retry passes;
in build 1693158 the first attempt's assertion and standard output
appear in the task log before the retry's results.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Replace the shared AssertRetriesLockedDirectory helper with explicit
tests: a Windows-only test that releases a real file lock after the
first failed attempt, and platform-independent tests that inject
sharing violations to verify the custom and zero retry counts.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@jonathanpeppers
jonathanpeppers force-pushed the dev/simonrozsival/timing-cancellation-retries branch from b78f226 to 44f3fd5 Compare November 23, 2026 14:55
@simonrozsival
simonrozsival marked this pull request as ready for review November 27, 2026 21:16
Copilot AI balanced review requested due to automatic review settings November 27, 2026 21:16
@simonrozsival

Copy link
Copy Markdown
Member Author

@dalexsoto review

@simonrozsival
simonrozsival enabled stacked auto-merge (squash) November 27, 2026 21:17

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.

🔵 Needs a closer look

The unexplained JNI-load CI hang and runtime-dependent coordination require human review, while Windows cancellation and locked-directory retries remain unvalidated.

No open issues 🎉

What changed in this PR

This PR makes cancellation, retry, and native-library load tests more deterministic by waiting for observable states instead of fixed delays. It also adds diagnostics for intermittent worker JNI library load hangs without changing the expected results.

Changes:

  • Synchronize cancellation with keytool startup and emulator boot polling.
  • Establish native-load contention explicitly and add progress markers, Java thread dumps, and bounded host diagnostics.
  • Replace timed directory-lock release with controlled retry scenarios, including zero retries.
File Description
tests/​Xamarin.Android.Tools.AndroidSdk-Tests/​EmulatorRunnerTests.cs Cancel after boot polling starts, with a bounded completion wait.
tests/​MSBuildDeviceIntegration/​Tests/​NativeLibraryLoadTests.cs Observe thread contention and collect diagnostics for worker JNI load failures.
src/​Xamarin.Android.Build.Tasks/​Tests/​Xamarin.Android.Build.Tests/​Tasks/​RemoveDirTests.cs Make retry scenarios deterministic and clean up test directories.
src/​Xamarin.Android.Build.Tasks/​Tests/​Xamarin.Android.Build.Tests/​Tasks/​AndroidCreateDebugKeyTests.cs Wait for a script-generated startup marker before cancelling keytool.

Review effort: Balanced

@dalexsoto

Copy link
Copy Markdown
Member

In response to @simonrozsival's request: I still need to finish the Windows marker-directory path in AndroidCreateDebugKeyTests.cs, the cross-platform retry behavior of RemoveDirFixed used by RemoveDirTests.cs, and the timed Task.Wait contract in NativeLibraryLoadTests.cs. The discussion output was also truncated to 160 characters per body, so those full decision reads and the final pass remain outstanding. These are gaps in my review coverage, not defects identified in the PR.

@PeppersMuse PeppersMuse left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Reviewed the diff, the PR description, and both Copilot reviews. Verified the keytool marker-file handshake (script-relative marker on Windows, File.Delete of stale markers, SpinUntil distinguishing "never started" from "started then cancelled"), the directory-retry attempt counts against RemoveDirFixed (RetryAttempts=3 ⇒ exactly 4 attempts, 0 ⇒ 1 attempt; 0x80070020 is the sharing violation the task retries on), the native-load contention changes (the old 150 ms timing check removal is a genuine improvement; main-thread wait detection via ThreadState.WaitSleepJoin is correct), the 65 s Java watchdog vs 60 s worker-join timeout ordering, and the emulator-boot cancellation flow (deviceQueries == 2 genuinely means polling started; the catch … when filter correctly excludes user cancellation). One real flakiness risk below — the same point Copilot's inline comment raised, verified independently with the mechanism spelled out.

return false;
}
try {
bool observed = SpinWait.SpinUntil (

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

SpinUntil exits on the first Blocked observation, and the loadLibrary0 stack check runs exactly once afterwards — so this can spuriously fail the test. The callback thread's started.Wait() returns the instant the reader thread sets the event, before that thread has called Progress("…PInvokeStarting") or entered Runtime.loadLibrary0. In that window the reader can legitimately be Blocked on an incidental Java monitor (log-call / class-init locks), so SpinUntil exits, the stack has no loadLibrary0 frame, and the method returns false — failing ExemptJniLibraryLoadsOnWorkerThreadWithBlockedMainThread as "did not block in Java while JNI_OnLoad was active" even though the thread would have reached the loader monitor well within the 20 s deadline. The Progress() calls between started.Set() and the P/Invoke widen this window. The post-loop GetState() re-read is also a second sampling point that can observe a transient state different from the one that ended the spin.

Fix: move the stack-frame qualification inside the SpinUntil predicate — poll until Blocked and a loadLibrary0 frame is present, keeping !IsAlive as the failure exit. Test-only flakiness (not a product bug), and the PR's validation (24 runs / 500 relaunches) didn't hit it, so the probability is low — but the race is real.

@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 at 44f3fd5, all four changed test files. The tests now wait for observed state instead of fixed delays: the keytool start marker, the main thread in WaitSleepJoin, readers BLOCKED inside Runtime.loadLibrary0, the second ListDevices poll, and injected DeleteDirectory failures. The new diagnostics are bounded and can't hide the original assertion. The JNI signatures ((J)V, (Ljava/lang/String;)V, ()V) match the Java probe, the string local ref is released, and the watchdog is stopped in finally. The simulated 0x80070020 failures go through RemoveDirFixed's HResult retry path, which is the same on every platform, so the retry tests that are no longer Windows-only are valid on macOS/Linux too.

On the open note about WaitForJavaLoadBlock (r4724247784): the window is real. started.Set() runs before Progress(...) and the P/Invoke, and the loadLibrary0 frame is checked only once after the first BLOCKED sample. A false negative needs the reader to be blocked on a different Java monitor during that short window, and it would fail loudly via CallbackError rather than pass silently, so I don't consider it blocking. If it shows up in CI, polling until the frame appears or the deadline passes would close it.

@simonrozsival
simonrozsival merged commit 4347e8c into main Nov 28, 2026
40 checks passed
@simonrozsival
simonrozsival deleted the dev/simonrozsival/timing-cancellation-retries branch November 28, 2026 03:18
simonrozsival added a commit that referenced this pull request Nov 28, 2026
#13694 added NUnit's TestContext.Out and TestContext.AddTestAttachment;
use Console.Out and the instance TestContext.AddResultFile instead.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
simonrozsival added a commit that referenced this pull request Nov 29, 2026
#13694 added NUnit's TestContext.Out and TestContext.AddTestAttachment;
use Console.Out and the instance TestContext.AddResultFile instead.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants