Skip to content

HybridCache over-releases the shared default cache item on concurrent DisableUnderlyingData misses #7880

Closed

Description

@svick

Description

Concurrent calls to the existing GetOrCreateAsync API with HybridCacheEntryFlags.DisableUnderlyingData can over-release an internal cache item when the key is absent from both cache tiers.

StampedeState<TState, T>.SetDefaultResult() completes the shared operation using ImmutableCacheItem<T>.GetReservedShared(). That method reserves the returned item once per operation, but each independently unwrapping caller releases it through GetReservedValue().

Reservations for joined callers are instead recorded on the stampede's own cache item, which is not the item returned on this path.

Reproduction

  1. Configure HybridCache with an IDistributedCache implementation whose GetAsync can be blocked until explicitly released.
  2. Start at least three GetOrCreateAsync<string> calls for the same missing key, with DisableUnderlyingData and a cancellable token. Do not cancel the token.
  3. Keep the distributed-cache read blocked until all callers have joined the operation.
  4. Release the distributed-cache read, returning null to indicate a miss.

Using cancellable tokens ensures waiting callers unwrap independently rather than sharing the immutable-result unwrap task.

Expected behavior

All callers receive null, the factory is not invoked, and internal reference counts remain balanced.

Actual behavior

Each caller decrements the shared default item's reference count, although only one reservation was added for the operation.

A fresh shared default item starts at count 2, so three independent unwraps decrement it to -1. Debug builds trigger:

Debug.Assert(newCount >= 0, "over-release detected")

Release builds retain the incorrect reference count. Cached-data corruption has not been demonstrated.

Related

Discovered and addressed by @Eng3bbas alongside the API addition in #7876. This bug affects the existing API and can be fixed independently of that addition.

Note

Investigated and drafted with GitHub Copilot. Based on source inspection; reproduction steps have not been executed.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-caching-hybridbug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions