-
Notifications
You must be signed in to change notification settings - Fork 5.5k
Fix MemoryCache negative _cacheSize drift that permanently latches a size-limited cache #129215
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
cincuranet
merged 17 commits into
dotnet:main
from
sablancoleis:fix/memorycache-sizelimit-negative-drift
Jun 16, 2026
+151
−12
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
7fead53
Fix MemoryCache negative _cacheSize drift on concurrent replace+remove
sablancoleis 5461528
Add concurrency regression test for MemoryCache size-tracking drift (…
sablancoleis ed121f9
Merge branch 'main' into fix/memorycache-sizelimit-negative-drift
sablancoleis 4f3d193
Merge main into fix/memorycache-sizelimit-negative-drift
sablancoleis 01f90d3
Keep prior-aware capacity check; commit only entry.Size
sablancoleis ee67b97
Use explicit types and target-typed new in the regression test
sablancoleis 5904776
Merge branch 'main' into fix/memorycache-sizelimit-negative-drift
sablancoleis 9fddf79
Use LongRunning tasks for the concurrent size-tracking regression test
sablancoleis 03aeb9f
Merge branch 'main' into fix/memorycache-sizelimit-negative-drift
sablancoleis 8664fcb
Fix build: use PlatformDetection.IsMultithreadingSupported
sablancoleis 25f37a3
Merge branch 'main' into fix/memorycache-sizelimit-negative-drift
sablancoleis f3bb16a
Merge branch 'main' into fix/memorycache-sizelimit-negative-drift
sablancoleis 6538000
Merge branch 'main' into fix/memorycache-sizelimit-negative-drift
sablancoleis a243d46
Address review: remove redundant SizeLimit test, mark concurrency tes…
sablancoleis b28f90e
Merge branch 'main' into fix/memorycache-sizelimit-negative-drift
sablancoleis 5491394
Merge branch 'main' into fix/memorycache-sizelimit-negative-drift
sablancoleis 9d93550
Merge branch 'main' into fix/memorycache-sizelimit-negative-drift
sablancoleis File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
121 changes: 121 additions & 0 deletions
121
...aries/Microsoft.Extensions.Caching.Memory/tests/MemoryCacheConcurrentSizeTrackingTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Xunit; | ||
|
|
||
| namespace Microsoft.Extensions.Caching.Memory | ||
| { | ||
| public class MemoryCacheConcurrentSizeTrackingTests | ||
| { | ||
| // Regression test for the size-tracking double-decrement that drives _cacheSize negative and | ||
| // permanently latches a size-limited cache into rejecting all inserts. Many threads | ||
| // concurrently Set (replace), Get, and Remove a small set of string keys with short | ||
| // expirations under a generous SizeLimit. The working set is a tiny fraction of the limit, so | ||
| // no legitimate capacity rejection can occur. After the storm the tracked size must not be | ||
| // negative and the cache must still retain fresh, non-expiring entries. | ||
| // | ||
| // The workers are LongRunning tasks, which the default scheduler backs with dedicated threads | ||
| // rather than the shared ThreadPool. This prevents the storm from starving timing-sensitive | ||
| // post-eviction callbacks in sibling tests. It runs as OuterLoop because it is a long-running | ||
| // stress test, and ConditionalFact skips platforms without real thread support (e.g. browser/wasm). | ||
| [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsMultithreadingSupported))] | ||
| [OuterLoop] | ||
| public void ConcurrentSetReplaceAndRemove_DoesNotDriftSizeNegative_NorLatch() | ||
| { | ||
| using MemoryCache cache = new(new MemoryCacheOptions | ||
| { | ||
| SizeLimit = 200L * 1024 * 1024, // far larger than the working set below | ||
| TrackStatistics = true | ||
| }); | ||
|
|
||
| const int KeyCount = 16; | ||
| const int ValueSize = 4096; | ||
| const int IterationsPerThread = 200_000; | ||
| const int SampleMask = 1023; // sample CurrentEstimatedSize roughly every 1024 iterations | ||
| byte[] payload = new byte[ValueSize]; | ||
| int threadCount = Math.Min(Math.Max(4, Environment.ProcessorCount), 16); | ||
|
|
||
| long observedMinSize = 0; | ||
|
|
||
| Task[] workers = new Task[threadCount]; | ||
| for (int t = 0; t < threadCount; t++) | ||
| { | ||
| int seed = t + 1; | ||
| workers[t] = Task.Factory.StartNew( | ||
| () => | ||
| { | ||
| Random rnd = new(seed); | ||
| for (int i = 0; i < IterationsPerThread; i++) | ||
| { | ||
| string key = "k" + rnd.Next(KeyCount); | ||
| int roll = rnd.Next(100); | ||
| if (roll < 65) | ||
| { | ||
| using ICacheEntry entry = cache.CreateEntry(key); | ||
| entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMilliseconds(15); | ||
| entry.Size = ValueSize; | ||
| entry.Value = payload; | ||
| } | ||
| else if (roll < 85) | ||
| { | ||
| cache.TryGetValue(key, out _); | ||
| } | ||
| else | ||
| { | ||
| cache.Remove(key); | ||
| } | ||
|
|
||
| if ((i & SampleMask) == 0) | ||
| { | ||
| long? size = cache.GetCurrentStatistics()?.CurrentEstimatedSize; | ||
| if (size.HasValue && size.Value < Interlocked.Read(ref observedMinSize)) | ||
| { | ||
| Interlocked.Exchange(ref observedMinSize, size.Value); | ||
| } | ||
| } | ||
| } | ||
| }, | ||
| CancellationToken.None, | ||
| TaskCreationOptions.LongRunning, | ||
| TaskScheduler.Default); | ||
| } | ||
|
|
||
| Task.WaitAll(workers); | ||
|
|
||
| // Drain the working set so the cache is logically empty. | ||
| for (int k = 0; k < KeyCount; k++) | ||
| { | ||
| cache.Remove("k" + k); | ||
| } | ||
| Thread.Sleep(100); | ||
|
|
||
| Assert.True(observedMinSize >= 0, $"CurrentEstimatedSize drifted negative to {observedMinSize}."); | ||
|
|
||
| long drainedSize = cache.GetCurrentStatistics().CurrentEstimatedSize ?? 0; | ||
| Assert.True(drainedSize >= 0, $"CurrentEstimatedSize is negative after drain: {drainedSize}."); | ||
|
|
||
| // The cache must still retain fresh, non-expiring entries (i.e., it is not latched). | ||
| const int Probe = 512; | ||
| int retained = 0; | ||
| for (int i = 0; i < Probe; i++) | ||
| { | ||
| string key = "fresh-" + i; | ||
| using (ICacheEntry entry = cache.CreateEntry(key)) | ||
| { | ||
| entry.Size = ValueSize; | ||
| entry.Value = payload; | ||
| } | ||
|
|
||
| if (cache.TryGetValue(key, out _)) | ||
| { | ||
| retained++; | ||
| } | ||
| } | ||
|
|
||
| Assert.Equal(Probe, retained); | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.