System.Linq.Expression.Invoke not thread safe on lambda argument.
This is a crazy bug that took me awhile to track down.
System.Expression.Invoke will modify its lambda argument, making it unsafe if the lambda can be changed in a field updated by another thread. This simple test illustrates the problem:
using System;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Threading.Tasks;
public class Indirect
{
public Func<int> DoItA = () => 0;
public Func<int> DoItB = () => 0;
private int Count = 1;
public void Refresh()
{
{
var valueA = DoItA();
var valueB = DoItB();
Debug.Assert(valueA == valueB);
}
var idx = Count;
Count += 1;
DoItA = () => idx;
DoItB = DoItA;
}
public static Action Compile(Indirect ind)
{
var ind0 = Expression.Constant(ind);
var fld = Expression.PropertyOrField(ind0, "DoItA");
var block = Expression.Block(typeof(void), Expression.Invoke(fld));
return (Action)Expression.Lambda(block).Compile();
}
public static void DoTest()
{
var ind = new Indirect();
Task.Run(() =>
{
while (true)
ind.Refresh();
});
var act = Compile(ind);
Task.Run(() =>
{
while (true)
act();
});
}
}
Note that DoItA and DoItB are apparently only modified by the Refresh call that occurs in the first task forked by DoTest. However, the assertion will eventually fail because the mere invocation of the lambda through a field can cause that field to retain its value even if it is modified by another thread during the invocation!
The work around on the user side is to load the field into a temporary variable and invoke on that variable. Not a big deal, but the fact that Expression.Invoke is not thread safe on its lambda argument is not documented...either it should be thread safe (by not storing into its lambda operand argument, which is really unexpected behavior), or it should be documented that it could do this.
It is documented though:
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
https://msdn.microsoft.com/en-us/library/system.linq.expressions.expression%28v=vs.110%29.aspx
That is vague and not useful...in particular, it doesn't tell me what parts need to be protected by locks. The InvocationExpression returned by the static method? The code compiled from the invocation expression (basically, meaning it can only be used in single threaded contexts)? Why isn't:
var ind0 = Expression.Constant(ind);
var fld = Expression.PropertyOrField(ind0, "DoItA");
var block = Expression.Block(typeof(void), Expression.Invoke(fld));
return (Action)Expression.Lambda(block).Compile();
just equivalent to:
return new Action(() => ind.DoItA());
the latter being perfectly thread safe, ind.DoItA() doesn't modify the mutable field ind.DoItA! The current semantics of Expression.Invoke are more like this:
just equivalent to:
return new Action(() => {
var lmb = ind.DoItA;
var ret = lmb();
ind.DoItA = lmb; // why????
});
Is it just because the DLR isn't thread safe for the code it generates that we just can't use it in a multi-threaded context? Could we reasonably assume that Expression.Add does not change its operands in addition to do computing a fairly functional add? Why wouldn't Expression.Invoke be similar?
Since Expression.Invoke is so dangerous, I'll just wrap it in my own thing. I hope this is the only case though, and it would be nice to share this with the community just in case someone else runs into this issue in the future.
It's the case that none of of it guaranteed to be thread-safe, which is normal for instance methods throughout the framework.
That said, for Invoke() to write back to its argument does not seem very useful, with dangers beyond thread-safety; while Invoke() cannot be thread-safe (it can be explicitly asked to do explicitly non-thread-safe things, after all), and we can reasonably assume that reading from different threads won't be un-thread-safe when combined only with reading from different threads.
How are you running this? I tried it with a simple caller thus:
public void Main(string[] args)
{
Indirect.DoTest();
while(true)
{
Task.Delay(10000); // Keep application alive
}
}
And I haven't seen the assertion fail yet.
Good point! Let me come up with an example that doesn't involve threads:
public class NoThread
{
public Func<NoThread, int> DoItA = (nt) =>
{
nt.DoItA = (nt0) => 1;
return 0;
};
public static Action Compile(NoThread ind)
{
var ind0 = Expression.Constant(ind);
var fld = Expression.PropertyOrField(ind0, "DoItA");
var block = Expression.Block(typeof(void), Expression.Invoke(fld, ind0));
return (Action)Expression.Lambda(block).Compile();
}
public static void DoTestA()
{
var nt = new NoThread();
nt.DoItA(nt);
Debug.Assert(nt.DoItA(nt) == 1);
}
public static void DoTestB()
{
var nt = new NoThread();
var act = Compile(nt);
act();
Debug.Assert(nt.DoItA(nt) == 1);
}
}
DoTestA() does not crash while DoTestB() does crash. I see no reasonable interpretation where DoTestB() should crash.
I am running this from a UWP application, since that is the context of my project. So I call Indirect.DoTest() from the OnLaunched method of a custom Application object.
If I run it from:
public sealed partial class App3
{
public static void Main(string[] args)
{
Indirect.DoTest();
while (true)
{
Task.Delay(10000); // Keep application alive
}
return;
}
}
It still crashes. I'm not sure what my library versions are, UWP is weird in that it doesn't let me easily see what the version of my assemblies are. Ok, it seems like this is 10.0.10240.0. If you can't reproduce, it might be in some code that has already been updated or in something that isn't here. This might just be a Windows bug and I'm blathering to the wrong place!
Good catch. This looks like another issue with the expression interpreter we're in the process of beefing up. From a quick inspection, the compiler and interpreter (which is used when compiling using .NET Native) don't agree on outcomes. I'll push a PR with the test case.
Thanks, I'm glad I'm not crazy :)
I'm using an interpreter for my DLR code? Is there a way I can use the compiler and still make a universal windows app? I'm really relying on the DLR to generate JIT compiled code for my dynamic programming environment.
If you have a debugger, you can inspect the delegate returned from .Compile() to make sure. Access the .Method.Name property and see what comes back:
- lambda_method indicates the compiler is used
- Thunk indicates the interpreter is used
The interpreter is used on platforms with dynamic code generation is not available or allowed. I'm not a 100% sure about all of the project types / platform targets that ultimately lead to the use of the interpreter. @VSadov may be able to give a more detailed breakdown.
I was about the ping you @bartdesmet because I got @mcdirmid's code down to the following two tests (more informative names could no doubt be picked):
public static Func<int> DoItA = () =>
{
DoItA = () => 1;
return 0;
};
public static Func<int> DoItB = () =>
{
DoItB = () => 1;
return 0;
};
[Fact]
public static void DoTestA()
{
var fld = Expression.Field(null, typeof(BlockTests), "DoItA");
var block = Expression.Block(typeof(void), Expression.Invoke(fld));
Action act = (Action)Expression.Lambda(block).Compile(false);
act();
Assert.Equal(1, DoItA());
}
[Fact]
public static void DoTestB()
{
var fld = Expression.Field(null, typeof(BlockTests), "DoItB");
var block = Expression.Block(typeof(void), Expression.Invoke(fld));
Action act = (Action)Expression.Lambda(block).Compile(true);
act();
Assert.Equal(1, DoItB());
}
DoTestA using the compiler passes and DoTestB using the interpreter fails.
@JonHanna - Cool :-) I came to the same conclusion here. Thanks for confirming on your end too.
@JonHanna - Your test code is better; it doesn't need the object instance. Feel free to independently contribute it to the test suite. I'll have a look at the interpreter guts for invocation nodes right now.
Done, though I moved to using an instance so when it's brought into line with dotnet/corefx#4113 the two tests can be merged into one without introducing issues of whichever runs first sets the delegate the second will use.
Also changed to using the field directly rather than in a Block to reduce it down and rule out Block having some strange effect here.
@mcdirmid UWP assumes a common denominator platform, including phone and such. Dynamic compilation is specifically not supported. However, note that interpretation is not necessarily slower. It depends on many factors including how many times a given lambda is executed (compiling is expensive).
@VSadov Taking this to email since it isn't related to this problem.
The problem seems to actually be with CallExpression. A CallExpression is used by the interpreter to invoke the delegate through it's Invoke() method, and that's where the write-back happens, so that mutable structs are treated correctly. There would be other cases where this was incorrect, most obviously if one explicitly requested a CallExpression calling Invoke() on a delegate.