SQL Server: quadratic parameter-name generation across split queries with MultipleParameters (10.0.13)

Aperta
#39,333 0 commenti 0 reazioni 1 assegnatario Vedi su GitHub

I maintainer di solito rispondono entro 2 giorni

@AndriySvyryd ci sta già lavorando.

Dal 22/10/2026.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
48/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
csharp, sql

Direzione di ricerca

Start with SqlNullabilityProcessor.Process and trace ProcessInExpressionValues and ExpandParameterIfNeeded, then inspect Uniquifier.Uniquify as linked in the issue. Use the supplied SQL Server interceptor reproduction to compare MultipleParameters and JSON modes with split collection includes. Done means parameter-name generation scales roughly with IDs × split statements without the reported allocation growth.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

area-perf area-query
Bug description

ParameterTranslationMode.MultipleParameters has a severe client-side performance/allocation problem when a parameterized Contains filter is repeated across AsSplitQuery() collection includes. This reproduces on EF Core / SQL Server provider 10.0.13, the latest stable 10.0.x on NuGet when tested, and on 10.0.12.

The reproduction below needs no SQL Server installation or connection. A connection interceptor suppresses opening the dummy connection, and a command interceptor returns one synthetic root row and empty child readers. It still executes EF's real SQL Server translation, parameter generation, split-query enumeration and materialization paths. No database work, network latency or large result set is involved.

With 1,000 IDs and 12 included collections (13 SQL statements), scalar translation takes about 3.8–4.0 seconds and cumulatively allocates about 10.5 GiB. JSON translation takes about 4 ms and allocates about 0.4 MiB after query-shape warmup. These are cumulative managed allocations, not retained memory or SQL Server grants.

Each scalar command has only 1,000 parameters; this is below the SQL Server limit and does not use OPENJSON.

Related: #37152 / #37313 addressed quadratic unique-parameter-name generation in 10.0.2. That fix is already present in both versions tested here. I could not find an existing issue specifically covering repeated collection expansion across split statements.

Observed results

Release build, Windows x64, SDK 10.0.401, runtime .NET 10.0.12. Modes run in separate processes. The first 100-ID cases warm the three query shapes; values below are later cases from the same process. These are Stopwatch measurements, not BenchmarkDotNet results.

EF / provider Mode IDs Collection includes SQL statements Wall ms Total managed allocations, MiB
10.0.13 MultipleParameters 500 0 1 2.7 0.6
10.0.13 MultipleParameters 500 4 5 256.1 346.8
10.0.13 MultipleParameters 500 12 13 993.1 2688.9
10.0.13 MultipleParameters 1000 0 1 0.9 1.2
10.0.13 MultipleParameters 1000 4 5 414.9 1379.8
10.0.13 MultipleParameters 1000 12 13 3756.1 10733.8
10.0.13 MultipleParameters 1500 12 13 10152.7 24133.6
10.0.13 Parameter (JSON) 1000 12 13 4.0 0.4
10.0.13 Parameter (JSON) 1500 12 13 1.3 0.6
10.0.12 MultipleParameters 1000 12 13 4044.8 10733.8
10.0.12 MultipleParameters 1500 12 13 9371.9 24133.6
Suspected cause

The command interceptor observes disjoint parameter-name ranges for successive split statements, although they all filter on the same captured ID array:

statement 1:  @ids1     .. @ids1000
statement 2:  @ids1001  .. @ids2000
statement 3:  @ids2001  .. @ids3000
...
statement 13: @ids12001 .. @ids13000

In SqlNullabilityProcessor.Process, _collectionParameterExpansionMap is cleared per statement. ProcessInExpressionValues / ExpandParameterIfNeeded then expands the collection again, adding parameters to the parameter-values dictionary. ExpandParameterIfNeeded calls Uniquifier.Uniquify with a starting suffix based on the element index; the dictionary already contains names generated for earlier split statements, so finding the next unused name appears to repeatedly scan those ranges and allocate candidate strings.

This mechanism is a source-based diagnosis, not a patched-framework A/B proof. The independently runnable reproduction demonstrates the performance/allocation growth and the increasing parameter-name ranges directly.

Relevant source on the tested release:

Expected: expanding an N-element parameter collection across S split statements should scale roughly with N × S, without a large volume of repeated collision searches and transient string allocations. Reusing the collection's scalar parameters across split commands, or generating new names without repeatedly scanning prior ranges, may avoid the issue.

Workaround: UseParameterizedCollectionMode(ParameterTranslationMode.Parameter) avoids this client-side regression, but uses JSON and therefore has different server-side cardinality/plan characteristics.

Your code

Create an empty folder containing the following two files. No database setup, credentials, schema or seed data are needed.

Run each mode in its own process:

dotnet run -c Release -- scalar 100 500 1000 1500
dotnet run -c Release -- json 100 500 1000 1500

To also check 10.0.12:

dotnet run -c Release -p:EFVersion=10.0.12 -- scalar 100 500 1000 1500

The program verifies the returned root and command count, prints loaded assembly versions, command/parameter counts, timings and cumulative allocated bytes, and shows parameter-name ranges for the 1,000-ID / 12-collection case. No AppContext compatibility switches are set.

Repro.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
    <ManagePackageVersionsCentrally>false</ManagePackageVersionsCentrally>
    <EFVersion Condition="'$(EFVersion)' == ''">10.0.13</EFVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="$(EFVersion)" />
  </ItemGroup>
</Project>

Program.cs (complete runnable reproduction)
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;

System.Globalization.CultureInfo.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
Console.WriteLine($"EF Core: {typeof(DbContext).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()!.InformationalVersion}");
Console.WriteLine($"SQL Server provider: {typeof(SqlServerDbContextOptionsExtensions).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()!.InformationalVersion}");
Console.WriteLine($"Runtime: {System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription}");
Console.WriteLine("No SQL Server connection is opened. Every command returns synthetic data.");
Console.WriteLine("Mode,IDs,Collections,Commands,MaxParameters,JSONCommands,WallMs,ProcessCpuMs,AllocatedMiB");

var mode = args.FirstOrDefault() == "json" ? ParameterTranslationMode.Parameter : ParameterTranslationMode.MultipleParameters;
var sizes = args.Length <= 1 ? new[] { 100, 1000, 1500 } : args.Skip(1).Select(int.Parse).ToArray();
{
    foreach (var count in sizes)
    {
        foreach (var collections in new[] { 0, 4, 12 })
        {
            var interceptor = new SyntheticDatabase();
            var options = new DbContextOptionsBuilder<ReproContext>()
                .UseSqlServer("Server=unused.invalid;Database=Unused;Integrated Security=true;MultipleActiveResultSets=false",
                    sql => sql.UseParameterizedCollectionMode(mode))
                .AddInterceptors(new NeverConnect(), interceptor)
                .Options;
            await using var context = new ReproContext(options);
            _ = context.Model;
            var ids = Enumerable.Range(1, count).ToArray();
            IQueryable<Root> query = context.Roots.Where(r => ids.Contains(r.Id));
            for (var i = 1; i <= collections; i++)
                query = query.Include($"Children{i:00}");
            query = query.AsSplitQuery();

            var cpu = Process.GetCurrentProcess().TotalProcessorTime;
            var allocated = GC.GetTotalAllocatedBytes(precise: true);
            var watch = Stopwatch.StartNew();
            var roots = await query.ToListAsync();
            watch.Stop();
            var cpuMs = (Process.GetCurrentProcess().TotalProcessorTime - cpu).TotalMilliseconds;
            if (roots.Count != 1 || roots[0].Id != 1 || interceptor.Commands != collections + 1)
                throw new InvalidOperationException("Unexpected synthetic query results or command count.");
            var allocatedMiB = (GC.GetTotalAllocatedBytes(precise: true) - allocated) / 1048576.0;
            Console.WriteLine($"{mode},{count},{collections},{interceptor.Commands},{interceptor.MaxParameters},{interceptor.JsonCommands},{watch.Elapsed.TotalMilliseconds:F1},{cpuMs:F1},{allocatedMiB:F1}");
            if (count == 1000 && collections == 12)
                Console.WriteLine("Parameter ranges: " + string.Join("; ", interceptor.ParameterRanges));
        }
    }
}

sealed class NeverConnect : DbConnectionInterceptor
{
    public override InterceptionResult ConnectionOpening(DbConnection connection, ConnectionEventData eventData, InterceptionResult result)
        => InterceptionResult.Suppress();

    public override ValueTask<InterceptionResult> ConnectionOpeningAsync(DbConnection connection, ConnectionEventData eventData,
        InterceptionResult result, CancellationToken cancellationToken = default)
        => ValueTask.FromResult(InterceptionResult.Suppress());
}

sealed class SyntheticDatabase : DbCommandInterceptor
{
    public int Commands { get; private set; }
    public int MaxParameters { get; private set; }
    public int JsonCommands { get; private set; }
    public List<string> ParameterRanges { get; } = [];

    public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(DbCommand command, CommandEventData eventData,
        InterceptionResult<DbDataReader> result, CancellationToken cancellationToken = default)
    {
        Commands++;
        MaxParameters = Math.Max(MaxParameters, command.Parameters.Count);
        if (command.Parameters.Count > 0)
            ParameterRanges.Add($"{command.Parameters[0].ParameterName}..{command.Parameters[command.Parameters.Count - 1].ParameterName}");
        if (command.CommandText.Contains("OPENJSON", StringComparison.OrdinalIgnoreCase)) JsonCommands++;
        var table = new DataTable();
        table.Columns.Add("Id", typeof(int));
        if (command.CommandText.Contains("JOIN", StringComparison.OrdinalIgnoreCase))
        {
            // Collection statements project Child.Id, Child.RootId and Root.Id; all children are empty.
            table.Columns.Add("RootId", typeof(int));
            table.Columns.Add("ParentId", typeof(int));
        }
        else
        {
            table.Rows.Add(1);
        }
        return ValueTask.FromResult(InterceptionResult<DbDataReader>.SuppressWithResult(table.CreateDataReader()));
    }
}

sealed class ReproContext(DbContextOptions<ReproContext> options) : DbContext(options)
{
    public DbSet<Root> Roots => Set<Root>();

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Root>().ToTable("Roots");
        for (var i = 1; i <= 12; i++)
        {
            var navigation = typeof(Root).GetProperty($"Children{i:00}")!;
            var childType = navigation.PropertyType.GenericTypeArguments[0];
            builder.Entity(childType).ToTable($"Children{i:00}");
            builder.Entity<Root>().HasMany(childType, navigation.Name).WithOne().HasForeignKey("RootId");
        }
    }
}

sealed class Root
{
    public int Id { get; set; }
    public List<Child<Tag01>> Children01 { get; set; } = [];
    public List<Child<Tag02>> Children02 { get; set; } = [];
    public List<Child<Tag03>> Children03 { get; set; } = [];
    public List<Child<Tag04>> Children04 { get; set; } = [];
    public List<Child<Tag05>> Children05 { get; set; } = [];
    public List<Child<Tag06>> Children06 { get; set; } = [];
    public List<Child<Tag07>> Children07 { get; set; } = [];
    public List<Child<Tag08>> Children08 { get; set; } = [];
    public List<Child<Tag09>> Children09 { get; set; } = [];
    public List<Child<Tag10>> Children10 { get; set; } = [];
    public List<Child<Tag11>> Children11 { get; set; } = [];
    public List<Child<Tag12>> Children12 { get; set; } = [];
}

sealed class Child<T>
{
    public int Id { get; set; }
    public int RootId { get; set; }
}

sealed class Tag01;
sealed class Tag02;
sealed class Tag03;
sealed class Tag04;
sealed class Tag05;
sealed class Tag06;
sealed class Tag07;
sealed class Tag08;
sealed class Tag09;
sealed class Tag10;
sealed class Tag11;
sealed class Tag12;

EF Core version

10.0.13 (also reproduced on 10.0.12)

Database provider

Microsoft.EntityFrameworkCore.SqlServer 10.0.13 (also 10.0.12); no database connection required

Target framework

net10.0; runtime .NET 10.0.12; SDK 10.0.401

Operating system

Windows x64

IDE

.NET CLI, Release build

Lingua principale
C#
Stelle
14.8k
Fork
3.5k
Merge medio
3g 7h
PR unite (30g)
182

Preparare l'ambiente

Apri in Codespaces

Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di dotnet/efcore

Tutte le issue di dotnet/efcore

Issue simili

Altre issue su C#

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.