Repository navigation
Description
Background and Motivation
I have some collections (specifically weak value collections) where it would be nice to have them implement ICollection<T>, but I am extremely hesitant to do that since weak collections are inherently "concurrent" (in the sense that values can be collected by the GC at any time) and thus the very commonly used ToArray() and ToList() enumerable extension methods have a high probability of returning a collection that is too large and contains some null values at the end if my collection implements ICollection<T> (see here for notes on a similar issue with ConcurrentDictionary). If I could implement IListProvider then I could provide a safe alternative that always returns the correct size array/list when the enumerable extension methods are called.
An additional benefit to making IListProvider public would come from being able to make collections like ConcurrentDictionary which live in a different assembly than IListProvider implement that interface so that the issue noted above could be mitigated and EnumerableExtensions.ToArray()/ToList() would be safe to call on it.
Update:
It appears that any LINQ methods that use Buffer (due to the call on this line) like OrderBy() are also currently unsafe to use on a ConcurrentDictionary and would become unsafe if the weak collections implemented ICollection<T>. That's a really sneaky non-deterministic and very difficult to trace intermittent heisenbug that only shows up in high load situations waiting to happen. It also violates the principle of least surprise given that ConcurrentDictionary is safe to enumerate. I certainly did not know that this was an issue - I need to go back and review all my code now.
This proposal could fix that glaring problem.
Proposed API
Make IListProvider public.
Risks
None that I can think of.
Activity
[-][API Proposal] Make IListProvider public[/-][+][API Proposal + Bug] Make IListProvider public[/+]mikernet commentedon Feb 26, 2021
If a type says it is safe to enumerate over and fulfills the
IEnumerable<T>contract, LINQ methods need to be safe to call on it. Any "hidden detail" internal optimizations that LINQ methods do above callingIEnumerable<T>members should not create bugs, especially ones this difficult to trace. There needs to be a mechanism that collection types can use like theIListProviderinterface that provides a way for those optimizations to work safely or at least some attribute like[NoLinqCollectionOptimizations]to disable those optimizations...anything less is pure insanity IMO. I would obviously prefer the former and given that it is already there and just needs to be made public that seems like the easier solution.The fact that MS provided collections that say they are safe to enumerate over while concurrently reading/writing break when using LINQ operations and this isn't heavily documented is troubling, to say the least.
Pzixel commentedon Feb 26, 2021
Could you provide some code sample with problem you're having right now? I know you have written about "weak collections" and "inherently unsafe" but it's just words. I feel you but it's not quite comprehensive what are you talking about.
Simple snippet could solve this and show the exact problem and exact value of your proposal.
mikernet commentedon Feb 26, 2021
To be honest I'm more concerned about the
ConcurrentDictionaryissue now, but sorry, let me explain "weak collections" because that probably could have used a better explanation.Weak collections are collections that store values with
WeakReference<T>so those values can be collected at any time. The enumerator for those collections skips over those values so the collection fundamentally suffers from the same issue asConcurrentDictionarywhen used with LINQ - theCountcan change at any time and thus the sameCount/CopyTosynchronization problem mentioned here also applies to the weak collections.Pzixel commentedon Feb 26, 2021
Right, as I said i've got the idea but still need some concrete example to play with. Please, show some code snippet do demonstrate the problem
mikernet commentedon Feb 26, 2021
The problem is in the BCL. For example,
concurrentDictionary.OrderBy(x => x.Value.Something)is unsafe because of the issue mentioned there. Having the dictionary implementIListProviderwould solve the issue.What else do you need to know? Not sure how I can explain that any better, the issue is explained in the code there.
Pzixel commentedon Feb 26, 2021
Could you provide a code snippet to demonstrate
concurrentDictionary.OrderBy(x => x.Value.Something)is unsafe? I don't see anything unsafe about it. This is how things are supposed to be done.mikernet commentedon Feb 26, 2021
It's a 1 in a million operation concurrency race condition that is documented in the link. As per the link above:
The example is simply concurrently adding objects to the
ConcurrentDictionarywhile calling any LINQ operation that usesBuffer, such asToList().Pzixel commentedon Feb 26, 2021
Well that's correct yet I don't see it as a bug, it's just how multithreading works. You're making an unsynchronized access to shared state and get into some troubles. And this is indeed why
ConcurrentDictionarydoesn't implement interface which is not supposed to work with any kind of multithreading.mikernet commentedon Feb 26, 2021
Enumerating the dictionary is thread safe, thus calling LINQ methods on it should be thread safe. If LINQ didn't use the
Collection<T>optimization then it would be thread-safe to call LINQ methods on theConcurrentDictionary. This is an internal implementation detail that breaks the contract provided by LINQ methods, which should be "if the object implements IEnumerable in a safe manner then LINQ methods should operate against it safely".The
IListProvideris already there, it would be incredibly simple to implement its 2 methods onConcurrentDictionaryand enable it to be thread safe, so its not "just how multithreading works". Likewise, my collection could work safely with LINQ methods if that interface was exposed.ConcurrentDictionary already has instance methods that do
ToListandToArraysafely, it literally just needs to say that it implements that interface and it would be thread safe to call LINQ operations on it.Pzixel commentedon Feb 26, 2021
Why
ConcurrentDictionaryis special here? LINQ is just not supposed to work in multithreaded environment. Look at this snippetOn my machine it eventually fails with
ArgumentException: Destination array was not long enough. Check the destination index, length, and the array's lower bounds. (Parameter 'destinationArray')You're just not supposed to alter sequence while LINQ is performing a query on it.
Right
If you don't alter it - then yes. If you do then it's not. LINQ is leaky abstraction you know. If it was only working with
IEnumerablerepresentation then you would be right. But it's not. For exampleSelect(Identity)should change anything at all, it's a no-op but if you add oneSuddenly the snippet stop failing and works just fine
18 remaining items
stephentoub commentedon Feb 26, 2021
If you're asking that enumeration see an atomic view, in your collection's enumerator you can do:
GetEnumerator() => YourThreadSafeToArray().GetEnumerator()
And don't implement ICollection, or expose a wrapper with an ICollection implementation that has atomic semantics on top of your own ToArray.
Or don't use it concurrently with any API that might check for the interface, e.g. List's ctor.
There's no magic bullet here.
mikernet commentedon Feb 26, 2021
My enumerator is safe. The issue is that
GetEnumerator()does not get called if my collection implementsICollection<T>because of theCount/CopyTo()optimization issue. I also asked this question above:The only issue is a GC collection happening that removes items from the collection.
Thanks for some of the other suggestions. Not implementing
ICollectionbut adding anIWeakCollectioninterface that has anAsCollection()method on it may work if I can't figure out how to get the GC not to run.stephentoub commentedon Feb 26, 2021
Why is that an issue? Implementations (well beyond LINQ, List, etc.) check the count and then do a copy. Adding to a ConcurrentDictionary could be a problem, but I don't see why removing from a ConcurrentDictionary would be a problem.
mikernet commentedon Feb 26, 2021
It's a problem because the array/list would contain a bunch of default values at the end of it that aren't actually in the collection.
stephentoub commentedon Feb 26, 2021
That means your CopyTo is copying the full list rather than what it knows to be the current count? That sounds broken.
mikernet commentedon Feb 26, 2021
No, it goes like this in the
Bufferimplementationmikernet commentedon Feb 26, 2021
So ideally, I would like to ensure the GC does not run where the
// GC runs hereline is, but I have a feeling that isn't possible.Pzixel commentedon Feb 26, 2021
Empty elements are still elements and still have to be copied.
stephentoub commentedon Feb 26, 2021
Oh, you meant the resulting array, not the array/list in your collection's implementation. I thought you were saying stale values from your collection were being copied, which is what I was commenting on as broken. Yes, you could end up with default values at the end.
mikernet commentedon Feb 26, 2021
I don't know what you are saying @Pzixel.
Pzixel commentedon Feb 26, 2021
GC doesn't remove anything, it's not how it works. It only make some
WeakRefhave nullTargetbut that's it. And I don't see why they shouldn't be copied viaCopyTomethod - it's just bunch of regular structures.mikernet commentedon Feb 26, 2021
Because the enumerator in my collections do not return collected items, it skips over them. I know how the GC works 😋
mikernet commentedon Feb 26, 2021
I think I'm just going to go with adding
IWeakCollection/IReadOnlyWeakCollectioninterfaces for now and the user can justToList()the weak collection or whatnot if they need to pass it to something expecting anICollection, probably safer that way anyway for interoperating with other code that depends on particularICollectionbehavior.I still think that
ConcurrentDictionarywith LINQ should be fixed though, it just seems like the only sensible thing to do given that it has a thread-safe enumerator. I'll probably open up another issue for that with theICollection<T>.ToArray()DIM idea as per your suggestion.