ImmutableSortedSet<T>.Builder: enumerating through IEnumerable<T> doesn't throw on modification and can return wrong items

Abierto Apto para principiantes
#137,167 1 comentario 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
78/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
csharp
Área
backend, testing

Línea de trabajo

Empieza en src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Builder.cs, en la implementación de IEnumerable<T>.GetEnumerator() enlazada en la incidencia, y compárala después con los enumeradores comprobados de los demás generadores inmutables. Ejecuta las pruebas de System.Collections.Immutable.Tests; se considera terminado cuando la enumeración mediante IEnumerable<T> lanza InvalidOperationException después de una modificación del generador, igual que la enumeración directa.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

area-System.Collections untriaged
Description

ImmutableSortedSet.Builder's IEnumerable.GetEnumerator() returns this.Root.GetEnumerator() and doesn't pass the builder, so the enumerator never checks the version:

https://github.com/dotnet/runtime/blob/614e7dafc09bcf359e8ce4f166b28189db14c364/src/libraries/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableSortedSet_1.Builder.cs#L394-L397

foreach over the builder itself throws if you modify it, but going through IEnumerable (LINQ, an IEnumerable parameter, etc.) doesn't. And since the builder mutates its own nodes in place, the enumeration can return items that were removed, return an item twice, or skip items that are still there.

Reproduction Steps
using System.Collections.Immutable;

var builder = ImmutableSortedSet.CreateBuilder<int>();
builder.Add(0);
builder.Add(2);
builder.Add(4);

foreach (int x in (IEnumerable<int>)builder)
{
    Console.Write(x + " ");
    if (x == 0)
        builder.Remove(2);
}
Expected behavior

InvalidOperationException after the Remove, like with foreach (int x in builder).

Actual behavior

No exception, and it prints "0 2 0 4". The builder contains "0 4" afterwards.

With 0 2 4 6 8 and the same Remove(2) it prints "0 2 6 8", so 4 is skipped even though it's still in the set.

I ran this with different mutations (Add, Remove, Clear, set operations, KeyComparer) at every position for sizes 1-48. It never throws through IEnumerable. For a builder filled with Add, about 14% of runs (2,450 of 17,640) gave duplicates, skipped items or wrong order. For a builder from ToBuilder() that wasn't modified before enumerating, you just get the old contents.

Regression?

I don't think so. Same result on .NET 10.0.11 and current main, and this line hasn't changed since the code was added to the repo in 2014 (ebabdf94973). I didn't try older releases or .NET Framework.

Known Workarounds

foreach over the builder directly (not through IEnumerable), or call ToImmutable() and enumerate that.

Configuration

.NET 10.0.11, and a local build of main (614e7dafc09)
macOS, ARM64

Other information

The other builders (ImmutableList, ImmutableHashSet, ImmutableDictionary, ImmutableSortedDictionary) go through their checked enumerator here. Doing the same fixes it:

IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
    return this.GetEnumerator();
}

I tried that locally. All the cases above throw with it, and System.Collections.Immutable.Tests passes. I can send a PR if that's the fix you want.

Lenguaje dominante
C#
Estrellas
18.4k
Forks
5.8k
Merge medio
2 d 12 h
PR fusionados (30 d)
581

Preparar el entorno

Abrir en Codespaces

Inicia el contenedor de desarrollo del proyecto en tu navegador, con tu propia cuenta de GitHub.

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de dotnet/runtime

Todos los issues de dotnet/runtime

Issues similares

Más issues de C#

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.