Repository navigation
Description
We rarely get the following exception (Castle.Core 4.2.1):
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.List1.Enumerator.MoveNextRare() at System.Collections.Generic.List1.Enumerator.MoveNext()
at System.Linq.Enumerable.Any[TSource](IEnumerable1 source, Func2 predicate)
at Castle.DynamicProxy.Generators.AttributesToAvoidReplicating.ShouldAvoid(Type attribute)
at Castle.DynamicProxy.Internal.AttributeUtil.ShouldSkipAttributeReplication(Type attribute)
at Castle.DynamicProxy.Internal.AttributeUtil.d__5.MoveNext()
at Castle.DynamicProxy.Contributors.CompositeTypeContributor.ImplementMethod(MetaMethod method, ClassEmitter class, ProxyGenerationOptions options, OverrideMethodDelegate overrideMethod)
at Castle.DynamicProxy.Contributors.CompositeTypeContributor.Generate(ClassEmitter class, ProxyGenerationOptions options)
at Castle.DynamicProxy.Generators.InterfaceProxyWithoutTargetGenerator.GenerateType(String typeName, Type proxyTargetType, Type[] interfaces, INamingScope namingScope)
at Castle.DynamicProxy.Generators.InterfaceProxyWithTargetGenerator.<>c__DisplayClass6_0.b__0(String n, INamingScope s)
at Castle.DynamicProxy.Generators.BaseProxyGenerator.ObtainProxyType(CacheKey cacheKey, Func`3 factory)
at Castle.DynamicProxy.Generators.InterfaceProxyWithTargetGenerator.GenerateCode(Type proxyTargetType, Type[] interfaces, ProxyGenerationOptions options)
at Castle.DynamicProxy.DefaultProxyBuilder.CreateInterfaceProxyTypeWithoutTarget(Type interfaceToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options)
at Castle.DynamicProxy.ProxyGenerator.CreateInterfaceProxyWithoutTarget(Type interfaceToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, IInterceptor[] interceptors)
Now, the obvious error case would be a concurrent call to AttributesToAvoidReplicating.Add<T>() or AttributesToAvoidReplicating.Add(Type attribute).
As it happens we're also using MOQ which is in fact modifying this collection.
Given that our use of MOQ happens concurrent to our own code creating proxies it's, IMHO, quite clear that this can occasionaly cause the above exception.
Even though MOQ and our own code don't share the same ProxyGenerator instance, as AttributesToAvoidReplicating is static it's being shared.
The only way (workaround) to synchronize access in this case is to cause MOQ to initialize before use Castle.Core in our own code. Of course, that's quite the design smell.
Two alternative suggestions for fixing the issue:
- make
AttributesToAvoidReplicatingpart of a specificProxyGeneratorInstance. Means attributes need to be supplied when creating it. Also means;- breaking change
AttributesToAvoidReplicatingconfiguration not leaking to other users of DynamicProxy- don't know how this will affect the cleanliness of the implementation itself, as the information would have to be passed around since it can't be static anymore...
- make
AttributesToAvoidReplicatingthread safe- suggestion: use
Interlocked.CompareExchangeinAddto replace the backing collection. - performance overhead should be negliglible as
Addis only called a few times...
- suggestion: use
Activity
stakx commentedon Jan 24, 2018
FYI, when targeting the full .NET Framework, Moq does call
AttributesToAvoidReplicating.Add:https://github.com/moq/moq4/blob/612c6fae5d8695d6d13cc028e1cc0ec86e76dca8/Source/ProxyFactories/CastleProxyFactory.cs#L74-L87
(I'd be surprised if that were the source of the error you're occasionally seeing, as the calls in question happen inside a type constructor and should run only once per
AppDomain. I am however not actually certain that .NET ensures that a type constructor only run once, even when several concurrent threads might trigger it at the same time.)Regarding Moq, I don't understand the precise details, but it seems that this feature does indeed have its uses; see e. g. this and this old Google Code issue for Moq (the latter of which got fixed in devlooped/moq@0ee8d21).
BrunoJuchli commentedon Jan 24, 2018
Can anyone tell me where I can find Castle.Core.4.2.1.symbols.nupkg? That would simplify things a lot... :-)
@stakx thanks a lot!
Apparently I was looking at the wrong repository or using GitHub search the wrong way.
In that case I'm actually pretty conviced that exactly this is causing the issue. We're running multi-threaded tests. We ourselves use Castle.DynamicProxy for interception, too. Now imagine
while
AttributesToAvoidReplicating.Addkaboom ;-)
And of course the likelihood of this is very small since MOQ's only going to call that method once. When, however, is dependent on the first access to the Type that's doing it. At that time, some other part of the application can already be creating proxies.
[-]InvalidOperationException in AttributesToAvoidReplicating[/-][+]Static AttributesToAvoidReplicating is not Thread Safe[/+]BrunoJuchli commentedon Jan 24, 2018
@stakx thanks again
@jonorossi @kkozmic
If you tell which way to go I'll provide a PR. Thanks!
jonorossi commentedon Jan 24, 2018
I guess I made this worse with 9a3567a in v4.0, it didn't have the enumeration before, however
Addstill wasn't thread safe but only calledList<>.ContainsbeforeList<>.Add.Yep exactly, as the CLR obviously won't let anything call
AttributesToAvoidReplicating.AddbeforeAttributesToAvoidReplicating's class constructor has finished.AttributesToAvoidReplicatingwas designed as a static class so for example a user of Moq could add another attribute without needing access to theProxyGeneratorinstance used by Moq. I'm pretty sure it was added as a get out of jail card when you are in a pickle with some attribute causing you grief.Wouldn't using
Interlocked.CompareExchange(or justExchange) introduce a possible race condition where two threads could attempt to add an attribute resulting in one getting lost?Performance shouldn't be a problem on this codepath as it is only called during proxy type generation. We can't use
ConcurrentBag<>because we still support .NET 3.5, however can use ourLockclass like most of DP (which uses aReaderWriterLockorMonitoron .NET 3.5), or a basiclockstatement likeStrongNameUtil, orlockon writing and just create a new List with the previous contents when you go to add a new attribute it then stays readonly for the during of the process.The quickest fix would actually be to just remove those calls to
Addfrom Moq, everything it is requesting to avoid replicating are already in DP's default list (@stakx). Anything that DP is missing should get added there anyway, most of these attributes are compiler or runtime magic attributes. Discouraging use ofAttributesToAvoidReplicatingis a good thing, but we should still fix the threading issue.https://ci.appveyor.com/project/castleproject/core/build/4.2.1/artifacts
jonorossi commentedon Jan 24, 2018
@stakx it definitely does, the Common Language Infrastructure (CLI) spec, ECMA-335 states:
BrunoJuchli commentedon Jan 24, 2018
@jonorossi
I've provided PR #335 using
Interlocked.CompareExchangeand it takes care ofHowever, the code is more complicated than simply doing
lock(...)so maybe it would be better to uselock? I'm happy to make a new PR.stakx commentedon Jan 24, 2018
I thought there were a few that DynamicProxy doesn't have by default... anyways, I'll review this and remove unnecessary calls to
Addfrom Moq.If I can't remove all of those calls, given that each call to
Addwill now re-allocate the entire array, perhaps it would be good to add aAddRangecall? (In practice though calls toAddare probably going to be so rare that this isn't really worth it.)BrunoJuchli commentedon Jan 25, 2018
@stakx
I've thought about this as well, however,.. It's just going to be called once when the type is loaded, so for the unit testing scenario it's once per test assembly. Most likely it won't have a measurable performance impact.
But I'm open to adding that code, it's not a big deal.
stakx commentedon Jan 25, 2018
I came to the same conclusion: YAGNI. I'd say let's add
AddRangeonly when repeated calls toAddactually turn out to be problematic. I just thought I'd mention it for thoroughness' sake.jonorossi commentedon Jan 25, 2018
I'd much prefer this just for maintainability/readability sake. Happy for you to just update the branch behind #335 rather than creating a new PR.
Could you please also update our changelog in the repository root.
Completely agree YAGNI, definitely a premature optimisation, creating half a dozen lists in Gen0 would likely be orders of magnitude faster than a single reflection call to get a list of members, let alone generating a single proxy type.
BrunoJuchli commentedon Jan 25, 2018
@jonorossi done and done