Skip to content

MemoryExtensions.Sort<TKey, TValue, TComparer>(keys, items, comparer) sorts incorrectly for struct TComparer in .NET 11 #136274

Closed

Description

@manofstick

Description

Whilst taking Cistern.ValueLinq for a spin in .net 11 (which is goes quite well actually, that's to JIT updates!) I found that some of my tests were failing as elements were being sorted incorrectly. The following code, written by Claude, shows the error.

Reproduction Steps

using System;
using System.Collections.Generic;

Console.WriteLine(Environment.Version);
const int n = 499;

static (int[] keys, int[] elements, int[] indexes) Make(int n)
{
    var elements = new int[n];
    for (var i = 0; i < n; ++i) elements[i] = i;
    var keys = (int[])elements.Clone();
    var indexes = new int[n];
    for (var i = 0; i < n; ++i) indexes[i] = i;
    return (keys, elements, indexes);
}

static string Check(int[] elements, int[] keys, int[] indexes)
{
    for (var i = 1; i < elements.Length; ++i)
        if (elements[i - 1] > elements[i])
            return $"NOT sorted; first bad at {i}: [{string.Join(",", elements.AsSpan(Math.Max(0, i - 3), 7).ToArray())}] indexes=[{string.Join(",", indexes.AsSpan(Math.Max(0, i - 3), 7).ToArray())}]";
    return "sorted";
}

{
    var (keys, elements, indexes) = Make(n);
    indexes.AsSpan().Sort(elements.AsSpan(), new StructCmp(keys));
    Console.WriteLine($"Span.Sort(items, structComparer)       : {Check(elements, keys, indexes)}");
}
{
    var (keys, elements, indexes) = Make(n);
    indexes.AsSpan().Sort<int, int, IComparer<int>>(elements.AsSpan(), new ClassCmp(keys));
    Console.WriteLine($"Span.Sort(items, classComparer)        : {Check(elements, keys, indexes)}");
}
{
    var (keys, elements, indexes) = Make(n);
    indexes.AsSpan().Sort(elements.AsSpan(), (x, y) => keys[x].CompareTo(keys[y]) switch { 0 => x.CompareTo(y), var c => c });
    Console.WriteLine($"Span.Sort(items, Comparison)           : {Check(elements, keys, indexes)}");
}
{
    var (keys, elements, indexes) = Make(n);
    Array.Sort(indexes, elements, new ClassCmp(keys));
    Console.WriteLine($"Array.Sort(keys, items, classComparer) : {Check(elements, keys, indexes)}");
}
{
    var (keys, elements, indexes) = Make(n);
    indexes.AsSpan().Sort(new StructCmp(keys));
    var ok = true;
    for (var i = 1; i < n && ok; ++i) ok = keys[indexes[i - 1]] <= keys[indexes[i]];
    Console.WriteLine($"Span.Sort(structComparer) no items     : {(ok ? "sorted" : "NOT sorted")}");
}
{
    // Same, but keys are NOT already in index order (so the comparer disagrees with natural int order)
    var (keys, elements, indexes) = Make(n);
    for (var i = 0; i < n; ++i) { keys[i] = n - i - 1; elements[i] = keys[i]; }
    indexes.AsSpan().Sort(elements.AsSpan(), new StructCmp(keys));
    Console.WriteLine($"Span.Sort(items, structComparer) desc  : {Check(elements, keys, indexes)}");
}
{
    // Does the comparer get called at all?
    var (keys, elements, indexes) = Make(n);
    var counting = new CountingCmp(keys);
    indexes.AsSpan().Sort<int, int, CountingCmp>(elements.AsSpan(), counting);
    Console.WriteLine($"comparer calls with items overload     : {counting.Calls}");
    var counting2 = new CountingCmp(keys);
    indexes.AsSpan().Sort<int, CountingCmp>(counting2);
    Console.WriteLine($"comparer calls without items overload  : {counting2.Calls}");
}

struct StructCmp : IComparer<int>
{
    readonly int[] _keys;
    public StructCmp(int[] keys) => _keys = keys;
    public int Compare(int x, int y) => _keys[x].CompareTo(_keys[y]) switch { 0 => x.CompareTo(y), var c => c };
}

sealed class ClassCmp : IComparer<int>
{
    readonly int[] _keys;
    public ClassCmp(int[] keys) => _keys = keys;
    public int Compare(int x, int y) => _keys[x].CompareTo(_keys[y]) switch { 0 => x.CompareTo(y), var c => c };
}

sealed class CountingCmp : IComparer<int>
{
    readonly int[] _keys;
    public int Calls;
    public CountingCmp(int[] keys) => _keys = keys;
    public int Compare(int x, int y) { Calls++; return _keys[x].CompareTo(_keys[y]) switch { 0 => x.CompareTo(y), var c => c }; }
}

Expected behavior

Data to be sorted correctly

Actual behavior

Data not sorted correctly

Regression?

This worked under .net 10

Claude says

  • PR 116109 "Avoid sort allocations" by 2A5F, merged into main on 2025-10-03, is the change behind the failing path. It added ArraySortHelper<T, TComparer> so a struct comparer flows through Span.Sort without boxing. That matches the probe exactly: only the struct-comparer path fails, and only the keys-plus-items overload of it. It is the only commit to ArraySortHelper.cs since then, so no fix has landed in main.
  • Two follow-up PRs build on it without reporting a defect: PR 121797 "Refactor Array.Sort methods to use Span.Sort" (2025-11-19) and PR 122379 "Improve sort tcomp path" (2025-12-10).
  • Issue 135755, opened 2026-10-14 by hexawyz and still open, is the only live issue on this overload. It is an API proposal to add allows ref struct to the TComparer constraint, motivated by an indirect sort over an index array, which is the same usage as the probe. It is not a bug report and its three comments say nothing about wrong output. It is worth cross-referencing in your issue since the reporter is about to hit the same defect.
  • The web search found no blog, StackOverflow or issue report of wrong results from this overload. The .NET 11 performance blog post only describes the non-boxing path as a feature.

Known Workarounds

No response

Configuration

No response

Other information

No response

Activity

  1. added
    untriaged
    on Oct 22, 2026
  2. dotnet-policy-service commented on Oct 22, 2026

    @dotnet-policy-service
    Contributor

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

  3. dotnet-policy-service commented on Oct 22, 2026

    @dotnet-policy-service
    Contributor

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

  4. eiriktsarpalis commented on Oct 22, 2026

    @eiriktsarpalis
    Member

    Confirmed on .NET 11.0.0-rc.2.26504.105 (Windows x64), with the same repro passing on .NET 10.0.13. The failure does not require indirect sorting: 17 already-sorted integers and a stateless struct comparer are sufficient.

    The paired-span partitioner is missing Swap(keys, values, middle, hi - 1) after selecting the pivot, although the subsequent partitioning assumes that move occurred. Passing the same struct comparer as IComparer<int> to force boxing avoids the affected path.

    AI-generated with GitHub Copilot.

  5. xgbtxy commented on Oct 22, 2026

    @xgbtxy
    Contributor

    I reproduced this on Windows x64 using the official .NET 11.0.0-rc.2.26504.105 runtime. With keys 0..16, corresponding items 1000..1016, and a concrete stateless struct comparer, the resulting keys are 0..7, 15, 8..14, 16.

    A 90-case local matrix (nine lengths from 0 to 499, ascending/reversed input, and five comparer/overload paths) has eight failures, all in the paired-span struct-comparer path above the 16-element threshold. The smaller inputs, boxed struct comparer, class comparer, Comparison<T>, and keys-only struct-comparer controls pass. The test also checks the key/item association.

    I'll take this up by restoring the paired pivot exchange identified above and adding regression coverage that actually selects the concrete value-type comparer path. I am building unchanged main 7975d8de with a Checked runtime first, then will verify the regression against both the original and fixed CoreLib.

    Note

    This investigation, test driver, and comment were prepared with Codex and are AI-generated.

  6. removed
    untriaged
    on Oct 28, 2026
  7. added a commit that references this issue on Oct 29, 2026
    3bd97c1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions