Skip to content

CancellationToken registration leak, regression #1810

Closed

Description

@tlecomte

Describe the bug

After updating to SqlClient 5.0.1, we observe a memory leak in our application. Memory dumps show a huge amount of CancellationTokenSource+CallbackNode entries (we had a dump with 2 GB of those), referencing SqlCommand objects.

We believe this might be due to the changes in:

With the changes in these PRs, it seems the CancellationToken registration is not always disposed. There are several if blocks that may return before the registration object gets to be saved in the context. And exceptions could also be thrown.

To reproduce

using Microsoft.Data.SqlClient; // 5.0.1
using System.Threading;
using System.Threading.Tasks;

public static class Program
{
    public static async Task Main()
    {
        const string query = "SELECT 1";

        // this could be the application lifetime cancellation
        // or another form of global shared cancellation
        using var longRunningCts = new CancellationTokenSource();

        var connectionString = new SqlConnectionStringBuilder
        {
            DataSource = "(local)",
            IntegratedSecurity = true,
            TrustServerCertificate = true,
        }.ToString();

        try
        {
            using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(longRunningCts.Token))
            using (var connection = new SqlConnection(connectionString))
            {
                await connection.OpenAsync(linkedCts.Token);

                using (var command = new SqlCommand(query, connection))
                using (var reader = await command.ExecuteReaderAsync(linkedCts.Token))
                {
                    linkedCts.Cancel();

                    while (await reader.ReadAsync(linkedCts.Token))
                    {

                    }
                }
            }
        }
        catch (Exception e)
        {

        }

        // => attach a debugger here
        // linkedCts as well as all the SQL objects have been disposed above
        // however a memory snapshot shows that the CancellationTokenSource+Registrations and CancellationTokenSource+CallbackNode are still there, including the objects they reference
        // so garbage collection cannot happen correctly
    }
}

Expected behavior

No memory leak, CancellationTokenSource+CallbackNode entries are not present in a dump.

Further technical details

Microsoft.Data.SqlClient version: 5.0.1
.NET target: .NET 6.0.3
SQL Server version: SQL Server 2019
Operating system: Windows 2019

Additional context

Activity

  1. lcheunglci commented on Oct 20, 2022

    @lcheunglci
    Contributor

    Hi @tlecomte, thanks for bringing this to our attention. We'll look into it soon.

  2. tlecomte commented on Oct 21, 2022

    @tlecomte
    Author

    Thanks @lcheunglci.
    FYI I edited the issue to add a code sample to reproduce the problem.

  3. Wraith2 commented on Oct 25, 2022

    @Wraith2
    Contributor

    There's a fairly simple way to solve it using a mutable ref struct to hold the registration and then the context can Take() it if needed. If the struct has a value when it disposes then you dispose the value if not then it's been taken and is now owned by the context which will clean it up.

  4. added
    Regression 💥
    and removed on Oct 25, 2022
  5. Shane32 commented on Nov 1, 2022

    @Shane32

    I'm having this issue also. After moving to 5.0.1 my Linux server would leak memory rapidly until crashing. Analyzing a memory dump revealed millions of instances of SqlCommand rooted only by the cancellation token registration (CallbackNode). Even after just a couple hours, I can confirm that reverting to 5.0.0 has solved the problem. For an in-depth analysis, including dump screen shots, system configuration, and other information, please see this issue:

    image

    (Azure App Service - Linux - Memory Working Set - last 30 days)

    image

    (Azure App Service - Linux - Memory Working Set - last 3 days)

    I recommend marking 5.0.1 as unstable on NuGet for three reasons:

    1. This bug potentially affects anyone that has SQL code continuously or periodically executing within a BackgroundService, which is probably common enough.
    2. The bug is not necessarily obvious (if the memory leak is small), and is very difficult to track down and diagnose, and even harder to write a test for. (I spent probably 40 hours on this.)
    3. The severity of the bug is such that it can often result in the application crashing. Not only that, it can crash other applications within the same server/VM. (For me, it affected all web apps within within same Azure App Service Plan.)
  6. dmytro-gokun commented on Nov 1, 2022

    @dmytro-gokun

    Same here

  7. Wraith2 commented on Nov 1, 2022

    @Wraith2
    Contributor

    It's not really a leak. A leak would be if we somehow had unreferenced memory filling memory and being unreclaimable. This is unwanted retention. It's also not how it used to work.

    I do find it odd that you're seeing so big a problem. From my understanding of the change that caused it the retention should only happen if you pass in a cts to a query execution which then returns before any query is required, doesn't that mean that large quantities of your queries are pointless because they're not going to succeed?

  8. Shane32 commented on Nov 1, 2022

    @Shane32

    I have not been able to understand how the bug affects my code yet. The code snapshot was taken after about an hour of running. There was 400 retained instances of SqlCommand, yet there was about 4.7 million CallbackNode instances at the time of the snapshot (see here for more details). The cancellation token for these references have an application lifetime and are never signaled. The code runs periodically and executes a few queries; perhaps several. Any exceptions in any of this code would have been logged; as far as I know all the code works just fine. So I don't really see how 4 million of anything could possibly have been executed in that timeframe. Unless it was individual packets of data I suppose, and even that would be a stretch. However, 400 SQL calls over an hour for this code sounds about right.

    The rest of the codebase stems from ASP.NET Core and seems to be unaffected; perhaps ASP.NET Core releases the reference to the CancellationTokenSource after each request is finished. It's also possible that all the code is affected and I am simply interpreting the memory dump incorrectly.

    Note that all my data access is through the linq2db data access layer. I do not use EF in this project, nor do I access SqlClient directly.

    I'd be happy to help diagnose this further....if I can. So far I have not been able to create a small code sample that reproduces the bug.

  9. Wraith2 commented on Nov 1, 2022

    @Wraith2
    Contributor

    You could see if you can reproduce the issue with the artifacts from the PR i opened to fix this #1818 if you can then i'll need to rework, otherwise we just wait for it to be merged and released.

  10. JRahnama commented on Nov 1, 2022

    @JRahnama
    Contributor

    You could see if you can reproduce the issue with the artifacts from the PR i opened to fix this #1818 if you can then i'll need to rework, otherwise we just wait for it to be merged and released.

    We are planning to release next preview on Tuesday 8th, if you can provide the feedback before that date, we will be able to include this PR, otherwise it will go to next year after GA release of 5.1

  11. ErikEJ commented on Nov 1, 2022

    @ErikEJ
    Contributor

    @JRahnama any chance to get the TimeOnly DateOnly PR in before next preview then?

  12. JRahnama commented on Nov 1, 2022

    @JRahnama
    Contributor

    @JRahnama any chance to get the TimeOnly DateOnly PR in before next preview then?

    It is included in preview2 milestone and hopefully will get merged for next preview release unless reviewers find some odd behaviors/regression in the changes.

  13. Shane32 commented on Nov 2, 2022

    @Shane32

    You could see if you can reproduce the issue with the artifacts from the PR i opened to fix this #1818 if you can then i'll need to rework, otherwise we just wait for it to be merged and released.

    We are planning to release next preview on Tuesday 8th, if you can provide the feedback before that date, we will be able to include this PR, otherwise it will go to next year after GA release of 5.1

    I installed the nuget package and will report tomorrow with a memory usage graph. I can verify that it is loaded in memory on my production server as this code now returns "5.00-pull.55891" in the live environment:

        private string GetSqlClientVersion()
        {
            // pull a linq2db data context from DI
            using var scope = _serviceScopeFactory.CreateScope();
            var db = scope.ServiceProvider.GetRequiredService<HiveDataContext>();
            // create a DbConnection instance
            using var dbConnection = db.DataProvider.CreateConnection(db.ConnectionString!);
            // get the "ProductVersion" from the assembly
            var assembly = dbConnection.GetType().Assembly;
            var fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location);
            return fileVersionInfo.ProductVersion;
        }
  14. 8 remaining items

  15. Tornhoof commented on Nov 8, 2022

    @Tornhoof

    May I suggest to release a 5.0.2 anyway?
    The new EF 7 SQL Server package depends on 5.0.1 now.
    see Microsoft.EntityFrameworkCore.SqlServer

    You might want to reconsider ;)

    Afaik Nuget automatically resolves the lowest version of a package which fits the constraints, so until a new EF Core SqlServer Package is released referencing a new version of the client package (be it 5.0.2 or 5.1) everyone need to manually reference the fixed package.

  16. Wraith2 commented on Nov 9, 2022

    @Wraith2
    Contributor

    Sounds like a good idea. We'll have to make sure the EFCore team are aware that they might get some problems with the current version and I'm sure they'll pick up the later version as soon as it's available

    /cc @ajcvickers @roji

  17. roji commented on Nov 9, 2022

    @roji
    Member

    Yep, we're very aware. I think it makes sense for an EF Core patch release to take a dependency on the SqlClient 5.0.2, when that's released - we'll be discussing that.

  18. paalandreassen commented on Nov 22, 2022

    @paalandreassen

    We are seeing crashing AKS K8S pods with OutOfMemory exceptions after upgrading to 5.0.1. Seems memory usage increases 10-20 MB for each processing run which involves efcore. You really can't leave this bug and not fix it until 5.1.0 is out. You konw the reason and how to fix it, so please come together with the efcore guys and release both 5.0.2 and an updated ef 7 package the requires 5.0.2 at the same time. Thank you.

  19. ErikEJ commented on Nov 22, 2022

    @ErikEJ
    Contributor

    @paalandreassen You can use 5.1 preview 2 today and add an explicit reference to it in your EF Core project.

  20. paalandreassen commented on Nov 22, 2022

    @paalandreassen

    @paalandreassen You can use 5.1 preview 2 today and add an explicit reference to it in your EF Core project.

    Is 5.1 preview 2 production ready? I really try to avoid preview releases in production.

  21. ErikEJ commented on Nov 22, 2022

    @ErikEJ
    Contributor
  22. stevendarby commented on Dec 18, 2022

    @stevendarby

    Any decision about a 5.0.2?

  23. ErikEJ commented on Dec 18, 2022

    @ErikEJ
    Contributor

    @stevendarby 5.1 preview is out today, and 5.1 will appear beginning of next month.

  24. stevendarby commented on Dec 18, 2022

    @stevendarby

    I know but as per above discussions, 5.0.2 would seem like a really good idea and I wanted to know if a decision was made about whether that was going to happen.

  25. CodeAngry commented on Dec 27, 2022

    @CodeAngry

    Just putting this here as it's a Test that seems to work.

    • in 5.0.1 referenced == references.Count so no reference is lost.
    • in 5.0.0 referenced is usually 1 and sometimes 0.
    const string connectionString = "Server=lpc:localhost;" +
    	"Integrated Security=True;Encrypt=False;" +
    	"MultipleActiveResultSets=False;Pooling=False;";
    
    using CancellationTokenSource cts = new();
    cts.CancelAfter(TimeSpan.FromMinutes(1));
    CancellationToken ct = cts.Token;
    
    List<WeakReference<SqlConnection>> references = new(100);
    for (int it = 0; it < 100; ++it)
    {
    	using SqlConnection connection = new(connectionString);
    	references.Add(new(connection));
    	await connection.OpenAsync(ct);
    
    	using SqlCommand command = connection.CreateCommand();
    	command.CommandText = "select cast(1 as bit);";
    
    	using SqlDataReader reader = await command.ExecuteReaderAsync(ct);
    	if (await reader.ReadAsync(ct))
    	{
    		_ = reader.GetBoolean(0);
    	}
    }
    
    SqlConnection.ClearAllPools();
    GC.Collect();
    
    int referenced = references.Where(i => i.TryGetTarget(out _)).Count();
    Console.WriteLine("References: {0:N0} of {1:N0}", referenced, references.Count);
    Debug.Assert(referenced != references.Count);
    
  26. Shane32 commented on Dec 27, 2022

    @Shane32

    FYI @CodeAngry the bug occurs when the SQLClient already has the data cached for the call to ReadAsync. So for a proper test, you’d want to call ReadAsync at least twice; the bug triggers on the second call. I’m your example, just reading a second time (which should return false) should be enough.

    You can also use reflection to determine the exact number of lost registrations without relying on GC behavior. See code snippet at #1810 (comment)

    Perhaps your code is triggering the bug in a way I’m unaware however.

  27. CodeAngry commented on Dec 27, 2022

    @CodeAngry

    @Shane32 My StackOverflow post (mentioned right above) has a infinite loop that triggers it. One ReadAsync() per DataReader is enough. Nice code, thanks!

  28. aarondandy commented on Jan 6, 2023

    @aarondandy

    I think many out there (like me) who took way too long to discover this as the root cause are going to really appreciate upgrading to 5.1.0 when it is released.
    image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Regression 💥

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions