Skip to content

[tests] Synchronize cancellation and native loads - #13694

Draft
simonrozsival wants to merge 7 commits into
mainfrom
dev/simonrozsival/timing-cancellation-retries
Draft

simonrozsival wants to merge 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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
`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 <[email protected]>
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 <[email protected]>
@jonathanpeppers
jonathanpeppers force-pushed the dev/simonrozsival/timing-cancellation-retries branch from b78f226 to 44f3fd5 Compare November 23, 2026 14:55

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant