Skip to content

Make MemoryCache thread-safety tests deterministic#129897

Open
sami-daniel wants to merge 2 commits into
dotnet:mainfrom
sami-daniel:sami-daniel-issue-72890
Open

Make MemoryCache thread-safety tests deterministic#129897
sami-daniel wants to merge 2 commits into
dotnet:mainfrom
sami-daniel:sami-daniel-issue-72890

Conversation

@sami-daniel

Copy link
Copy Markdown

The three concurrency tests in MemoryCacheSetAndRemoveTests were disabled because they were timing-sensitive and racy. They relied on fixed multi-second delays to bound their run, so every run took ~7s and the outcome depended on thread scheduling. Two of them also had bugs in the test code itself:

  • OvercapacityPurge_AreThreadSafe created its worker tasks with a cancellation token (Task.Run(..., cts.Token)). When the token fired, the tasks ended up Canceled, so Task.WaitAll threw TaskCanceledException, the failure tracked in the issue.
  • AddAndReplaceEntries_AreThreadSafe shared a single Random instance across three threads. Random is not thread-safe, so concurrent use corrupted its state.

Fix #72890

The three concurrency tests in MemoryCacheSetAndRemoveTests relied on
fixed multi-second delays plus task cancellation to bound their run,
which made them slow and racy, so they were disabled. Rewrite them to
run a fixed number of iterations per thread, started together with a
Barrier, removing all wall-clock timing.

OvercapacityPurge_AreThreadSafe also created its tasks with a
cancellation token, so cancellation left them Canceled and
Task.WaitAll threw TaskCanceledException. AddAndReplaceEntries_AreThreadSafe
shared a single Random across threads, which is not thread-safe; each
thread now owns its own instance.

Re-enable both. GetAndSet_AreThreadSafe_AndUpdatesNeverLeavesNullValues
is de-raced too but stays disabled under dotnet#72879, an unrelated cache bug
it exercises.

Fix dotnet#72890
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Jun 26, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-extensions-caching
See info in area-owners.md if you want to be subscribed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-Extensions-Caching community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Rewrite 3 MemoryCache tests to not be timing sensitive

1 participant