You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@arrow.apache.org by "CurtHagenlocher (via GitHub)" <gi...@apache.org> on 2026/07/27 23:55:22 UTC
[I] ArrowBuffer spans do not keep native memory alive: NativeMemoryManager's finalizer can free a buffer while a Span over it is in use [arrow-dotnet]
CurtHagenlocher opened a new issue, #397:
URL: https://github.com/apache/arrow-dotnet/issues/397
### Summary
A `ReadOnlySpan<byte>` obtained from `ArrowBuffer.Span` does not keep the buffer's memory alive. Because `MemoryAllocator.Default` allocates native memory owned by a `NativeMemoryManager` **whose finalizer frees it**, an array that becomes unreachable while spans over its buffers are still in use can have those buffers freed underneath them.
The result is a use-after-free in ordinary-looking consumer code. The failure is usually silent — freed `HGlobal` pages typically stay mapped, so the span keeps returning plausible data — and only occasionally surfaces as an `AccessViolationException`.
### Reproduction
`repro.csproj`:
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Apache.Arrow" Version="23.0.0" />
</ItemGroup>
</Project>
```
`Program.cs`:
```csharp
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Apache.Arrow;
static StringArray BuildArray(int rows)
{
var b = new StringArray.Builder();
for (int i = 0; i < rows; i++) b.Append($"row-{i}");
return b.Build();
}
// WeakReference to the MemoryManager that owns the array's value buffer.
static WeakReference OwnerOf(StringArray a)
{
MemoryMarshal.TryGetMemoryManager<byte, MemoryManager<byte>>(
a.Data.Buffers[2].Memory, out var manager);
Console.WriteLine($"value buffer is owned by: {manager?.GetType().Name ?? "(managed array)"}");
return new WeakReference(manager);
}
// Stands in for the allocating work a consumer does while holding the spans.
static void DoWorkWhileHoldingSpans()
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool WithoutKeepAlive()
{
var array = BuildArray(100_000);
var owner = OwnerOf(array);
ReadOnlySpan<int> offsets = MemoryMarshal.Cast<byte, int>(array.Data.Buffers[1].Span);
ReadOnlySpan<byte> values = array.Data.Buffers[2].Span;
DoWorkWhileHoldingSpans();
long total = 0;
for (int i = 0; i < 100_000; i++) total += offsets[i + 1] - offsets[i];
_ = values.Length;
return owner.IsAlive;
}
[MethodImpl(MethodImplOptions.NoInlining)]
static bool WithKeepAlive()
{
var array = BuildArray(100_000);
var owner = OwnerOf(array);
ReadOnlySpan<int> offsets = MemoryMarshal.Cast<byte, int>(array.Data.Buffers[1].Span);
ReadOnlySpan<byte> values = array.Data.Buffers[2].Span;
DoWorkWhileHoldingSpans();
long total = 0;
for (int i = 0; i < 100_000; i++) total += offsets[i + 1] - offsets[i];
_ = values.Length;
bool alive = owner.IsAlive;
GC.KeepAlive(array);
return alive;
}
Console.WriteLine($"buffer owner still alive, without GC.KeepAlive: {WithoutKeepAlive()}");
Console.WriteLine($"buffer owner still alive, with GC.KeepAlive: {WithKeepAlive()}");
```
Run with tiered compilation disabled, since tier-0 keeps locals alive to the end of the method and masks the problem:
```
DOTNET_TieredCompilation=0 dotnet run -c Release
```
Output:
```
value buffer is owned by: NativeMemoryManager
buffer owner still alive, without GC.KeepAlive: False
value buffer is owned by: NativeMemoryManager
buffer owner still alive, with GC.KeepAlive: True
```
`False` means the `NativeMemoryManager` was collected and finalized — i.e. `Marshal.FreeHGlobal` ran on the buffer — while the two spans above were still being read.
### Why it happens
Three behaviours combine:
1. `MemoryAllocator.Default` is a `NativeMemoryAllocator`, so any buffer produced by an Arrow builder lives in `Marshal.AllocHGlobal` memory.
2. `NativeMemoryManager` frees that memory from a **finalizer**.
3. `ArrowBuffer.Span` (and the `Values` properties on the typed arrays) hand out a raw span, which is a bare pointer into that native memory and keeps nothing alive.
A span over a *managed* `byte[]` is safe here, because its interior pointer is reported to the GC and roots the array. A span over native memory has no such protection, so the only thing keeping the allocation alive is a reference to the owning object — and in the code shape above there isn't one past the point where the spans are taken.
Notably, `NativeMemoryManager` already suppresses the analyzer that exists specifically to flag this:
```csharp
#pragma warning disable CA2015 // TODO: is this correct?
~NativeMemoryManager()
{
Dispose(false);
}
#pragma warning restore CA2015
```
[CA2015](https://learn.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca2015) is *"Do not define finalizers for types derived from `MemoryManager<T>`"*, and its rationale is exactly this failure mode.
### Why it is easy to miss
The freed pages usually remain mapped, so the span keeps returning correct-looking bytes and nothing is observed. It faults only when the page is genuinely returned to the OS.
We hit it as an `AccessViolationException` that killed a test host mid-run, in a dictionary encoder that took two spans off a caller-supplied array and then looped over a million rows while allocating. It appeared on a commit that changed only Markdown, having passed on the three commits before it — the code involved had been in place and "working" for some time.
### Note on `main`
The reference-counting layer added in #297 (`SharedMemoryHandle`, `ArrowBuffer.Retain()`, `ArrowBuffer : IDisposable`) makes sharing explicit, but does not close this: `SharedMemoryHandle` also defines a finalizer, and `ArrowBuffer.Span` still returns a span that roots nothing. So the hazard appears to remain on `main`.
### Possible directions
Any one of these would remove the failure mode; they are not mutually exclusive:
- **Drop the finalizers** on `NativeMemoryManager` (and `SharedMemoryHandle`), so that a missing release becomes a *leak* rather than a free-under-live-span. This is what CA2015 prescribes, and it converts a silent-corruption bug class into a diagnosable one. It is a behaviour change for callers who never dispose, but the `IDisposable`/ref-counting work already moves in that direction.
- **Make the lifetime-safe accessor the ergonomic one** — e.g. favour `Memory<byte>` (which does root the manager) over `Span`, or provide a scope type that holds the owner for the duration of a read.
- **Consider a managed-array allocator as the default**, reserving native allocation for interop and explicitly-aligned paths. This has real costs for alignment and the C Data Interface, so it is the least appealing of the three, but it would make the question moot for consumers that never touch native interop.
### Workaround for consumers
Keep the array reachable until after the last span read:
```csharp
var data = array.Data;
ReadOnlySpan<byte> values = data.Buffers[2].Span;
// ... work ...
GC.KeepAlive(array);
```
It is worth noting that this is an unwritten contract every consumer has to rediscover independently, and that code violating it looks correct and passes tests.
### Environment
- Apache.Arrow 23.0.0 (NuGet)
- .NET 8 target, .NET 10 SDK
- macOS 15 / arm64
- Also expected on `main` by inspection (see the note above)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@arrow.apache.org.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [I] ArrowBuffer spans do not keep native memory alive: NativeMemoryManager's finalizer can free a buffer while a Span over it is in use [arrow-dotnet]
Posted by "rustyconover (via GitHub)" <gi...@apache.org>.
rustyconover commented on issue #397:
URL: https://github.com/apache/arrow-dotnet/issues/397#issuecomment-5738548624
`ArrowStreamWriter` hits this hazard internally. A caller that writes a batch it built only to write gets a `NullReferenceException`, or silently wrong bytes, with no span in its own code. The writer case also shows that preferring `Memory<byte>` over `Span` isn't enough on `main`.
### Where it happens
In `WriteRecordBatchInternal`, the last use of `recordBatch` is `recordBatch.Length`, when the header is built. The bodies are copied later, by `WriteBufferData(recordBatchBuilder.Buffers)`. In optimized code, if the caller holds no other reference to the batch, it is unreachable during that copy.
`recordBatchBuilder.Buffers` holds `ReadOnlyMemory<byte>` views. They root the `NativeMemoryManager`, but not the `SharedMemoryHandle` that owns it. A collection in that window finalizes the handles, `SharedMemoryHandle.Release()` disposes the manager, and `WriteBufferData` copies from freed memory. Keeping `Memory<byte>` alive does not help, because the finalizer that frees the memory belongs to the handle, not to the manager.
### Repro (Apache.Arrow 23.0.0 from NuGet, .NET 10, linux-arm64)
```csharp
// A destination whose writes allocate, e.g. a network or compression stream.
sealed class CollectingStream : MemoryStream
{
static void Collect() { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); }
public override void Write(byte[] b, int o, int c) { Collect(); base.Write(b, o, c); }
public override void Write(ReadOnlySpan<byte> b) { Collect(); base.Write(b); }
}
[MethodImpl(MethodImplOptions.NoInlining)]
static RecordBatch Build() // Int64 + String columns, 1000 rows, from the builders
{ ... }
[MethodImpl(MethodImplOptions.NoInlining)]
static byte[] WriteTemporary()
{
using var stream = new CollectingStream();
using (var writer = new ArrowStreamWriter(stream, schema, leaveOpen: true))
{
writer.WriteRecordBatch(Build()); // referenced by nothing but the call
writer.WriteEnd();
}
return stream.ToArray();
}
```
Twenty iterations with `DOTNET_TieredCompilation=0`, each result read back and checked value by value:
```
temporary batch (no keep-alive): NullReferenceException: 20
batch kept alive by the caller: ok: 20
```
```
System.NullReferenceException: Object reference not set to an instance of an object.
at System.SpanHelpers.Memmove(Byte& dest, Byte& src, UIntPtr len)
at System.IO.Stream.Write(ReadOnlySpan`1 buffer)
at CollectingStream.Write(ReadOnlySpan`1 buffer)
at Apache.Arrow.Ipc.ArrowStreamWriter.WriteBufferData(IReadOnlyList`1 buffers)
at Apache.Arrow.Ipc.ArrowStreamWriter.WriteRecordBatchInternal(RecordBatch recordBatch)
```
With default tiering it passes, because tier-0 keeps locals alive to the end of the method.
We found this in a multithreaded HTTP server. Each response writes a few hundred single-row batches built only to be written, and about 0.7% of our integration test files failed intermittently. Code shaped like `writer.WriteRecordBatch(BuildRow(...))` is common and looks correct.
### What fixed it for us
`GC.KeepAlive(recordBatch)` at the end of `WriteRecordBatchInternal` and `WriteRecordBatchInternalAsync`, after the bodies are copied. We added the same guard for `dictionary` in `WriteDictionary` / `WriteDictionaryAsync`. The dictionary memo already holds it, so that one is defensive.
This is the second case in the repro, moved into the writer. It is carried as a patch in our fork. With the patched writer, repeated runs of the server scenario went from 23 crashes in 144 to 0 in 144. I'm happy to open a PR with that change and a regression test that forces a collection from the destination stream, if that's useful while the broader ownership question in this issue is worked out.
Main is unchanged as of 75718c9: no `GC.KeepAlive` in `ArrowStreamWriter.cs`, and `SharedMemoryHandle` still has its finalizer.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org