GitHub user cmettler added a comment to the discussion: Proposal: Pluggable 
allocator API

Thanks for writing this up. I tried PR #504 (head `399ab94`, packed as a local 
package) in a real host instead of only reading it, so most of what follows is 
measured rather than opinion.

**Context.** The host is a DuckDB extension that runs CoreCLR in process and 
exchanges Arrow with DuckDB over the C stream interface in both directions: 
DuckDB hands us batches (scan arguments, filter constants, `INSERT` input) and 
we hand DuckDB batches (query results). Our SQL Server reader builds every 
batch with array builders, which is where an allocator can be passed. Most 
other batches come from the Parquet/Delta library we use, EngineeredWood, which 
allocates its decoded buffers itself, so an allocator we choose does not reach 
them. Where I compare against Arrow `main` without the PR, that is `2fc782e`.

## Default path: neutral

With no allocator passed, our tests give identical results on the PR and on 
23.0.0, with the same assertion count per suite: 101 self-contained suites 
(mostly Delta/Parquet, no external services) and 92 that run against SQL 
Server, about 150k assertions in total. That needed one change on our side, and 
it was for #483 rather than #504 (see below); `main` without the PR failed the 
same way.

We also ran the self-contained suites on both versions, and the SQL Server 
suites on 23.0.0, with a background thread that forced a blocking compacting 
gen2 plus `WaitForPendingFinalizers` every 5 ms, and found no #397-class 
failure. Take that as weak evidence: it ran with default tiered compilation, 
and we never reproduced the known #397 crash under the same harness as a 
positive control.

## Opt-in: what it buys

Functionally, the SQL Server suites pass with identical counts with each of 
`CallerOwnedNativeAllocator`, `ManagedMemoryAllocator` and 
`PooledManagedAllocator` with `PoisonDisposedBuffers`, for the batches our 
reader builds.

For the numbers, the test was a full scan of 1M rows and 7 types, with the row 
count of each batch known up front, so the builders could be created with that 
capacity.

| | default | `CallerOwnedNativeAllocator` | `PooledManagedAllocator` |
|---|---|---|---|
| managed allocation per scan | 633 MB | 451 MB (−29%) | not measured |
| wall time (median of 7) | 3.59 s | 3.54 s | 3.54 s |

We passed the allocator explicitly to every column builder: all seven types, 
including string, decimal and boolean, which we sized with `Reserve` because 
they have no capacity constructor yet. Managed allocation is 
`GC.GetTotalAllocatedBytes` over the whole scan, including the database client, 
so native memory is not in this number. The saving is the builders' working 
memory, which on the default path grows in managed arrays and is copied to 
native memory by `Build()`.

The wall-time difference is noise: on our path the database client and 
per-value boxing dominate. Our reader also appends one value at a time through 
`Append`, not through `GetSpan`/`Advance`, so these timings say nothing about 
what writing through spans would gain.

I also ran 8 concurrent scans in one process (8M rows):
- **Small heap:** gen0/gen1/gen2 went from 580/270/144 to 363/3/1, and total GC 
pause from about 390 ms to about 170 ms.
- **With a 2 GB live ballast:** the induced gen2s were gone on the default path 
too (671/185/8 against 545/185/8, where the 8 gen2s are the ballast's). That 
fits #261 as far as I read the runtime: the `AddMemoryPressure` budget grows 
with the managed heap, so the induced gen2s come exactly when the heap is small 
and a gen2 is cheap.

Wall time did not move in either case. So for us `CallerOwned` is about hygiene 
(no finalizer, a deterministic free on `release`, less churn) rather than 
throughput. That probably matters most under a hard memory limit, such as a 
container or notebook, which I have not measured.

## Q1 and Q3: disposal is load-bearing with `CallerOwned`

One finding argues for documenting this strongly. With 
`CallerOwnedNativeAllocator`, `Build()` does not take over every piece of a 
builder's working memory. Our case was the validity bitmap of a column without 
nulls. The binary/string, fixed-size binary (including decimal) and boolean 
builders still create their validity bitmap in the constructor, and `Build()` 
hands it over only when `NullCount > 0`; otherwise it stays with the builder. A 
builder that is built but never disposed then leaks that bitmap for the life of 
the process. On the 1M-row scan we saw about 1,500 live allocations left behind 
per scan, growing without bound, until we disposed builders after `Build`. 
`PrimitiveArrayBuilder` already creates its bitmap lazily, on the first null, 
so I assume these builders simply have not been converted yet; they are the 
ones on your follow-up list for capacity constructors.

A second leak came from our own code, not the PR. We created builders before we 
knew a result set was finished and dropped them on the empty last call. 
Builders reserve capacity when created, so each scan leaked one set of buffers.

Two suggestions:
1. When those builders get their capacity constructors, make their validity 
bitmap lazy as well, as in `PrimitiveArrayBuilder`. Alternatively `Build()` 
could release working memory it does not hand over. Either would make "build, 
then forget the builder" safe for the common case.
2. Make the allocator's live-allocation count public. 
`CallerOwnedNativeAllocator.LiveAllocations` is internal today; we read it 
through reflection, and it was the only way to see that we were leaking at all. 
Under `Finalized` such bugs are invisible and only delay frees; under 
`CallerOwned` they become permanent. A host needs a supported way to assert 
"nothing live" at a quiescent point. To find where the remaining leaks came 
from we also recorded the allocation site of each live buffer, as a wrapper 
around the allocator.

On Q1 itself: keeping `IArrowArrayBuilder` free of `IDisposable` has a cost we 
ran into. We have code that holds its column builders as 
`IArrowArrayBuilder<IArrowArray>[]`, a builder per column created from a 
schema. Through the interface it cannot dispose them, so it needs `(b as 
IDisposable)?.Dispose()`, which happens to be a no-op on 23.0.0 and works on 
the PR. That pattern is easy to miss, and with `CallerOwned` missing it is a 
leak. If the interface stays as it is for compatibility, the docs for 
`CallerOwned` should show that cast; adding `IDisposable` to the interface in 
the next major release would remove the trap. We have not looked at CA2000.

On Q3 we have no data either way: we build each builder once per batch, so the 
throw-after-hand-over rule never triggered.

## Q2: the default

My answer to Q2 is to keep the default as it is. I would not make `CallerOwned` 
the library's default: every forgotten `Dispose` turns from "freed late" into 
"never freed." `ManagedMemoryAllocator` as the default would be the safe 
direction for #397, but I can't add evidence for that change from our side: we 
found no #397 failure, and on our path the memory-pressure cost only showed 
with a small heap, where gen2s are cheap.

For a host like ours, though, `CallerOwned` is what we would choose. Nearly all 
our batches end up in native code, which releases them deterministically 
through the C interface, so a finalizer and GC pressure buy us nothing. That 
release frees the batch only if its own reference is disposed too: by the 
stream exporter since #483, or by the producer after exporting (see below). 
Under a memory limit (containers, notebooks) the prompt free matters more than 
throughput, and we would rather have a leak we can count than a span freed 
under us.

## Q4: temporary and result allocators

Yes, I think the pairing is worth exposing, though which allocator fits each 
role depends less on the Arrow type than on whether the size is known up front. 
With a known size one allocator is best: allocate once and hand the memory 
over. That is our case for the fixed-width columns. With an unknown size the 
working memory grows several times, and a pool for the working memory plus one 
copy at `Build()` may beat repeated native resizes. For us that is the value 
buffer of string columns: `Reserve(capacity)` only sizes the offsets, so with 
`CallerOwned` the value bytes grow by repeated allocate, copy and free, since 
it does not override `Resize`. We have not measured whether that matters.

So I would split the decision the way your question suggests: the code knows 
which buffers are temporary (a builder's growth, an IPC reader's scratch 
buffers), and the host knows which allocator suits each role (memory limit, 
interop, GC pressure). An `ArrowContext` with both allocators expresses that. A 
reasonable default could be to build directly in the result allocator when the 
capacity is known, and in the temporary one otherwise.

## C data interface: safe with every allocator

We checked whether `release` arriving late, and on another thread, from the C 
consumer is safe for each allocator. We exported a batch, disposed our side, 
and let the allocator serve the next request. The consumer still read the 
original values with every allocator, including the pooled one, because the 
exporter `Retain()`s the reference-counted handle and the pool only gets the 
array back after `release`.

## Heads-up: #483 changes ownership on `main`

This is not part of #504, but it is in the same area. Since #483 the C stream 
exporter disposes every batch a stream returns when the consumer calls 
`release`. That broke two of our streams that returned batches we did not own 
(we re-exported cached batches), with an `ObjectDisposedException` in one case 
and a segfault in the other. The fix was to return views that `Retain()` each 
buffer.

It is a correct change and it fixes a real leak for us: imported batches passed 
straight back to the consumer are now freed instead of waiting for a finalizer. 
But it is a silent behaviour change for any stream that hands out shared 
batches, and it is worth a line in the release notes.

#483 also matters for `CallerOwned`. The export retains each buffer, and 
`release` drops only that retained reference; the batch's own reference is 
released only when someone disposes the batch. Before #483 the stream exporter 
never did, so with `CallerOwned` (no finalizer) every exported batch would leak 
for the life of the process. With #483 the stream exporter disposes the batch 
on `release`, which makes the two changes belong together. We measured it with 
the PR head built twice, once as is and once with only the `transferOwnership: 
true` in `CArrowArrayStreamExporter.GetNext` set back to `false`. Both runs 
used `CallerOwned` and one SQL Server test suite (891 assertions, 9,126 
allocations):

| | live allocations at the end | maximum |
|---|---|---|
| with #483 | 11 (the last scan's columns, still in flight) | 62 |
| #483 reverted | 1,514, growing with every scan | 1,514 |
| #483 reverted, producer disposes each batch after export | 11 | 62 |

The public single-batch `ExportRecordBatch` deliberately leaves the batch to 
the caller, as #483 says, and that is right: callers can dispose right after 
the call, and code that keeps using a batch after exporting it would break 
otherwise. With `CallerOwned`, though, its docs should say so explicitly, 
because a forgotten `Dispose` there is a permanent leak rather than a late free.

## Smaller points

- `PoisonDisposedBuffers` found no use-after-dispose on our reader path, but 
the pooled allocator only covered the batches we build ourselves, which is a 
small part of what our code reads.
- Mixing allocators within one batch works, because ownership is per buffer. We 
have batches that combine library-decoded columns with a column we built 
ourselves; they export and release cleanly in our tests.


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

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

Reply via email to