GitHub user CurtHagenlocher created a discussion: Proposal: Pluggable allocator 
API

# Opt-in pluggable allocators: proposed public API changes

This summarizes the public API changes in the draft PR #504, to get feedback on 
the API before the work is split into smaller PRs. Implementation details are 
left out.

**The change is purely additive.** I compared the public and protected API of 
`Apache.Arrow`, `Apache.Arrow.Flight`, `Apache.Arrow.Flight.Sql` and 
`Apache.Arrow.Operations` with `main` (2fc782e). Nothing is removed or changed, 
and 127 members are added. Existing code compiles and behaves as before. 
Passing no allocator, or `null`, gives today's behaviour, and the new behaviour 
applies only when you pass one of the new allocators.

## Goals

- **Choose the allocator:** let applications decide where Arrow memory comes 
from, and what happens to buffers that are never disposed. Today every buffer 
is native memory that a finalizer frees. So a span over a buffer can be 
invalidated while still in use (#397), and every allocation adds GC memory 
pressure (#261).
- **One allocation for a builder of known size:** let a builder whose final 
size is known allocate once, then hand that memory to the built array without 
copying.
- **No change for existing applications:** they keep today's behaviour unless 
they opt in.

## Allocators (`Apache.Arrow.Memory`)

### `AllocationLifetime` (new enum)

This enum states what happens to a buffer that is *never* disposed. Whatever 
the lifetime, a span must never be used after its buffer is disposed.

| Value | Undisposed buffer | Span over an undisposed buffer |
|---|---|---|
| `GarbageCollected` | Reclaimed by the GC | Keeps the memory alive |
| `CallerOwned` | Leaked for the life of the process | Always valid |
| `Finalized` | Reclaimed by a finalizer (today's behaviour) | Can be freed 
while the span is still in use (#397) |

### `MemoryAllocator` (new virtual members)

```csharp
public virtual AllocationLifetime Lifetime { get; }   // defaults to Finalized
public virtual IMemoryOwner<byte> Resize(IMemoryOwner<byte> owner, int 
newLength);
```

- **`Lifetime`:** defaults to `Finalized`, so existing third-party allocators 
describe themselves conservatively without any change. `NativeMemoryAllocator` 
overrides it to return `Finalized`.
- **`Resize`:** returns a buffer of the new length with the old contents, and 
releases the old one. Builders grow through it. The default implementation 
allocates, copies and releases; an allocator can override it to grow in place.

`MemoryAllocator.Default` is unchanged and can't be replaced. To use a 
different allocator, you pass it to whatever allocates.

### New allocators

| Type | Lifetime | Notes |
|---|---|---|
| `ManagedMemoryAllocator()` | `GarbageCollected` | Plain `byte[]` with no 
pooling, and disposing a buffer releases nothing. This is the safest choice: 
spans stay valid even after disposal. Aligned only to the pointer size. |
| `PooledManagedAllocator()` / `(PooledManagedAllocatorOptions)` | 
`GarbageCollected` | Reuses the arrays of disposed buffers, so using a span 
after disposal can see another buffer's data. Overrides `Resize`. |
| `PooledManagedAllocatorOptions` | n/a | `MaxPooledLength` (default 1 MiB), 
`MaxArraysPerSize` (default 16, about 32 MiB worst case), `MaxRetainedBytes`, 
and `PoisonDisposedBuffers`, which fills disposed buffers with `0xDE` to expose 
use-after-dispose bugs. |
| `CallerOwnedNativeAllocator(int alignment = 64)` | `CallerOwned` | Aligned 
native memory with no finalizer and no GC memory pressure. It is freed only by 
disposal, and disposal while pinned defers the free until the last pin is 
released. |

## Builders

### Allocator constructors

Every array builder gains a constructor that takes the allocator for its 
working memory. Constructors that already shipped are kept as they are, for 
binary compatibility.

- **Fixed-width builders** get a new capacity constructor of the form `(…, int 
capacity, MemoryAllocator allocator = null)`. This covers `Int8` through 
`UInt64`, `HalfFloat`, `Float`, `Double`, `Date32`, `Date64`, `Bool8`, the 
three interval types, `Duration(type, …)`, `Time32(type, …)`, `Time64(type, …)` 
and `Timestamp(type, …)`. The protected base constructor 
`PrimitiveArrayBuilder(int capacity, MemoryAllocator allocator = null)` is new 
too.
- **Other builders** get an allocator overload added next to their existing 
constructors. This covers `Boolean`, `String`, `LargeString`, `StringView`, 
`Guid` and `Variant` with `(MemoryAllocator)`. `Binary`, `LargeBinary` and 
`BinaryView` get `(IArrowType, MemoryAllocator)`, and the decimal builders get 
`(DecimalNNType, MemoryAllocator)`. `List`, `LargeList`, `ListView` and 
`LargeListView` get `(Field or IArrowType, MemoryAllocator)`, `FixedSizeList` 
gets `(Field or IArrowType, int listSize, MemoryAllocator)`, `Map` gets 
`(MapType, MemoryAllocator)` and `TimestampWithOffset` gets 
`(TimestampWithOffsetType, MemoryAllocator)`. Protected equivalents are added 
on the `BuilderBase` classes.
- **Buffer builders:** `ArrowBuffer.Builder<T>` and `ArrowBuffer.BitmapBuilder` 
get `(int capacity, MemoryAllocator allocator)`.
- **Nested builders** pass the allocator on to their child builders, and 
`RecordBatch.Builder`'s column helpers build in the batch's allocator.

The design rule is that builders take a `MemoryAllocator`, and operations such 
as readers, writers and Flight take an `ArrowContext`.

### What passing an allocator changes

- **`null` (or an existing constructor):** the builder grows in managed memory, 
and `Build` copies the result once into the target allocator, or into 
`MemoryAllocator.Default` if none is given. This is what builders do today.
- **An allocator:** the builder's working memory comes from that allocator, and 
capacity is rounded up to a multiple of 64 bytes. If `Build()` gets no 
allocator or the same one, the working memory usually *becomes* the built 
buffer, with no allocation or copy. Passing a different allocator to `Build` 
copies instead. The builder can still be used afterwards: the next write copies 
its contents back into memory of its own, and `Clear()` discards them without 
copying.

```csharp
var allocator = new CallerOwnedNativeAllocator();
using var builder = new Int32Array.Builder(1000, allocator);
Span<int> values = builder.GetSpan(1000);
// ... fill values ...
builder.Advance(1000);
using Int32Array array = builder.Build();   // one allocation, no copy
```

### Builders implement `IDisposable`

Each builder class now has `Dispose()` and `protected virtual Dispose(bool)`:

- `ArrowBuffer.Builder<T>` and `ArrowBuffer.BitmapBuilder`
- `PrimitiveArrayBuilder<…>`, in both its forms, and `DelegatingArrayBuilder<…>`
- the `BuilderBase` classes of `BinaryArray`, `LargeBinaryArray`, 
`BinaryViewArray` and `FixedSizeBinaryArray`
- `BooleanArray`, `ListArray`, `LargeListArray`, `ListViewArray`, 
`LargeListViewArray`, `FixedSizeListArray`, `MapArray`, 
`TimestampWithOffsetArray` and `VariantArray`

A parent builder disposes its child builders. Arrays that have already been 
built aren't affected.

- **When it's required:** only when the working memory comes from a 
`CallerOwned` allocator. Otherwise disposing just releases memory sooner.
- **`IArrowArrayBuilder` is unchanged:** adding `IDisposable` to the interface 
would break third-party implementers.

### Writing values directly: `GetSpan` / `Advance`

These are new on `ArrowBuffer.Builder<T>` and `PrimitiveArrayBuilder<T, TArray, 
TBuilder>`:

```csharp
public Span<T> GetSpan(int count);   // exactly `count` items past the end; 
contents unspecified
public TBuilder Advance(int count);  // appends the `count` items written 
(non-null)
```

The span is invalidated by any other call on the builder. This is similar to 
`IBufferWriter<T>`, but `Advance` returns the builder so calls can be chained.

## IPC and Flight: `ArrowContext`

- **Writers:** there are new `ArrowStreamWriter(ArrowContext, Stream, Schema, 
bool leaveOpen = false, IpcOptions options = null)` and `ArrowFileWriter` 
constructors in the same shape. The context supplies the allocator for 
temporary buffers. It also supplies the compression codec factory when 
`IpcOptions` doesn't specify one.
- **Flight client:** there is a new `FlightClient(CallInvoker, ArrowContext 
context = null)`. It is marked `[ActivatorUtilitiesConstructor]` so that 
clients created by `Grpc.Net.ClientFactory` get the `ArrowContext` registered 
for dependency injection. That needs a new package dependency on 
`Microsoft.Extensions.DependencyInjection.Abstractions` (6.0.0, matching the 
`Logging.Abstractions` version Flight already uses).
- **Flight server:** there is a new `protected FlightServer(ArrowContext 
context)` and `public ArrowContext Context { get; }`. A server hosted through 
ASP.NET Core dependency injection gets the context by taking it in its own 
constructor.
- **Flight SQL server:** there is a new `protected 
FlightSqlServer(ArrowContext? context, ILoggerFactory? factory)`.
- **Server stream writer:** there is a new 
`FlightServerRecordBatchStreamWriter(IServerStreamWriter<FlightData>, 
ArrowContext)`.
- **Already on `main` but not yet released:** the readers' context support came 
from #285, which isn't in v23.0.0. That covers `FlightClient(ChannelBase, 
ArrowContext)`, `FlightClient.Create(CallInvoker, ArrowContext)` and 
`FlightServerRecordBatchStreamReader(…, ArrowContext)`. Because they're 
unreleased, they can still be changed.

## Behaviour changes with the default allocator

These come without any opt-in. Most are bug fixes.

- **Dictionary bodies in the IPC readers are reference-counted.** A 
dictionary's memory is freed once the reader and every batch using it are 
disposed, rather than by a finalizer. Code that keeps using a dictionary after 
disposing both its batch and the reader would now read freed memory. That's the 
same rule that already applies to a batch's own columns.
- **Writers keep the record batch alive while writing it.** This fixes the 
writer variant of the #397 use-after-free.
- **Failures no longer leak.** Buffers are now released if an IPC read or write 
fails partway, or if a builder's `Build` fails partway.
- **`ArrowBuffer.Clone` and `Equals` keep the buffer alive while reading it.**
- **`NativeMemoryAllocator` with a non-default alignment** now removes exactly 
the memory pressure it added (#50).
- **Builders created for list elements of timestamp type** now keep the 
element's unit and time zone.
- **Flight schema decoding** uses the context's extension type registry instead 
of always using the default one.

## Behaviour on the opt-in path that deserves a look

- **After a hand-over, the builder's contents belong to the built buffer.** 
This applies with `GarbageCollected` and `CallerOwned` lifetimes. Once that 
buffer is disposed, using the builder throws `ObjectDisposedException` until 
`Clear()` is called. The alternative was for the builder to keep a reference to 
the buffer, but then the common `new Builder(allocator).Append(x).Build()` 
would leak whenever the builder isn't disposed. With `Finalized` lifetimes the 
builder still keeps its contents, as it does today.
- **Capacity is rounded up.** With an explicit allocator, `Capacity` can be 
larger than requested, because working memory is rounded up to 64 bytes.

## Questions for discussion

1. **Disposable builders:** is making builders `IDisposable` acceptable? Code 
analysis users with CA2000 enabled may start seeing warnings on builders they 
never disposed. Should `IArrowArrayBuilder` stay as it is?
2. **Defaults and #397:** should a future major release change the default 
allocator? For example, it could become `ManagedMemoryAllocator`, or arrays on 
the pinned object heap, which are rooted by the GC, aligned and never move. Or 
should the default stay native, with fixes like this one targeted at specific 
cases?
3. **Hand-over contract:** is throwing after the built buffer is disposed the 
right trade-off, compared with leaking or always copying?
4. **Separate temporary and long-term allocators:** internally a builder 
already pairs an allocator for working memory with one for the result. Should 
that pairing be public, for example on `ArrowContext`?
5. **Naming:** are `AllocationLifetime` and its values, 
`CallerOwnedNativeAllocator`, `PooledManagedAllocator` and 
`ManagedMemoryAllocator` the right names?
6. **`FlightClient.Create`:** this unreleased method is now redundant with the 
new constructor. Should it be removed before it ships?
7. **The new Flight dependency:** is the dependency on 
`Microsoft.Extensions.DependencyInjection.Abstractions` acceptable?
8. **Follow-ups not yet in the prototype:**
   - capacity constructors for the Boolean, binary, decimal, fixed-size binary 
and nested builders
   - `GetSpan` on the converting builders
   - a per-buffer lifetime for composite allocators
   - trimming the pool over time
   - batching memory pressure (#261)


GitHub link: https://github.com/apache/arrow-dotnet/discussions/509

----
This is an automatically sent email for [email protected].
To unsubscribe, please send an email to: [email protected]

Reply via email to