Skip to content

[tests] Retire allocation contexts before measuring allocations - #13729

Merged
simonrozsival merged 3 commits into
mainfrom
simonrozsival-fix-disabled-tracing-alloc-flake
Nov 24, 2026
Merged

simonrozsival merged 3 commits into
mainfrom
simonrozsival-fix-disabled-tracing-alloc-flake

Conversation

@simonrozsival

Copy link
Copy Markdown
Member

Fixes: #13726

DisabledTracingDoesNotAllocateDuringReferenceOperations intermittently reports allocations in CI, for example 2,432 bytes above its initial counter value. CoreCLR can void a thread's allocation context during a background GC, causing GC.GetAllocatedBytesForCurrentThread() to include the unused remainder even when the thread has not allocated anything.

Force a full blocking collection immediately before sampling the counter in the reference tracing and cached typemap lookup tests. This retires the allocation context before the allocation-free loops. The exact-zero assertions remain unchanged and still detect genuine allocations.

Validation on an API 29 arm64 emulator with Debug CoreCLR:

  • ./dotnet-local.sh build -t:Install -c Debug -p:Device=emulator-5584 -p:IncludeCategories=ReferenceTracing tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -v:q -nologo — passed.
  • (cd tests/Mono.Android-Tests/Mono.Android-Tests && ../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --no-build -c Debug -p:Device=emulator-5584 -p:IncludeCategories=ReferenceTracing) — passed, 10/10.
  • With temporary instrumentation of both test methods, ./dotnet-local.sh build -t:Install -c Debug -p:Device=emulator-5584 -p:IncludeCategories=AllocationStress tests/Mono.Android-Tests/Mono.Android-Tests/Mono.Android.NET-Tests.csproj -v:q -nologo — passed. The instrumentation is not included in the PR.
  • With that instrumentation, (cd tests/Mono.Android-Tests/Mono.Android-Tests && ../../../dotnet-local.sh test Mono.Android.NET-Tests.csproj --no-build -c Debug -p:Device=emulator-5584 -p:IncludeCategories=AllocationStress) — passed three runs, two tests per run. Across 6,000 interleaved measurements under background-GC pressure, the original reference test failed 5 times; the explicit blocking-GC variant failed 0 times. The typemap test reported 0 failures in either variant. A deliberately injected 64-byte allocation was detected 60/60 times per test with the explicit variant.

The full device suite was not rerun with the final explicit overload; the focused device and stress runs above cover the changed tests.

simonrozsival and others added 2 commits November 23, 2026 15:41
Fixes: #13726

`ManagedObjectReferenceManagerTests.DisabledTracingDoesNotAllocateDuringReferenceOperations` intermittently failed on the Debug CoreCLR device lane with small, varying deltas:

    Expected: 2059520
      But was:  2061240

Other builds showed deltas of 280 and 2432 bytes.

The code under test does not allocate. The extra bytes come from CoreCLR's allocation accounting. `GC.GetAllocatedBytesForCurrentThread ()` returns `alloc_bytes - (alloc_limit - alloc_ptr)` for the thread's allocation context. At the end of a background GC's mark phase, `gc_heap::background_mark_phase ()` calls `repair_allocation_contexts (FALSE)`. That calls `void_allocation ()`, which sets every thread's `alloc_ptr` and `alloc_limit` to 0 without subtracting the unused remainder from `alloc_bytes`, unlike `fix_allocation_context ()`. When a background GC finishes marking during the measured loop, the measuring thread's count jumps by whatever was left in its allocation context, up to one allocation quantum, even though the thread allocated nothing.

This was reproduced on an API 35 arm64 emulator with a background thread that churns allocations and requests non-blocking gen2 collections. About 20 of 300 rounds of 1000 iterations reported roughly 7.7–8.3 KB each, and the jump landed on a different reference operation every time.

A blocking `GC.Collect ()` immediately before the `before` sample retires the thread's allocation context through `fix_allocation_context (…, for_gc_p: TRUE)`, so `alloc_ptr` is 0 and a later void has nothing to discard. Any genuine allocation during the measured loop creates a new allocation context and is still counted, so the exact-zero assertion stays meaningful. `TrimmableTypeMapTypeManagerTests` uses the same exact-zero pattern and gets the same fix.

Validation, on emulator API 35 arm64, Debug:

  * Stress repro with `GC.Collect ()` before each round: 0 nonzero rounds out of 1,500 while background GCs kept running (the last background GC index advanced by about 3,900 per run). Without it, about 20 nonzero rounds out of 300.
  * `dotnet-local.sh test Mono.Android.NET-Tests.csproj --no-build -c Debug -p:IncludeCategories=ReferenceTracing`: passed 5 out of 5.
  * Full `Mono.Android.NET-Tests` Debug suite: 1109 out of 1109 passed in the runs that completed. The other runs aborted in `ManagedExceptionRoundTripPreservesIdentity (False)`. That abort already exists on main (4 of 5 baseline runs without this change, 3 of 5 with it) and is unrelated.

Co-authored-by: Copilot App <[email protected]>
…ments

Spell out GC.Collect (GC.MaxGeneration, GCCollectionMode.Forced, blocking: true)
so the intent (retire the thread's allocation context with a full blocking GC)
is explicit rather than implied by GC.Collect () defaults.

Co-authored-by: Copilot App <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 23, 2026 16:16

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 were identified for the allocation-test stabilization changes.

No open issues 🎉

What changed in this PR

This PR addresses intermittent allocation-test failures from #13726 by retiring the test thread’s allocation context before measuring allocations.

Changes:

  • Adds a forced, full blocking garbage collection before allocation-counter sampling in both tests.
  • Documents why background collection can inflate the counter without actual allocations.
  • Preserves the exact-zero assertions so genuine allocations remain detectable.
File Description
tests/​Mono.Android-Tests/​Mono.Android-Tests/​Java.Interop/​TrimmableTypeMapTypeManagerTests.cs Stabilizes allocation measurement for cached Java-to-managed type lookups.
tests/​Mono.Android-Tests/​Mono.Android-Tests/​Android.Runtime/​ManagedObjectReferenceManagerTests.cs Stabilizes allocation measurement for reference operations with tracing disabled.

Review effort: Balanced

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

@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 blocking findings. Counts: 0 ❌ errors, 0 ⚠️ warnings, 1 💡 documentation suggestion posted inline.

Reviewed both complete changed files, the reference-manager and typemap lookup implementations, and the device-test project configuration. The forced maximum-generation blocking collection is outside each measured interval, after warm-up; both exact-zero assertions and the reference-event assertion remain unchanged. The test assembly is already marked DoNotParallelize, so no additional test-parallelism annotation is needed. No product behavior or JNI ownership logic changes. The PR reports comparative background-GC stress measurements and deliberate-allocation checks, which are useful evidence for this narrowly scoped test fix; I did not independently rerun those device experiments.

CI verification is limited: all 39 returned GitHub checks report success, including the aggregate dotnet-android check for Azure build 1695316. Direct Azure build/timeline queries were unsuccessful because the CLI required authentication and the timeline command encountered a CLI initialization error. Therefore I cannot independently certify the Azure build details or non-gating device-test results. Runtime-source search was also rate-limited, so the allocation-accounting explanation could not be independently confirmed against the pinned runtime source. These are review-environment limitations, not demonstrated PR regressions.

Generated by Android PR Reviewer for #13729 · copilot · gpt61 · 29.4 AIC · ⌖ 4.83 AIC · ⊞ 20.3K
Comment /review to run again

@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 24, 2026
@simonrozsival
simonrozsival merged commit b05e6f1 into main Nov 24, 2026
38 checks passed
@simonrozsival
simonrozsival deleted the simonrozsival-fix-disabled-tracing-alloc-flake branch November 24, 2026 21:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

CI: DisabledTracingDoesNotAllocateDuringReferenceOperations intermittently reports allocations

3 participants