Skip to content

[API Proposal + Bug] Make IListProvider public #48805

Closed

Description

@mikernet

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

  1. added
    api-suggestion
    on Feb 26, 2021
  2. ghost added
    untriaged
    on Feb 26, 2021
  3. changed the title [-][API Proposal] Make IListProvider public[/-] [+][API Proposal + Bug] Make IListProvider public[/+] on Feb 26, 2021
  4. mikernet commented on Feb 26, 2021

    @mikernet
    ContributorAuthor

    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 calling IEnumerable<T> members should not create bugs, especially ones this difficult to trace. There needs to be a mechanism that collection types can use like the IListProvider interface 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.

  5. Pzixel commented on Feb 26, 2021

    @Pzixel

    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.

  6. mikernet commented on Feb 26, 2021

    @mikernet
    ContributorAuthor

    To be honest I'm more concerned about the ConcurrentDictionary issue 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 as ConcurrentDictionary when used with LINQ - the Count can change at any time and thus the same Count / CopyTo synchronization problem mentioned here also applies to the weak collections.

  7. Pzixel commented on Feb 26, 2021

    @Pzixel

    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

  8. mikernet commented on Feb 26, 2021

    @mikernet
    ContributorAuthor

    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 implement IListProvider would 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.

  9. Pzixel commented on Feb 26, 2021

    @Pzixel

    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.

  10. mikernet commented on Feb 26, 2021

    @mikernet
    ContributorAuthor

    It's a 1 in a million operation concurrency race condition that is documented in the link. As per the link above:

    If the collection size concurrently changes between the array allocation and the CopyTo, we could end up either getting an exception from overrunning the array (if the size went up) or we could end up not filling as many items as 'count' suggests (if the size went down). This is only an issue for concurrent collections that implement ICollection, which as of .NET 4.6 is just ConcurrentDictionary<TKey, TValue>.

    The example is simply concurrently adding objects to the ConcurrentDictionary while calling any LINQ operation that uses Buffer, such as ToList().

  11. Pzixel commented on Feb 26, 2021

    @Pzixel

    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 ConcurrentDictionary doesn't implement interface which is not supposed to work with any kind of multithreading.

  12. mikernet commented on Feb 26, 2021

    @mikernet
    ContributorAuthor

    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 the ConcurrentDictionary. 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 IListProvider is already there, it would be incredibly simple to implement its 2 methods on ConcurrentDictionary and 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 ToList and ToArray safely, it literally just needs to say that it implements that interface and it would be thread safe to call LINQ operations on it.

  13. Pzixel commented on Feb 26, 2021

    @Pzixel

    Why ConcurrentDictionary is special here? LINQ is just not supposed to work in multithreaded environment. Look at this snippet

    void Main()
    {
    	var list = new List<int>();
    	var semaphor = new SemaphoreSlim(1);
    	var tasks = Enumerable.Range(1, 100).Select(async i =>
    	{
    		try
    		{	        
    			await semaphor.WaitAsync();
    			await Task.Delay(1);
    			list.Add(i);
    		}
    		finally
    		{
    			semaphor.Release();
    		}
    	});
    	
    	var items = list.OrderBy(x => x);
    	Task.Run (() => Task.WaitAll(tasks.ToArray()));
    	
    	while (list.Count < 100) {
    		items.ToArray().Dump();
    	}
    }

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

    Enumerating the dictionary is thread safe

    Right

    thus calling LINQ methods on it should be thread safe

    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 IEnumerable representation then you would be right. But it's not. For example Select(Identity) should change anything at all, it's a no-op but if you add one

    // var items = list.OrderBy(x => x);
    var items = list.Select(x => x).OrderBy(x => x);

    Suddenly the snippet stop failing and works just fine

  14. 18 remaining items

  15. stephentoub commented on Feb 26, 2021

    @stephentoub
    Member

    That said, this issue still has the outstanding topic of what I can do about the weak collections implementing ICollection<>

    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.

  16. mikernet commented on Feb 26, 2021

    @mikernet
    ContributorAuthor

    My enumerator is safe. The issue is that GetEnumerator() does not get called if my collection implements ICollection<T> because of the Count/CopyTo() optimization issue. I also asked this question above:

    Is there any way to guarantee the GC does not run between the Count call and the CopyTo call nor during the CopyTo call? If so I could make that work

    The only issue is a GC collection happening that removes items from the collection.

    Thanks for some of the other suggestions. Not implementing ICollection but adding an IWeakCollection interface that has an AsCollection() method on it may work if I can't figure out how to get the GC not to run.

  17. stephentoub commented on Feb 26, 2021

    @stephentoub
    Member

    The only issue is a GC collection happening that removes items from the collection.

    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.

  18. mikernet commented on Feb 26, 2021

    @mikernet
    ContributorAuthor

    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.

  19. stephentoub commented on Feb 26, 2021

    @stephentoub
    Member

    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.

    That means your CopyTo is copying the full list rather than what it knows to be the current count? That sounds broken.

  20. mikernet commented on Feb 26, 2021

    @mikernet
    ContributorAuthor

    No, it goes like this in the Buffer implementation

    var array = new[collection.Count];
    // GC runs here on weak collection, or items are removed from the ConcurrentDictionary
    collection.CopyTo(array); // weak collection / ConcurrentDictionary have less items so array now has a bunch of default values at the end.
  21. mikernet commented on Feb 26, 2021

    @mikernet
    ContributorAuthor

    So ideally, I would like to ensure the GC does not run where the // GC runs here line is, but I have a feeling that isn't possible.

  22. Pzixel commented on Feb 26, 2021

    @Pzixel

    Empty elements are still elements and still have to be copied.

  23. stephentoub commented on Feb 26, 2021

    @stephentoub
    Member

    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.

  24. mikernet commented on Feb 26, 2021

    @mikernet
    ContributorAuthor

    I don't know what you are saying @Pzixel.

  25. Pzixel commented on Feb 26, 2021

    @Pzixel

    GC doesn't remove anything, it's not how it works. It only make some WeakRef have null Target but that's it. And I don't see why they shouldn't be copied via CopyTo method - it's just bunch of regular structures.

  26. mikernet commented on Feb 26, 2021

    @mikernet
    ContributorAuthor

    Because the enumerator in my collections do not return collected items, it skips over them. I know how the GC works 😋

  27. mikernet commented on Feb 26, 2021

    @mikernet
    ContributorAuthor

    I think I'm just going to go with adding IWeakCollection / IReadOnlyWeakCollection interfaces for now and the user can just ToList() the weak collection or whatnot if they need to pass it to something expecting an ICollection, probably safer that way anyway for interoperating with other code that depends on particular ICollection behavior.

    I still think that ConcurrentDictionary with 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 the ICollection<T>.ToArray() DIM idea as per your suggestion.

  28. ghost locked as resolved and limited conversation to collaborators on Mar 28, 2021
  29. removed
    untriaged
    on Apr 19, 2021
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

    api-suggestionarea-System.Collections

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions