Skip to content

Don't invalidate enumerators on capacity changes that keep item positions - #137213

Merged
krwq merged 4 commits into
dotnet:mainfrom
su-senka:capacity-ops-no-version-bump
Nov 20, 2026
Merged

krwq merged 4 commits into
dotnet:mainfrom
su-senka:capacity-ops-no-version-bump

Conversation

@su-senka

@su-senka su-senka commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

#82500 removed the capacity-only _version++ from List<T> and Stack<T>, since resizing their arrays doesn't change what an enumerator returns. This does the same for the other types where that's true:

  • Queue<T>: SetCapacity, which EnsureCapacity and both TrimExcess overloads go through. Remove unnecessary _version++ from a few places #82500 kept this one because growing a queue relays out the items from index 0. But the enumerator stores an offset from _head and re-reads _head and _array on each MoveNext, and SetCapacity resets _head to 0. That was already the case when Remove unnecessary _version++ from a few places #82500 was merged.
  • Dictionary<TKey, TValue>.EnsureCapacity: Resize copies the entries to the same indices. HashSet<T>.EnsureCapacity never had the increment.
  • PriorityQueue<TElement, TPriority>.EnsureCapacity and TrimExcess: both are an Array.Resize, and the enumerator reads _nodes[_index].
  • OrderedDictionary<TKey, TValue>.EnsureCapacity: Resize is an Array.Copy. Its TrimExcess already didn't increment.

TrimExcess on Dictionary and HashSet keeps the increment. It compacts the entries when some were removed. With none removed the entries stay at the same indices, but it increments anyway, so that whether it invalidates doesn't depend on earlier removals.

The increment in Dictionary.EnsureCapacity came from dotnet/coreclr#19096, after a review comment that TrimExcess and EnsureCapacity could invalidate an enumeration. That's true for TrimExcess but not for EnsureCapacity.

The Queue and Dictionary EnsureCapacity tests are flipped to DoesNotInvalidateEnumeration, like #82500 did for List and Stack, and now check that the enumeration returns the same items. The PriorityQueue EnsureCapacity(2 * Count) case moved to the non-modifying operations. New tests for Queue TrimExcess (with the items wrapped around the end of the array), PriorityQueue and OrderedDictionary change the capacity in the middle of an enumeration and compare the whole sequence.

System.Collections.Tests passes on osx-arm64. With the increments put back, 28 of the new and changed tests fail. I also checked it outside the test suite: interrupt an enumeration at every position with the capacity change, finish it, and compare with an undisturbed enumeration. That covered sizes 0 to 64, wrapped and unwrapped queues, and dictionaries with and without removed entries, 53,625 cases in all, with no differences.

The Dictionary<TKey, TValue>.GetEnumerator docs say that "changing the capacity" invalidates the enumerator. That's still true for TrimExcess, but I can send a docs PR to make it specific if this goes in.

Related to #81523.

…ions

dotnet#82500 removed these increments from List<T> and Stack<T>, because
resizing the array there doesn't change what an enumerator sees. The
same is true for a few more types that still bump the version:

- Queue<T> (EnsureCapacity and TrimExcess, via SetCapacity). dotnet#82500
  left it alone because growing relays out the items from index 0, but
  the enumerator stores an offset from _head and re-reads _head and
  _array on every MoveNext, and SetCapacity resets _head to 0. It
  already worked this way in 2023.
- Dictionary<TKey, TValue>.EnsureCapacity. Resize copies the entries to
  the same indices. HashSet<T>.EnsureCapacity never had the increment.
- PriorityQueue<TElement, TPriority>.EnsureCapacity and TrimExcess.
  Both are an Array.Resize, and the enumerator reads _nodes[_index].
- OrderedDictionary<TKey, TValue>.EnsureCapacity. Resize is an
  Array.Copy, and TrimExcess already didn't increment.

TrimExcess on Dictionary and HashSet still invalidates, since it
compacts the entries.

The Queue and Dictionary EnsureCapacity tests now check that the
enumeration continues with the same items, and there are new tests
for Queue.TrimExcess (with the items wrapped around the array),
PriorityQueue and OrderedDictionary that change the capacity in the
middle of an enumeration.
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Nov 9, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
12 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

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

…ment

These tests compare the serialized fields of a Queue<T>, including
_version. The first Enqueue grows the empty array, and SetCapacity no
longer increments the version, so the expected values are one lower.
@su-senka

Copy link
Copy Markdown
Contributor Author

Second commit updates three DCS/DCJS baselines that include Queue<T>._version. The first Enqueue grows the array, so the serialized version is one lower now. Old payloads still deserialize fine, the field isn't used after that.

…ries move

TrimExcess copies the entries with CopyEntries, which only moves entries
when it compacts free slots left by Remove. When there are none (nothing
removed, or the slots were reused by later adds or reset by Clear) every
entry keeps its index, so the enumerators keep working. Increment the
version only when _freeCount > 0.
…when entries move"

This reverts commit 838d42a.

TrimExcess keeps the unconditional increment so whether it invalidates
doesn't depend on earlier removals.
@krwq

krwq commented Nov 20, 2026

Copy link
Copy Markdown
Member

Copilot Failures Analysis

Failed work item Cause Related to this PR? Tracking
System.Runtime.Tests (iOS/CoreCLR) App installation failed: devicectl, NSPOSIXErrorDomain error 49 No - failed before tests ran Tracked: #123796 (open); matched by Build Analysis
ParallelForEachAsync.Test (iOS/NativeAOT) App installation failed: devicectl, NSPOSIXErrorDomain error 49 No - failed before tests ran Tracked: #123796 (open); matched by Build Analysis
ExportManagedSymbols.Test (iOS/NativeAOT) App installation failed: devicectl, NSPOSIXErrorDomain error 49 No - failed before tests ran Tracked: #123796 (open); matched by Build Analysis

@krwq
krwq merged commit be2de60 into dotnet:main Nov 20, 2026
100 of 102 checks passed
@su-senka
su-senka deleted the capacity-ops-no-version-bump branch November 20, 2026 15:39
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-System.Collections 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.

3 participants