Fix MemoryCache negative _cacheSize drift that permanently latches a size-limited cache#129215
Open
sablancoleis wants to merge 13 commits into
Open
Fix MemoryCache negative _cacheSize drift that permanently latches a size-limited cache#129215sablancoleis wants to merge 13 commits into
sablancoleis wants to merge 13 commits into
Conversation
Decrement the prior entry's size exactly once, atomically with the TryUpdate that swaps it out, instead of speculatively inside UpdateCacheSizeExceedsCapacity before the swap. The speculative subtraction races with a concurrent RemoveEntry of the prior entry (expiration/explicit Remove/eviction), double-counts the decrement, drives _cacheSize negative, and permanently latches the cache into silently rejecting all inserts. Restores the .NET 8 accounting semantics. Fixes dotnet#129186
The first revision removed priorEntry.Size from the capacity check as well as the commit, which regressed CapacityTests.ReplaceOldEntryWithSameSizeOrLessNew EntryAtSizeLimitCapacity (a same-or-smaller replace at the size limit was falsely rejected). Restore the prior-aware capacity decision while still committing only entry.Size to _cacheSize; the prior entry's size is decremented exactly once, atomically with the TryUpdate swap, which is what fixes the race.
Back the concurrency workers with dedicated threads via TaskCreationOptions.LongRunning instead of Task.Run so the storm cannot saturate the shared ThreadPool and starve timing-sensitive post-eviction callbacks in sibling tests. Sample CurrentEstimatedSize inline (dropping the busy-spin monitor task), bound the work to a fixed iteration count, and gate the test on PlatformDetection.IsThreadingSupported.
4b2cb2e to
9fddf79
Compare
Author
|
@dotnet-policy-service agree company="Microsoft" |
This was referenced Jun 11, 2026
Open
5 tasks
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
Fixes #129186. When
MemoryCacheOptions.SizeLimitis set, the internal_cacheSizecounter can drift negative under concurrentSet/Get/Removeon string keys. Once negative, the capacity check(ulong)... > (ulong)sizeLimitis permanently true, so every subsequentSetis silently rejected (no exception) and nothing is retained for the lifetime of the cache —CurrentEntryCountstuck at 0, everyGeta miss. This is permanent, silent data loss.Regression source
Introduced by #103931 (merged for 9.0, "Subtract prior entry size when adding entry to cache"), which fixed #36039 — allowing an entry at the size limit to be replaced by a same-or-smaller one. That PR made two changes to the replace path:
newSize -= priorEntry.Size) so a same-or-smaller replace fits at the limit. This is correct and desirable._cacheSizedecrement of the prior entry out of the post-swapif (entryAdded)block and into the speculative capacity computation, before theTryUpdateswap.Change (2) is the bug. Pre-#103931 (i.e., 8.x), the prior entry's size was decremented only after a successful
TryUpdate, atomically tied to the swap, so a concurrent removal of the prior entry could not double-count it.Root cause
In
SetEntry, the prior entry's size is subtracted speculatively insideUpdateCacheSizeExceedsCapacity, before the entry is actually swapped in byTryUpdate. If another thread runsRemoveEntry(priorEntry)(expiration scan, explicitRemove, or eviction) in the window between that subtraction and theTryUpdate,priorEntry.Sizeis subtracted twice — once speculatively and once by the real removal inCoherentState.RemoveEntry. Each leaked decrement drives_cacheSizenegative, and the(ulong)cast then latches the cache permanently.Fix
Keep #103931's prior-aware capacity check (so the #36039 behavior and its test are preserved), but commit only
+entry.Sizeto_cacheSizethere. DecrementpriorEntry.Sizeexactly once, atomically with theTryUpdatethat performs the swap — restoring the pre-#103931 (8.x) ordering. On the failure path, roll back onlyentry.Size.This intentionally keeps the existing
CompareExchangeretry loop and the "check capacity before committing" ordering, so it avoids both problems that closed #124430 (overflow-rollback corruption, and false rejections from a transiently-inflated size). The only transient window now over-counts bypriorEntry.Size(positive), which is self-correcting and can never latch the cache.Validation
Reproduced and validated against the genuine
MemoryCachesource compiled standalone (concurrent Set/Get/Remove storm on a small string keyspace under a generousSizeLimit, with a fresh-key retention probe):_cacheSizegoes negative, 0/512 fresh entries retained.SizeLimiteviction still enforced (a tiny limit still bounds count/size); and the 2nd call to MemoryCache.Set() with the same key erases entry if cache is full #36039 replace-at-limit behavior (ReplaceOldEntryWithSameSizeOrLessNewEntryAtSizeLimitCapacity, new value size 6/5/2 at limit 6) still passes.Bisection (same harness): 8.0.x not affected; 9.0.x and 10.0.x affected, on both
net462andnet10.0builds — consistent with #103931 shipping in 9.0.A single-threaded pure-replace microbenchmark (the only path this change touches) shows the difference vs the current code is within run-to-run noise (~100 ns/op either way) — per-replace cost is dominated by entry allocation and dictionary operations; the fix only restores one
Interlocked.Addon the replace path. Happy to add aSet-throughput benchmark to dotnet/performance if desired (per the discussion on #111959).Tests
Adds
MemoryCacheConcurrentSizeTrackingTestswith:SizeLimiteviction is still enforced.Related: #36039 (behavior preserved), #103931 (regression source), #111959, #124430.