You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Query: Allow non static methods in top level projection #13048
Console.WriteLine("Take 1st snapshot!");Console.ReadLine();for(vari=0;i<10;i++)using(varcontext=newTestContextSql()){varrepo=newRepository(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.varquery=repo.GetInt();varlist=query.ToList();}Console.WriteLine("Force GC");GC.Collect();Console.WriteLine("Take 2nd snapshot");Console.ReadLine();
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.
@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.
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).
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.
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.
@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.
@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.
Activity
ajcvickers commentedon Aug 20, 2018
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:
Note that the repository holds a reference to the context. Removing the opaque call makes the leak go away:
ksmithRenweb commentedon Aug 21, 2018
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.
ajcvickers commentedon Aug 21, 2018
@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.
ajcvickers commentedon Aug 28, 2018
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).
ajcvickers commentedon Jan 23, 2019
For triage: discuss workarounds.
ajcvickers commentedon Jan 25, 2019
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:
Mart-Bogdan commentedon Feb 9, 2019
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.
MichaConrad commentedon Apr 9, 2019
@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.
21 remaining items
[-]Memory Leak[/-][+]Query: Allow non static methods in top level projection[/+]smitpatel commentedon Nov 22, 2019
Since 3.0, now we throw exception when we capture something problematic in the query cache entry.
Further items,
toffuser commentedon Mar 9, 2020
I have the same problem, even if I dispose the context the Memory goes up. Any news ?
smitpatel commentedon Mar 9, 2020
@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.
LucasLopesr commentedon Oct 10, 2021
same problem here, any news ?
roji commentedon Oct 10, 2021
@LucasLopesr see @smitpatel's comment just above - which version of EF Core are you using?