runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Custom allocators - (size, disposal, pools, etc).

Open ayende opened this issue 11 years ago • 78 comments

One of the hardest things that we have to handle when writing server application or system software in .NET is the fact that we don't have good control over memory. This range from simple inability to state "how big is this thing" to controlling how much memory we'll use for certain operations.

In my case, working on RavenDB, there are a lot of operations that require extensive memory usage, over which we have little control. The user can specify any indexing function they want, and we'll have to respect that. When doing heavy indexing, that can cause several issues. In particular, it means that we generate a LOT of relatively short term data, during which other operations also run. Because we are system software, we are doing a lot of I/O, which require pinning memory.

The end result is that we may have memory with the following layout.

[useful objects] [ indexing garbage ] [pinned buffers doing i/o] [ indexing garbage] [ pinned buffers ]

That result in high memory fragmentation (on Gen0, mostly), which is hard to deal with.

It also means that when indexing is done, we have to cleanup quite a lot of garbage, and because the indexing garbage is mixed with stuff that is used right now, it either cannot be readily allocated or require a big compaction.

It would be great if we had greater control over memory usage. Being able to define a heap and instruct the CLR to allocate objects from it would be wonderful. We won't have request processing memory intermixed with background ops memory, and we have a good way to free a lot of memory all at once.

One option would be to do something like this:

using(var heap = Heap.Create(HeapOptions.None, 
    1024 * 1024, // initial size
    512 * 1024 * 1024)) // max size
{

  using(heap.AllocateFromMe())
  {
     var sb = new StringBuilder();
     for(var i = 0; i < 100; i ++ )
           sb.AppendLine(i);
     Console.WriteLine(sb.ToString());
  }
}

This will ensure that all allocations inside the scope are allocated on the new heap. The GC isn't involved in collecting items from this heap at all, it is the responsibility of the user to take care of that, either by explicitly freeing objects (rare) or by disposing the heap.

Usage of references to the heap after it is destroyed won't be allowed.

Alternatively, because that might be too hard / complex. Just having a way to do something like:

 heap.Allocate<MyItem>();

Would be great. Note that we can do the same right now by allocating native memory and using unsafe code to get a struct pointer back. This works, but very common types like arrays or strings cannot be allocated in this manner.

Having support for explicit usage like this would greatly alleviate the kind of gymnastics that we have to go through to manage memory.

ayende avatar Jul 14 '15 14:07 ayende

:+1: to more memory control for those that need it. I'd be happy with a way to managed memory very coarsely at the heap level. Not at useful as destructible or own values, but it is something.

whoisj avatar Jul 14 '15 15:07 whoisj

What if objects of the normal heap have references to objects in a user controlled heap? What will happen after the user heap is freed?

omariom avatar Jul 14 '15 15:07 omariom

Crash? Null reference?

This isn't meant to be something you would do lightly. And you can take responsibility for that On Jul 14, 2015 6:49 PM, "Omari Omarov" [email protected] wrote:

What if objects of the normal heap have references to objects in a user controlled heap? What will happen after the user heap is freed?

— Reply to this email directly or view it on GitHub https://github.com/dotnet/coreclr/issues/1235#issuecomment-121287169.

ayende avatar Jul 14 '15 15:07 ayende

This was mentioned also by Miguel de Icaza a couple of years ago. http://tirania.org/blog/archive/2012/Apr-04.html

@omariom We have already some sort of similar mechanism with weak references. They are nullified. This is certainly not for everyone, but it does have its uses in certain niches (even at the peril of introducing subtle bugs).

redknightlois avatar Jul 14 '15 15:07 redknightlois

In C++, this is called "placement new".

In C#, the main solutions to this are object pools, IDisposable, and IEnumerable. Object pools prevent the allocation of new memory so also avoid the fragmentation. IDisposable allows explict control over the release of non-managed resources or pinned memory. Finally, IEnumerable allows you to allocate/deallocate on demand instead of all at once.

As an alternative, you can create a native library to handle resources from a non-managed heap rather than pinning. The library would then have a C# facade over it that wrapps P/Invoke calls.

OtherCrashOverride avatar Jul 15 '15 08:07 OtherCrashOverride

Yes, I'm aware of all of those. And none of those really work for those cases.

Consider a highly simplify case of needing to read record from a CSV file and do some work on them. Each line we read becomes garbage very quickly. Now, assume that the file is large, processing time is long, and while some data can be discarded immediately (the line we just read), some data is kept for the duration of the entire file run.

Now, assume that you have to process many such files concurrently.

There is no way for us to control the memory usage. I would like to say "this process cannot take more than 1GB", and I would like to actually get an error if we exceed that, because this gives be more predictable behavior.

*Hibernating Rhinos Ltd *

Oren Eini* l CEO l *Mobile: + 972-52-548-6969

Office: +972-4-622-7811 *l *Fax: +972-153-4-622-7811

On Wed, Jul 15, 2015 at 11:48 AM, OtherCrashOverride < [email protected]> wrote:

In C++, this is called "placement new".

In C#, the main solutions to this are object pools, IDisposable, and IEnumerable. Object pools prevent the allocation of new memory so also avoid the fragmentation. IDisposable allows explict control over the release of non-managed resources or pinned memory. Finally, IEnumerable allows you to allocate/deallocate on demand instead of all at once.

As an alternative, you can create a native library to handle resources from a non-managed heap rather than pinning. The library would then have a C# facade over it that wrapps P/Invoke calls.

— Reply to this email directly or view it on GitHub https://github.com/dotnet/coreclr/issues/1235#issuecomment-121533267.

ayende avatar Jul 15 '15 09:07 ayende

And while I can do this in native code, the work I'm doing is primarily managed stuff. The only "resource" that I want to manage is memory itself.

*Hibernating Rhinos Ltd *

Oren Eini* l CEO l *Mobile: + 972-52-548-6969

Office: +972-4-622-7811 *l *Fax: +972-153-4-622-7811

On Wed, Jul 15, 2015 at 11:48 AM, OtherCrashOverride < [email protected]> wrote:

In C++, this is called "placement new".

In C#, the main solutions to this are object pools, IDisposable, and IEnumerable. Object pools prevent the allocation of new memory so also avoid the fragmentation. IDisposable allows explict control over the release of non-managed resources or pinned memory. Finally, IEnumerable allows you to allocate/deallocate on demand instead of all at once.

As an alternative, you can create a native library to handle resources from a non-managed heap rather than pinning. The library would then have a C# facade over it that wrapps P/Invoke calls.

— Reply to this email directly or view it on GitHub https://github.com/dotnet/coreclr/issues/1235#issuecomment-121533267.

ayende avatar Jul 15 '15 09:07 ayende

Sounds effectively like java nio's ByteBuffer http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html. We've also been looking into something like this for ASP.NET 5. The current plan is to allocate native memory and memcpy user bytes into it.

davidfowl avatar Jul 15 '15 10:07 davidfowl

How are you going to make that work with Stream ? That accept byte[], not byte*.

For specific things, we can use direct methods (ReadFile, WriteFile) that can accept it. But for many things, that isn't an option.

*Hibernating Rhinos Ltd *

Oren Eini* l CEO l *Mobile: + 972-52-548-6969

Office: +972-4-622-7811 *l *Fax: +972-153-4-622-7811

On Wed, Jul 15, 2015 at 1:03 PM, David Fowler [email protected] wrote:

Sounds effectively like java nio's ByteBuffer http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html. We've also been looking into something like this for ASP.NET 5. The current plan is to allocate native memory and memcpy user bytes into it.

— Reply to this email directly or view it on GitHub https://github.com/dotnet/coreclr/issues/1235#issuecomment-121563950.

ayende avatar Jul 15 '15 10:07 ayende

Stream.Write will be backed by native memory. So when the user passes the managed byte[], it'll be copied into the native buffer.

davidfowl avatar Jul 15 '15 10:07 davidfowl

@davidfowl How is that different from MemoryStream? Should we just expose the IntPtr (byte*) of the storage the class uses? Can it all be done with Marshal.AllocHGlobal in managed code?

https://msdn.microsoft.com/en-us/library/system.io.memorystream%28v=vs.110%29.aspx

OtherCrashOverride avatar Jul 15 '15 10:07 OtherCrashOverride

Now, assume that the file is large, processing time is long, and while some data can be discarded immediately (the line we just read), some data is kept for the duration of the entire file run.

You may also want to consider MemoryMappedFile: https://msdn.microsoft.com/en-us/library/system.io.memorymappedfiles.memorymappedfile_methods%28v=vs.110%29.aspx

OtherCrashOverride avatar Jul 15 '15 11:07 OtherCrashOverride

Imagine that I'm doing :

new GzipStream(new SslStream(new NetworkStream(socket))).Read(...)

What happens now? Also note that if you have a NativeMemoryStream or something like that, it would still need to allocate large byte arrays for the rest of the system.

We run into this frequently when using web sockets and long running requests.

*Hibernating Rhinos Ltd *

Oren Eini* l CEO l *Mobile: + 972-52-548-6969

Office: +972-4-622-7811 *l *Fax: +972-153-4-622-7811

On Wed, Jul 15, 2015 at 1:47 PM, David Fowler [email protected] wrote:

Stream.Write will be backed by native memory. So when the user passes the managed byte[], it'll be copied into the native buffer.

— Reply to this email directly or view it on GitHub https://github.com/dotnet/coreclr/issues/1235#issuecomment-121573852.

ayende avatar Jul 15 '15 12:07 ayende

@OtherCrashOverride

There is already UnamangedMemoryStream ( https://msdn.microsoft.com/en-us/library/system.io.unmanagedmemorystream(v=vs.110).aspx )

That doesn't help when your destination is an I/O stream.

*Hibernating Rhinos Ltd *

Oren Eini* l CEO l *Mobile: + 972-52-548-6969

Office: +972-4-622-7811 *l *Fax: +972-153-4-622-7811

On Wed, Jul 15, 2015 at 1:58 PM, OtherCrashOverride < [email protected]> wrote:

@davidfowl https://github.com/davidfowl How is that different from MemoryStream? Should we just expose the IntPtr (byte*) of the storage the class uses? Can it all be done with Marshal.AllocHGlobal in managed code?

https://msdn.microsoft.com/en-us/library/system.io.memorystream%28v=vs.110%29.aspx

— Reply to this email directly or view it on GitHub https://github.com/dotnet/coreclr/issues/1235#issuecomment-121579824.

ayende avatar Jul 15 '15 12:07 ayende

I intentionally gave a simple CSV file example, because it easy. The real example is getting data from users and indexing them.

But even with simple CSV file. I cannot allocate a string in the memory mapped file. So I need to read a bunch of bytes, then create a new string. I have no control over the size, where it is located, etc.

*Hibernating Rhinos Ltd *

Oren Eini* l CEO l *Mobile: + 972-52-548-6969

Office: +972-4-622-7811 *l *Fax: +972-153-4-622-7811

On Wed, Jul 15, 2015 at 2:06 PM, OtherCrashOverride < [email protected]> wrote:

Now, assume that the file is large, processing time is long, and while some data can be discarded immediately (the line we just read), some data is kept for the duration of the entire file run.

You may also want to consider MemoryMappedFile:

https://msdn.microsoft.com/en-us/library/system.io.memorymappedfiles.memorymappedfile_methods%28v=vs.110%29.aspx

— Reply to this email directly or view it on GitHub https://github.com/dotnet/coreclr/issues/1235#issuecomment-121583484.

ayende avatar Jul 15 '15 12:07 ayende

@OtherCrashOverride Having been on both sides of the fence, doing GPU computing and working inside a database engine with @ayende I can confirm first hand they are 2 very different beasts (what works in one wont work with the other).

In GPU land you can be very liberal about pinning memory. With a bus throughput in excess of 5Gb/s your pinning time will be measured in the microseconds. On database and/or web server land that is not true, we are speaking of at least 2 order of magnitude difference when you go to the extreme case as pointed with the network transfer. Mind you, even going to disk will be measured in high miliseconds land for big buffers (which I have seen in the wild ;) ).

This is an example of how the Gen0 looks like when such things happen. Since then we have been able to confirm what was an hypothesis at the time of writing. http://ayende.com/blog/170243/long-running-async-and-memory-fragmentation

This will become even worse with HTTP/2 where connections will be reused and facilities for long-lived connections are going to be common (not a hack like now). I couldnt find it for illustration purposes but I had seen code in Katana aimed to promote buffers to Gen2 repeateadly executing Gc.Collect() at startup to at least force that memory to go up in generations. The problem is that then you have a supply of fixed amount of memory, and if you consume it all, you are done. So you have to get memory in advance that you will either not use, or you wont have enough if work pattern changes.

redknightlois avatar Jul 15 '15 12:07 redknightlois

@davidfowl Constantly copying from the managed to the native copy to then do what the stream has to do will introduce extra memory bus pressure. Wouldnt that introduce a perf regression when you are dealing with big streams/source arrays?

redknightlois avatar Jul 15 '15 13:07 redknightlois

http://ayende.com/blog/170243/long-running-async-and-memory-fragmentation

That link and the comments were very helpful. From what has been stated so far the issue is that the framework is doing the pinning during the async socket operation, not the user. The solution to this may be to modify the socket API in someway or tune its internal operation to prevent it from keeping the memory pinned.

(Is the System.Net.Sockets API even available in CoreCLR at this point? https://github.com/dotnet/corefx-progress/blob/master/src-diff/README.md)

Wouldnt that introduce a perf regression when you are dealing with big streams/source arrays?

I was wondering the same thing; however, the basis for measurement is going to be whether doing multiple copies with short pin times is faster than doing no copies with long pin times overall.

OtherCrashOverride avatar Jul 15 '15 14:07 OtherCrashOverride

@OtherCrashOverride

I don't see a way for the framework to avoid pinning. Ideally, you are doing DMA by letting the hardware do the operations on specific memory. location.

Even if it isn't actually DMA, it behave very much in the same sense, that eventually you are down to some native function that takes a pointer, and you need that to remain fixed while the operation is running.

*Hibernating Rhinos Ltd *

Oren Eini* l CEO l *Mobile: + 972-52-548-6969

Office: +972-4-622-7811 *l *Fax: +972-153-4-622-7811

On Wed, Jul 15, 2015 at 5:30 PM, OtherCrashOverride < [email protected]> wrote:

http://ayende.com/blog/170243/long-running-async-and-memory-fragmentation

That link and the comments were very helpful. From what has been stated so far the issue is that the framework is doing the pinning during the async socket operation, not the user. The solution to this may be to modify the socket API in someway or tune its internal operation to prevent it from keeping the memory pinned.

(Is the System.Net.Sockets API even available in CoreCLR at this point? https://github.com/dotnet/corefx-progress/blob/master/src-diff/README.md)

Wouldnt that introduce a perf regression when you are dealing with big streams/source arrays?

I was wondering the same thing; however, the basis for measurement is going to be whether doing multiple copies with short pin times is faster than doing no copies with long pin times overall.

— Reply to this email directly or view it on GitHub https://github.com/dotnet/coreclr/issues/1235#issuecomment-121634209.

ayende avatar Jul 15 '15 14:07 ayende

I don't see a way for the framework to avoid pinning.

I have some theories that would require testing and benchmarking. Principally, introducing an intermediary native buffer owned by the socket and doing a memcpy to the destination buffer when it fills. No matter how much network I/O you have, there are natural breaks in the data (MTU) and memcpy will be faster than wirespeed in many cases. So there are lots of areas to explore to see what turns out to be performant and what is not. Of course, there actually needs to be a System.Net.Sockets before any experiments can be done.

OtherCrashOverride avatar Jul 15 '15 14:07 OtherCrashOverride