Skip to content

Query: Allow non static methods in top level projection #13048

Description

@ksmithRenweb

Under a specific condition, disposed context's are not being released with a GC. In production it is rapidly increasing memory usage.

Memory Analysis done with Jetbrains dotMemory.

Attached working project:
ReproduceEFCoreMemoryLeakNonStaticHelperMethods.zip

Sample from attached code:

            Console.WriteLine("Take 1st snapshot!");
            Console.ReadLine();

            for(var i=0; i<10; i++)
            using (var context = new TestContextSql())
            {
                var repo = new Repository(context); // <--- The non static helper will leave 10 instances TestContextSql in memory.
                //var repo = new RepositoryStatic(context); // <--- The static helper will leave 1 instances TestContextSql in memory.

                var query = repo.GetInt();

                var list = query.ToList();
            }

            Console.WriteLine("Force GC");
            GC.Collect();
            Console.WriteLine("Take 2nd snapshot");
            Console.ReadLine();
        public IQueryable<int> GetInt()
        {
            return _context.TestEntities.Select(t => HashCode(t.DateRange1));
        }

        private int HashCode(string dateRange1)
        {
            return dateRange1.GetHashCode();
        }

Occurs in:
EF Core 2.0.1
EF Core 2.1.1

Activity

  1. ajcvickers commented on Aug 20, 2018

    @ajcvickers
    Contributor

    Note for triage: I was able to reproduce this. The key part is that the query includes a call to an opaque instance method on the the repository:

    public IQueryable<int> GetInt()
    {
        return _context.TestEntities.Select(t => HashCode(t.DateRange1));
    }
    
    private int HashCode(string dateRange1)
    {
        return dateRange1.GetHashCode();
    }

    Note that the repository holds a reference to the context. Removing the opaque call makes the leak go away:

    public IQueryable<int> GetInt()
    {
        return _context.TestEntities.Select(t => t.DateRange1.Length);
    }
  2. ksmithRenweb commented on Aug 21, 2018

    @ksmithRenweb
    Author

    Morning,

    Last Friday I tried to keep to just the bare bones so I did not run on and on. I'll add a bit more detail today.

    I took a memory dump of a web api process running at GB's of memory when it should have been under 500 MB like all the others. I found that it was holding onto 50k context objects each with 300 KB of memory reserved.

    After a review of how we are handling context disposal and knowing that every other web api was not having this issue. I reviewed commits till i found the culprit.

    A developer wrote a couple repository helper methods, that are called during the IQueryable. Best practices say they should have been static if they could have been and they could have. The helper methods are more complex than the GetHashCode I used in the example here.

    It seems that when EF Core compiles the IQueryable it stores any such methods in a MemoryCache. Probably a really good idea for performance. But. Disposing of the context does not release those methods from the MemoryCache. Which is the Memory Leak!

    The reason that making the helper methods static negates this memory leak is due to how static works in the language. Without static, EFCore is keeping a reference to each instance of the repository and it's helper method, which happened to hold a reference to the context. Thereby not allowing GC to pick it up. With static, EFCore only keeps 1 reference to the "static" helper method. So though its still arguably a memory leak, it is very minor.

    I hope this helps understanding the issue.

  3. ajcvickers commented on Aug 21, 2018

    @ajcvickers
    Contributor

    @ksmithRenweb Sorry, I should have said that we know what the issue is. Deciding what to do about it is a different matter--it plays into #12795 because behavior is a consequence of how we evaluate the opaque method call on the client. We're considering changing some of this in 3.0.

  4. ajcvickers commented on Aug 28, 2018

    @ajcvickers
    Contributor

    Outcomes from triage discussion: detect when something problematic is being captured and then warn and don't cache (since cache entry will never be used anyway).

  5. added this to the 3.0.0 milestone on Aug 28, 2018
  6. removed this from the 3.0.0 milestone on Jan 23, 2019
  7. ajcvickers commented on Jan 23, 2019

    @ajcvickers
    Contributor

    For triage: discuss workarounds.

  8. ajcvickers commented on Jan 25, 2019

    @ajcvickers
    Contributor

    We investigated workarounds here, but the options are limited. In general, the workarounds are all about preventing state being captured where that state causes problems. In the specific cases here, that state is the context instance. For this, three things to try are:

    • Make sure the context instance (or whatever other state exists that is causing issues) isn't referenced from the method call, and hence won't be captured in the closure.
    • In some cases, this may be possible by replacing instance access with static access, like in the example above, such that the implicit reference to the context is not captured in the closure.
    • Another approach that works for the DbContext specifically is to make the method call actually be on the DbContext type. This pattern is detected and parameterized. For example, in the code above if the call is made directly on the context instead of through the repository, then it would be detected and parameterized.
  9. added this to the 3.0.0 milestone on Jan 25, 2019
  10. Mart-Bogdan commented on Feb 9, 2019

    @Mart-Bogdan

    We have encountered this issue yesterday. Actually this memory leaks was terrorizing us for quite long period, but recently we were able to trace source.

    I think, that EF should throw an exception if regular method being used inside Expression Tree used to generate DB query.
    I believe EF 6 (not core) had such behavior (as far as I remember, don't have time to check now).

    I understand that adding such behavior now could break existing code (despite it's most likely work with memory leaks, unless methods are static), so I'd suggest adding configuration flag, that would cause Exception on attempt to use Expression, which is using method defined in code, which don't map to any SQL function.

    P.S. in our case Controllers was captured inside Expression, which pooled lots of objects inside cache, like HttpContext and Request/Response objects.

  11. MichaConrad commented on Apr 9, 2019

    @MichaConrad

    @ajcvickers is there any good way of detecting code blocks which potentially could cause this issue via static code analysis?

    My team manages many different service endpoints with 1000s of lines of EF code doing all kinds of queries.
    We already found 2 occurrences causing out of memory issues (that's how I found this issue), where we for example map entities to return models, e.g. ctx.Set<Entity>().Select(p => this.Map(p))...

    Manually going through all this is pretty... .expensive though and waiting for and then upgrading to 3.0 is also not an option.

  12. 21 remaining items

  13. changed the title [-]Memory Leak[/-] [+]Query: Allow non static methods in top level projection[/+] on Nov 22, 2019
  14. smitpatel commented on Nov 22, 2019

    @smitpatel
    Contributor

    Since 3.0, now we throw exception when we capture something problematic in the query cache entry.
    Further items,

    • Rather than throwing warn and not cache entry?
    • Investigate what EF6 did. I believe @maumar did look into this in 3.0 time frame. Can you post outcome if you remember.
    • Investigate what LINQ to SQL does.
  15. removed this from the Backlog milestone on Nov 22, 2019
  16. added this to the Backlog milestone on Nov 22, 2019
  17. toffuser commented on Mar 9, 2020

    @toffuser

    I have the same problem, even if I dispose the context the Memory goes up. Any news ?

  18. smitpatel commented on Mar 9, 2020

    @smitpatel
    Contributor

    @toffuser - Which version of EF Core are you using? Starting from EF Core 3.0, this throws exception and forces users to use static methods only so you will not run into memory growth.

  19. LucasLopesr commented on Oct 10, 2021

    @LucasLopesr

    same problem here, any news ?

  20. roji commented on Oct 10, 2021

    @roji
    Member

    @LucasLopesr see @smitpatel's comment just above - which version of EF Core are you using?

  21. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions