Skip to content

[tests] Bound SharedPreferences asynchronous write pressure - #13310

Merged
simonrozsival merged 1 commit into
mainfrom
simonrozsival-remaining-device-crashes
Oct 29, 2026
Merged

simonrozsival merged 1 commit into
mainfrom
simonrozsival-remaining-device-crashes

Conversation

@simonrozsival

Copy link
Copy Markdown
Member

Context: #13278
Related: #13168
Original regression: #9136

Why change this test?

The flakiness inventories include early Java-heap exhaustion while Android.ContentTests.SharedPreferencesTest.PutAndGetManyValues() is active. The original test combines two useful obligations—roundtripping 1,000 distinct values and exercising 1,000 independent preference/editor binding cycles—but also accidentally creates a backlog of asynchronously retained, increasingly large map snapshots.

An independent reproduction on an owned API29 arm64 emulator with a measured 16,777,216-byte application Java heap fails with the unchanged test body:

Original workload Started / passed Outcome
SharedPreferences alone, fresh app data 1 / 0 Fatal queued-work OOM, self SIG9
Exact 16-test predecessor prefix, fresh app data 17 / 16 Same fatal OOM/SIG9
Same prefix, verified persisted 1,000-key preferences 17 / 16 Same fatal OOM/SIG9

The queued-work thread fails while trying to allocate the linked-list copy needed to begin draining work:

java.util.LinkedList.clone
android.app.QueuedWork.processPendingWork
...
FATAL EXCEPTION: queued-work-looper
java.lang.OutOfMemoryError
Process: Sending signal. ... SIG: 9

These runs fail before upload tests start. Fresh state already fails, so neither persisted preferences nor contamination from preceding tests is necessary. Persisted state amplifies the pressure. These are independent local reproductions, not evidence that every historical CI crash with this active test has the same cause.

What owns the memory?

In the Android 10 implementation, SharedPreferencesImpl.commitToMemory() copies the complete preferences map whenever a disk write is already in flight, before checking whether a value has changed. Each outstanding MemoryCommitResult retains its snapshot through the queued runnable/finisher. QueuedWork delays asynchronous processing and copies the pending work list before draining it.

Consequently, 1,000 overlapping writes to a growing map can retain 1 + 2 + ... + 1000 = 500,500 entry nodes, not just the final 1,000 values. Starting with an already populated 1,000-key file can approach 1,000,000 retained entries even when rewriting identical values.

The investigation measured the owners, rather than attributing the heap to the final failed allocation:

Evidence Observation
Sampled original fresh workload 960 queued maps retaining 461,280 entries near the 16MiB limit
Sampled persisted 1,000-key workload 448 queued maps retaining 448,000 entries
Actual application HPROF Strong QueuedWork runnable/finisher paths to 512 commit results/maps retaining 131,328 entries
Diagnostic-only queue drain Zero strongly reachable commit results afterwards; 488 remaining instances were uncollected garbage, not evidence of permanent retention
Java-only framework control Persisted-state OOM also reproduces without .NET or managed JNI owners
Sampled JNI lifetime counters Locals and weak globals stay zero; globals remain flat after warmup: 26 alone, 86 with the prefix

This supports a framework-owned asynchronous write backlog as the mechanism for this reproduction, not a new permanent JNI-reference leak. The diagnostic drain and heap dumps perturb scheduling and are not part of the fix. The linked Android 10 sources and the corresponding android10-gsi files have the same relevant implementation; they are version-family references, not a claim to possess the emulator image's exact source checkout.

Preserve both regression obligations

Batching everything into one editor would remove the repeated-editor coverage introduced by #9136 for API23 local-reference-table overflow. Instead, split the obligations:

  1. Keep PutAndGetManyValues(): put all 1,000 distinct key/value pairs through one editor, call asynchronous Apply(), and retain every original readback assertion and repeated preference acquisition on readback.
  2. Add RepeatedEditorsDoNotLeakReferences(): perform all 1,000 independent GetPreferences/Edit/PutString/Apply/readback/disposal cycles against a separate preference file with one repeatedly updated key. Values change on every iteration, so these are not only no-op writes. Move the original API23 regression comment here and link [Mono.Android] fix leaking lrefs in TypeManager #9136.

The repeated binding/wrapper churn remains above the original 512-local-reference threshold, while every map snapshot has bounded cardinality. The change does not add forced GC, sleeps, a queue-drain dependency, Commit(), a larger heap, fewer iterations, runtime changes, or committed diagnostic filters/logging.

Validation of the final patch

The Release local SDK was prepared and built with make prepare CONFIGURATION=Release and make leeroy CONFIGURATION=Release; both passed. The final test source was then freshly rebuilt for both NativeAOT and CoreCLR. All packages used the same final fixture content, not stale prototype outputs. Application runtime was .NET 11.0.0-preview.7.26381.103 on API29 arm64-v8a, with the same 16MiB Java heap.

Runtime Workload Fresh passed / failed / skipped Verified persisted passed / failed / skipped
NativeAOT SharedPreferences alone 2 / 0 / 0 2 / 0 / 0
NativeAOT Actual 16-test prefix plus SharedPreferences 18 / 0 / 0 18 / 0 / 0
CoreCLR SharedPreferences alone 2 / 0 / 0 2 / 0 / 0
CoreCLR Actual 16-test prefix plus SharedPreferences 18 / 0 / 0 18 / 0 / 0
NativeAOT Unfiltered suite, stock runtime exclusions 852 / 0 / 7 852 / 0 / 7
CoreCLR Unfiltered suite, stock runtime exclusions 991 / 0 / 7 990 / 0 / 8

Both changed tests positively passed in all 12 launches; none had process crashes. Persisted controls explicitly seeded and re-read all 1,000 values plus the separate one-key editor file before execution. Counts were cross-checked against actual TRX outcomes, instrumentation result bundles, and launch-PID-scoped test events, not just host exit status.

The eight focused controls total 80 passing case events, including the prefix cases. An earlier two-test prototype passed 40/40; that is separate investigation evidence, not counted as final-patch validation. Focused selection used a temporary runner-only class filter with the exact final fixture. That filter was removed, and the final one-file patch was rebuilt again before each runtime's unfiltered suite.

The build/install command was run with each PublishAot value (true for NativeAOT, false for CoreCLR); both passed. Machine-local SDK/JDK paths and per-build binlog destinations are omitted here:

./dotnet-local.sh build '-t:Rebuild;Install' -c Release \
  tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj \
  -p:RuntimeIdentifier=android-arm64 -p:PublishAot=true -p:IncludeCategories= \
  '-p:AdbTarget=-s emulator-5598' -p:Device=emulator-5598

./dotnet-local.sh build '-t:Rebuild;Install' -c Release \
  tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj \
  -p:RuntimeIdentifier=android-arm64 -p:PublishAot=false -p:IncludeCategories= \
  '-p:AdbTarget=-s emulator-5598' -p:Device=emulator-5598

Fresh full-suite runs followed adb -s emulator-5598 shell pm clear Mono.Android.NET_Tests. Persisted full-suite runs followed verified XML seeding instead. The unfiltered device command was:

adb -s emulator-5598 shell am instrument -w -r \
  Mono.Android.NET_Tests/xamarin.android.runtimetests.TestInstrumentation

Existing runtime/category exclusions remain unchanged; excluded cases are not claimed as executed. The CoreCLR persisted run additionally skipped AndroidMessageHandlerIntegrationTests.CancelRequestViaProxy with its existing “Test timed out waiting for task. Task status: WaitingForActivation” message; it is not counted as a pass. The owned emulator was stopped afterwards.

API23, MonoVM, other ABIs and Android versions were not run. The current test package has minSdk29, and the installed emulator cannot execute historical x86_64 images on this arm64 host. This preserves the API23 regression's intent without claiming to have revalidated that original environment. The results address this SharedPreferences workload defect only; they do not establish historical x86_64 equivalence or resolve the other crash groups in #13278/#13168.


Pull Request
title and
description
should follow the
commit-messages.md workflow documentation, and in particular should include:

  • Useful description of why the change is necessary.
  • Links to issues fixed
  • Unit tests

Context: #13278
Related: #13168
Original regression: #9136

SharedPreferencesTest.PutAndGetManyValues() independently reproduces a fatal queued-work Java OOM on API29 arm64 NativeAOT with a measured 16MiB application heap. The original body fails alone with 1 start/0 passes and after the real 16-test prefix with 17 starts/16 passes, before uploads execute. Fresh state already fails; a persisted 1,000-key file amplifies the pressure.

Android's SharedPreferencesImpl copies the complete map when another disk write is in flight. Its queued MemoryCommitResults retain the copies: the original workload reaches 960 queued maps/461,280 entries fresh, or 448 maps/448,000 entries persisted. Actual heap-root paths and a Java-only reproduction identify framework asynchronous write retention; flat JNI counts and zero strongly rooted commit results after a diagnostic drain do not support a new permanent JNI-leak claim.

Batch all 1,000 distinct values in one asynchronous Apply while preserving the original 1,000 readback assertions. Separately perform 1,000 independent preference/editor/Apply/readback/disposal cycles using a one-key preference file. Keep the #9136/API23 local-reference regression comment with that repeated-editor coverage. A batch-only replacement would lose its binding-cycle regression intent.

Freshly rebuilt final-fixture controls pass alone and after the prefix with fresh and verified persisted preferences on NativeAOT and CoreCLR: 80/80 case events, separate from the earlier prototype. Rebuild the final patch without the temporary selection harness and run the stock unfiltered suites at the same 16MiB: NativeAOT 852 passed/0 failed/7 skipped in each state; CoreCLR 991/0/7 fresh and 990/0/8 persisted. The extra CoreCLR skip is the existing proxy-cancellation timing skip.

Do not change the runtime, increase the heap, reduce iterations, force GC, sleep, or replace Apply with Commit. API23, MonoVM and other ABIs remain untested; these independent API29 arm64 results do not resolve every crash in the broader flakiness inventories.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: 9b182585-cef5-4f98-b5c5-e10ca24a48b7
Copilot AI balanced review requested due to automatic review settings October 29, 2026 12:26

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.

🟢 Approval recommended

No active review issues are blocking the SharedPreferences test changes.

No open issues 🎉

What changed in this PR

This PR reduces asynchronous write memory pressure in the SharedPreferences tests while preserving value-roundtrip coverage and the repeated-editor regression coverage from #9136.

Changes:

  • Batches 1,000 distinct values into one editor and one Apply(), retaining all readback assertions.
  • Adds 1,000 independent preference/editor cycles using a separate, single-key preference file to keep map snapshots small.
  • Moves the API23 local-reference-overflow regression comment to the repeated-editor test.
File Description
tests/​Mono.Android-Tests/​Mono.Android-Tests/​Android.Content/​SharedPreferencesTest.cs Separates bulk value roundtrips from repeated-editor coverage to bound asynchronous snapshot memory.

Review effort: Balanced

@simonrozsival simonrozsival added the flaky-ci Intermittent CI failures and work to improve CI reliability label Oct 29, 2026
@simonrozsival

Copy link
Copy Markdown
Member Author

/review

@simonrozsival simonrozsival added the ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable). label Oct 29, 2026
@github-actions

github-actions Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13310

@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: looks good; no blocking findings. Findings: 0 ❌ errors, 0 ⚠️ warnings, 1 💡 optional inline documentation suggestion.

The split retains all 1,000 distinct-value readbacks and the 1,000 independent preference/editor/disposal cycles from #9136. The separate fixed-key workload bounds map cardinality while changing each value, without replacing Apply() or reducing the stress count. I reviewed the full changed file, its test-project inclusion, and the original regression diff; the implementation matches the stated intent.

CI: All 42 GitHub check runs report success, including the aggregate dotnet-android check for Azure build 1654256. Independent Azure build/timeline verification remains incomplete: az devops invoke requires authentication, and the public REST request was denied by environment permissions. This is not a finding against the patch, but I cannot independently certify full pipeline health. The device results in the description were not rerun during this review.

Generated by Android PR Reviewer for #13310 · copilot · gpt61 · 23.1 AIC · ⌖ 4.21 AIC · ⊞ 19.3K
Comment /review to run again

@simonrozsival

Copy link
Copy Markdown
Member Author

@dalexsoto review

@simonrozsival
simonrozsival merged commit 87b7a75 into main Oct 29, 2026
42 checks passed
@simonrozsival
simonrozsival deleted the simonrozsival-remaining-device-crashes branch October 29, 2026 16:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

flaky-ci Intermittent CI failures and work to improve CI reliability ready-to-review This PR is ready to review/merge, I think any CI failures are just flaky (ignorable).

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants