runtime: First class span's break EFC
Description
When enabling LangVersion preview, that enables first class span’s which then prefers MemoryExtensions.Contains over Enumerable.Contains which then breaks EFC. It seems that EFC internally calls Expression.Compile with preferInterpretation set to true which then eventually crashes.
Reproduction Steps
public class MyDbContext : DbContext
{
public DbSet<MyTable> MyTable { get; set; }
}
public class MyTable
{
public int Id { get; set; }
public string Name { get; set; }
}
string[] filters = ["Test"];
var dbContext = new MyDbContext();
dbContext.MyTable.Where(x => filters.Contains(x.Name)).ToList();
Expected behavior
First class span’s should not negatively affect EFC queries
Actual behavior
TypeLoadException: GenericArguments[1], 'System.Span`1[System.String]', on 'System.Linq.Expressions.Interpreter.FuncCallInstruction`2[T0,TRet]' violates the constraint of type parameter 'TRet'.
at System.RuntimeType.ValidateGenericArguments(MemberInfo definition, RuntimeType[] genericArguments, Exception e)
at System.RuntimeType.MakeGenericType(Type[] instantiation)
at System.Linq.Expressions.Interpreter.CallInstruction.GetHelperType(MethodInfo info, Type[] arrTypes)
at System.Linq.Expressions.Interpreter.CallInstruction.SlowCreate(MethodInfo info, ParameterInfo[] pis)
at System.Linq.Expressions.Interpreter.CallInstruction.Create(MethodInfo info, ParameterInfo[] parameters)
at System.Linq.Expressions.Interpreter.LightCompiler.CompileMethodCallExpression(Expression object, MethodInfo method, IArgumentProvider arguments)
at System.Linq.Expressions.Interpreter.LightCompiler.Compile(Expression expr)
at System.Linq.Expressions.Interpreter.LightCompiler.CompileConvertUnaryExpression(Expression expr)
at System.Linq.Expressions.Interpreter.LightCompiler.Compile(Expression expr)
at System.Linq.Expressions.Interpreter.LightCompiler.CompileTop(LambdaExpression node)
at System.Linq.Expressions.Expression`1.Compile(Boolean preferInterpretation)
at Microsoft.EntityFrameworkCore.Query.Internal.ExpressionTreeFuncletizer.<Evaluate>g__EvaluateCore|70_0(Expression expression, String& parameterName, Boolean& isContextAccessor) in Microsoft.EntityFrameworkCore.Query.Internal\ExpressionTreeFuncletizer.cs:line 1755
Regression?
Yes, only when enabling <LangVersion>preview</LangVersion>
Known Workarounds
set <LangVersion>preview</LangVersion> to anything but preview
Configuration
.NET 9.0.0 EFC 9.0.0
Other information
No response
About this issue
- Original URL
- State: open
- Created 2 years ago
- Reactions: 17
- Comments: 27 (17 by maintainers)
Just to second @jkotas’s comment, our problem in EF is not recognizing MemoryExtensions.Contains and similar (though that in itself is also a breaking change) - it’s the reliance on the LINQ interpreter in various scenarios, but the interpreter doesn’t support this. More generally, there’s a gap that’s starting to widen between C# itself and its metaprogramming (and related) features: the interpreter can no longer handle any construct, and LINQ expression trees themselves only represent a small subset of C# (and getting smaller). This will become more and more problematic, unless a decision is made to start updating these components to bring them more in line with the latest C# developments.
This problem is not specific to EF Core. You can hit it with plain vanilla System.Linq.Expressions. It can be fixed in System.Linq.Expressions by adding support for byref-like types to the Interpreter, but that is in conflict with the effectively archived status of System.Linq.Expressions.
@jjonescz This needs a breaking change notice to be filled.
cc @jaredpar
It seems ironic to me that the LDM decision for this is that breaking old code that uses EF is okay when the common refrain when discussing adding new operators (e.g.
?.) toExpressionis that it breaks using EF in newer code that isn’t written yet.You can use .NET 9, just make sure you call
Enumerablemethods (e.g., by calling them in their non-extension static forms) instead ofMemoryExtensionsones. As you said, older .NETs are not supported with newer LangVersions, so workarounds like that are expected.@ChrisJollyAU and others, I think the EF strategy for dealing with this will be to perform early detection and replacing of expression nodes that cannot be interpreted, basically transforming the new tree back to the way it was - before the LINQ interpreter is ever invoked. In other words, we’d have a static, hard-coded table in EF’s funcletizer (the very first visitor that processes the incoming the tree), and would simply rewrite the tree. So from a pure EF perspective, we’ll likely be able to deal with this without any need to either disable interpretation, or something like CanInterpret.
Do you see any trouble with that approach @ChrisJollyAU?
Regardless, this will affect other users of the LINQ interpreter. I’m not sure CanInterpret would be very useful to them, and I’m generally not in love with “magically” switching between interpretation and compilation based on something that the user has no knowledge or control over (i.e. there’s a performance cliff the moment you introduce a Contains, or possibly other discrepancies). I’d at least want to discuss this with other users of the interpreter first…
Yep, that was the reason, nothing else.
Yes, adding support for ref structs in reflection has been on the reflection backlog for a while. So far we did not have a good motivating scenario to justify investing into it.
This does not work for native AOT that EF Core has been busy adding support for.
Well, the LINQ interpreter in .NET is a general component used by other users and packages out there, other than EF - they are all going to be similarly broken by this change; so if someone (regardless of who does the work) adds support to the interpreter, I don’t believe that should be part of the EF package. This is probably a conversation best taken offline…
Does this mean libraries need to fix this issue?
In that case it would mean .NET 9 (or lower) can never use the new C# LangVersion together with EF Core when First class span’s get released? You will either need to lower the C# LangVersion or upgrade .NET.
I know using newer C# LangVersions in older .NET versions isn’t official supported, but I do this together with PolySharp a lot.
When I upgraded my .NET SDK locally, I got hit by this issue; since I had
<LangVersion>preview</LangVersion>in my project during the .NET 7 to .NET 8 transition, I forgot I had the preview version still configured 😄.This was discussed at LDM with no change in the C# language planned. LINQ-to-DB should be probably updated to recognize
MemoryExtensions.Contains(and perhaps other similar methods) or users will need to update the calls (e.g., callingEnumerable.Containsexplicitly, or casting the array toIEnumerable<T>).@jjonescz @jkotas Was also thinking on this.
EFC calls the
.CompilewithpreferInterpretationbeing true.With the function being as follows
Clearly the
CanInterpretvariable is also true, even when the expression has the byref-like types/Span in it. Giving that the interpret fails it clearly can’t interpret. That’s a potential bug/mismatch there.Even if the byref-like types wasn’t added to the interpreter (if the verdict from the other mentioned issues is still valid now), I would say this part would be applicable - to make sure that the
CanConvertis false if you have those types in the expression.@roji This should satisfy you with regards to performance - those normal expressions will just be interpreted as normal, and then drop into the full compiler (which does work) for the restricted types
While
.Containsis the method giving the current problem, you would probably have to look at doing it for all methods fromMemoryExtensions@jjonescz There’s already 2 issues previously related to byref-like types and Span types in expression trees (#96160 and #27499). Both have basically said the same as @jkotas - that
System.Linq.Expressionsis effectively archived.With the new first class span support being introduced, it’s clear that there would be an increasing likelihood of more expression trees encountering the byref-like types. With this in mind, I feel the impact of that bug has changed enough to at the very least needing to be re-evaluated (and possibly implemented)
That doc says “We will consider changes that address significant bugs or regressions”. This seems like a significant regression.
So… does EF need to implement its own interpreter to avoid relying on an archived component?