Skip to content

Fix version tracking in ImmutableSortedSet<T>.Builder.Reverse() - #138008

Open
aw0lid wants to merge 1 commit into
dotnet:mainfrom
aw0lid:fix-immutableSortedSet-builder-reverse-enumerator
Open

aw0lid wants to merge 1 commit into
dotnet:mainfrom
aw0lid:fix-immutableSortedSet-builder-reverse-enumerator

Conversation

@aw0lid

@aw0lid aw0lid commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Description

  • Problem:
    • ImmutableSortedSet<T>.Builder.Reverse() enumerated _root via ReverseEnumerable without passing the builder instance, bypassing version/mutation tracking and allowing concurrent mutations during enumeration without throwing InvalidOperationException.
  • Solution:
    • Updated Reverse() to iterate via a static local iterator (ReverseIterator) that constructs Enumerator with builder.Root, builder, and reverse: true, matching SortedSet<T>.Reverse() mutation tracking.
  • Tests Added:
    • Added ReverseThrowsOnMutation to verify that mutating the builder during Reverse() enumeration throws InvalidOperationException.

@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Nov 20, 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.

public IEnumerable<T> Reverse()
{
return new ReverseEnumerable(_root);
return ReverseIterator(this);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does ReverseIterator accomplish that simply returning a new Enumerator(builder.Root, builder, reverse: true); doesn't do? It boxes instead of allocating I guess. But that shouldn't be a problem according to

/// CAUTION: when this enumerator is actually used as a valuetype (not boxed) do NOT copy it by assigning to a second variable

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I understood your question correctly, Enumerator implements IEnumerator<T>, but not IEnumerable<T>, so it cannot be returned directly from Reverse() since its return type is IEnumerable<T>.

Also, even if boxing wouldn't be a problem here, why introduce it in the first place when we can avoid it entirely by keeping the enumerator as a value type?

@lilinus lilinus Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I did indeed miss that it returned a IEnumerable<T>!

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't ReverseEnumerable unused after this change then?

@aw0lid aw0lid Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yup, It is still used here in

/// <summary>
/// Returns an <see cref="IEnumerable{T}"/> that iterates over this
/// collection in reverse order.
/// </summary>
/// <returns>
/// An enumerator that iterates over the <see cref="ImmutableSortedSet{T}"/>
/// in reverse order.
/// </returns>
public IEnumerable<T> Reverse()
{
return new ReverseEnumerable(_root);
}

However, I believe we have an opportunity to eliminate ReverseEnumerable entirely, since the existing Enumerator already supports reverse iteration. We could implement it directly instead (as example):

public IEnumerable<T> Reverse()
{
    Requires.NotNull(_root, nameof(_root));

    using var enumerator = _root.Reverse();
    while (enumerator.MoveNext())
    {
        yield return enumerator.Current;
    }
}

Alternatively, at the very least, we could improve ReverseEnumerable to support the builder correctly as well, by passing the builder instance to the enumerator.

For example:

         private sealed class ReverseEnumerable : IEnumerable<T>
         {
             private readonly Node _root;
+            private readonly Builder? _builder;

             internal ReverseEnumerable(Node root)
             {
                 Requires.NotNull(root, nameof(root));
                 _root = root;
             }

+            internal ReverseEnumerable(Builder builder)
+            {
+                Requires.NotNull(builder, nameof(builder));
+                _builder = builder;
+                _root = builder.root;
+            }

             public IEnumerator<T> GetEnumerator()
             {
+                if (_builder is not null)
+                {
+                    return GetBuilderEnumerator(_root, _builder);
+                }
+
                 return _root.Reverse();
             }

+            private static IEnumerator<T> GetBuilderEnumerator(Node root, Builder builder)
+            {
+                using Enumerator enumerator = new Enumerator(builder.root, builder, reverse: true);
+                while (enumerator.MoveNext())
+                {
+                    yield return enumerator.Current;
+                }
+            }
+
             IEnumerator IEnumerable.GetEnumerator()
             {
                 return this.GetEnumerator();
             }
         }

This would allow both ImmutableSortedSet<T> and Builder to use ReverseEnumerable correctly, while preserving the builder's mutation tracking.

Personally, I lean towards the first approach, and if we find it appropriate, I'll implement it in a separate follow-up PR.

@krwq krwq left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest we slightly simplify but we can do further analysis on enumerator in the follow up

@aw0lid
aw0lid force-pushed the fix-immutableSortedSet-builder-reverse-enumerator branch from e81a54b to 68902eb Compare November 25, 2026 16:43
@aw0lid
aw0lid force-pushed the fix-immutableSortedSet-builder-reverse-enumerator branch from 68902eb to 3c65f30 Compare November 25, 2026 17:13

This branch has not been deployed

No deployments
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