Skip to content

Static AttributesToAvoidReplicating is not Thread Safe #334

Closed

Description

@BrunoJuchli

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 AttributesToAvoidReplicating part of a specific ProxyGenerator Instance. Means attributes need to be supplied when creating it. Also means;
    • breaking change
    • AttributesToAvoidReplicating configuration 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 AttributesToAvoidReplicating thread safe
    • suggestion: use Interlocked.CompareExchange in Add to replace the backing collection.
    • performance overhead should be negliglible as Add is only called a few times...

Activity

  1. stakx commented on Jan 24, 2018

    @stakx
    Member

    I can't find any calls to .Add (apart from the static constructor of AttributesToAvoidReplicating) neither in the code base of Castle.Core, our own source code, nor any 3rd party assemblies we are employing (Moq being the only other one which actually references the Castle.Core assembly, too).

    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.)

    Don't know whether there are any known use cases for this feature?

    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).

  2. BrunoJuchli commented on Jan 24, 2018

    @BrunoJuchli
    ContributorAuthor

    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

    • our code is creating a proxy
      while
    • MOQ's type initializer calling AttributesToAvoidReplicating.Add

    kaboom ;-)

    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.

  3. changed the title [-]InvalidOperationException in AttributesToAvoidReplicating[/-] [+]Static AttributesToAvoidReplicating is not Thread Safe[/+] on Jan 24, 2018
  4. BrunoJuchli commented on Jan 24, 2018

    @BrunoJuchli
    ContributorAuthor

    @stakx thanks again

    @jonorossi @kkozmic
    If you tell which way to go I'll provide a PR. Thanks!

  5. jonorossi commented on Jan 24, 2018

    @jonorossi
    Member

    I guess I made this worse with 9a3567a in v4.0, it didn't have the enumeration before, however Add still wasn't thread safe but only called List<>.Contains before List<>.Add.

    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.

    Yep exactly, as the CLR obviously won't let anything call AttributesToAvoidReplicating.Add before AttributesToAvoidReplicating's class constructor has finished.

    Two alternative suggestions for fixing the issue:

    • make AttributesToAvoidReplicating part of a specific ProxyGenerator Instance. Means attributes need to be supplied when creating it. Also means;
      • breaking change
      • AttributesToAvoidReplicating configuration 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 AttributesToAvoidReplicating thread safe
    • suggestion: use Interlocked.CompareExchange in Add the backing collection.
    • performance overhead should be negliglible as Add is only called a few times...

    AttributesToAvoidReplicating was designed as a static class so for example a user of Moq could add another attribute without needing access to the ProxyGenerator instance 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 just Exchange) 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 our Lock class like most of DP (which uses a ReaderWriterLock or Monitor on .NET 3.5), or a basic lock statement like StrongNameUtil, or lock on 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 Add from 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 of AttributesToAvoidReplicating is a good thing, but we should still fix the threading issue.

    Can anyone tell me where I can find Castle.Core.4.2.1.symbols.nupkg

    https://ci.appveyor.com/project/castleproject/core/build/4.2.1/artifacts

  6. jonorossi commented on Jan 24, 2018

    @jonorossi
    Member

    ... 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.

    @stakx it definitely does, the Common Language Infrastructure (CLI) spec, ECMA-335 states:

    II.10.5.3.1 Type initialization guarantees
    The CLI shall provide the following guarantees regarding type initialization (but see also §II.10.5.3.2 and §II.10.5.3.3):

    1. As to when type initializers are executed is specified in Partition I.
    2. A type initializer shall be executed exactly once for any given type, unless explicitly
      called by user code.
    3. No methods other than those called directly or indirectly from the type initializer are
      able to access members of a type before its initializer completes execution.
  7. BrunoJuchli commented on Jan 24, 2018

    @BrunoJuchli
    ContributorAuthor

    @jonorossi

    I've provided PR #335 using Interlocked.CompareExchange and it takes care of

    Wouldn't using Interlocked.CompareExchange (or just Exchange) introduce a possible race condition where two threads could attempt to add an attribute resulting in one getting lost?

    However, the code is more complicated than simply doing lock(...) so maybe it would be better to use lock? I'm happy to make a new PR.

  8. stakx commented on Jan 24, 2018

    @stakx
    Member

    The quickest fix would actually be to just remove those calls to Add from Moq, everything it is requesting to avoid replicating are already in DP's default list.

    I thought there were a few that DynamicProxy doesn't have by default... anyways, I'll review this and remove unnecessary calls to Add from Moq.

    If I can't remove all of those calls, given that each call to Add will now re-allocate the entire array, perhaps it would be good to add a AddRange call? (In practice though calls to Add are probably going to be so rare that this isn't really worth it.)

  9. BrunoJuchli commented on Jan 25, 2018

    @BrunoJuchli
    ContributorAuthor

    @stakx

    If I can't remove all of those calls, given that each call to Add will now re-allocate the entire array, perhaps it would be good to add a AddRange call? (In practice though calls to Add are probably going to be so rare that this isn't really worth it.)

    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.

  10. stakx commented on Jan 25, 2018

    @stakx
    Member

    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.

    I came to the same conclusion: YAGNI. I'd say let's add AddRange only when repeated calls to Add actually turn out to be problematic. I just thought I'd mention it for thoroughness' sake.

  11. jonorossi commented on Jan 25, 2018

    @jonorossi
    Member

    However, the code is more complicated than simply doing lock(...) so maybe it would be better to use lock? I'm happy to make a new PR.

    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.

    If I can't remove all of those calls, given that each call to Add will now re-allocate the entire array, perhaps it would be good to add a AddRange call? (In practice though calls to Add are probably going to be so rare that this isn't really worth it.)

    I came to the same conclusion: YAGNI. I'd say let's add AddRange only when repeated calls to Add actually turn out to be problematic. I just thought I'd mention it for thoroughness' sake.

    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.

  12. BrunoJuchli commented on Jan 25, 2018

    @BrunoJuchli
    ContributorAuthor

    @jonorossi done and done

  13. added this to the vNext milestone on Jan 25, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions