From 0d49ae010d72021138626f209a9e9150c5842d90 Mon Sep 17 00:00:00 2001 From: Curt Hagenlocher Date: Sat, 5 Dec 2026 06:24:47 -0800 Subject: [PATCH] fix: Set an exported array's release callback only once the export has succeeded (#547) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### What's changed? `CArrowArrayExporter` set each struct's `release` callback and private data as soon as it started converting it. If the export then failed, for example because one of the array's buffers had already been disposed, the exporter freed the memory it had allocated but left the caller's struct with `release` set and pointing at that memory. Releasing the struct afterwards, as `CArrowArray.Free` does, then read freed memory. Each failure also kept a GC handle to the exporter's allocations. - The array or record batch is converted in full first. Only then are the release callbacks and private data set, children first. - If the export fails, the caller's struct is left zeroed, which marks it as released, and the exception is rethrown. This covers `ExportArray`, `ExportRecordBatch`, and the stream and device exporters that use them. The schema exporter already sets `release` last, so it is unchanged. ### Testing New tests in `CDataInterfaceDataTests` export a struct array with a disposed child and a record batch with a disposed column (with and without ownership transfer), check that the struct is left released, and free it. Without the change they fail, and on net472 freeing the struct crashed the test host. All of `Apache.Arrow.Tests`, including the pyarrow C Data tests, passes on net8.0, net462 and net472. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_012dFdcrBz22tRjiyNwBd7VB --------- Co-authored-by: Claude Opus 5.5 The record batch test calls ExportRecordBatch(batch, cArray), as there is no transferOwnership overload here. (cherry picked from commit 38ce7ee84d4e7f1746d6dd0a9a3954d340df9ccc) Claude-Session: https://claude.ai/code/session_012dFdcrBz22tRjiyNwBd7VB --- src/Apache.Arrow/C/CArrowArrayExporter.cs | 83 ++++++++++++++++++- .../CDataInterfaceDataTests.cs | 65 +++++++++++++++ 2 files changed, 144 insertions(+), 4 deletions(-) diff --git a/src/Apache.Arrow/C/CArrowArrayExporter.cs b/src/Apache.Arrow/C/CArrowArrayExporter.cs index 32daad31..8468bbd3 100644 --- a/src/Apache.Arrow/C/CArrowArrayExporter.cs +++ b/src/Apache.Arrow/C/CArrowArrayExporter.cs @@ -68,8 +68,15 @@ public static unsafe void ExportArray(IArrowArray array, CArrowArray* cArray) try { ConvertArray(allocationOwner, array.Data, cArray); + SetReleaseOrUndo(allocationOwner, cArray); allocationOwner = null; } + catch + { + // The struct may point to memory that is freed below: leave it released. + *cArray = default; + throw; + } finally { allocationOwner?.Dispose(); @@ -109,8 +116,15 @@ public static unsafe void ExportRecordBatch(RecordBatch batch, CArrowArray* cArr try { ConvertRecordBatch(allocationOwner, batch, cArray); + SetReleaseOrUndo(allocationOwner, cArray); allocationOwner = null; } + catch + { + // The struct may point to memory that is freed below: leave it released. + *cArray = default; + throw; + } finally { allocationOwner?.Dispose(); @@ -122,8 +136,9 @@ private unsafe static void ConvertArray(ExportedAllocationOwner sharedOwner, Arr cArray->length = array.Length; cArray->offset = array.Offset; cArray->null_count = array.NullCount; // The C Data interface allows the null count to be -1 - cArray->release = ReleaseArrayPtr; - cArray->private_data = MakePrivateData(sharedOwner); + // Set by SetRelease once the whole array has been converted + cArray->release = default; + cArray->private_data = null; cArray->n_buffers = array.Buffers?.Length ?? 0; cArray->buffers = null; @@ -186,8 +201,9 @@ private unsafe static void ConvertRecordBatch(ExportedAllocationOwner sharedOwne cArray->length = batch.Length; cArray->offset = 0; cArray->null_count = 0; - cArray->release = ReleaseArrayPtr; - cArray->private_data = MakePrivateData(sharedOwner); + // Set by SetRelease once the whole batch has been converted + cArray->release = default; + cArray->private_data = null; cArray->n_buffers = 1; cArray->buffers = (byte**)sharedOwner.Allocate(IntPtr.Size); @@ -231,6 +247,65 @@ private unsafe static void ReleaseArray(CArrowArray* cArray) cArray->release = default; } + /// + /// Sets the release callbacks with , and if that fails partway, + /// frees the handles it made before the caller disposes the owner, so they don't keep it + /// alive. + /// + private unsafe static void SetReleaseOrUndo(ExportedAllocationOwner sharedOwner, CArrowArray* cArray) + { + try + { + SetRelease(sharedOwner, cArray); + } + catch + { + UndoSetRelease(cArray); + throw; + } + } + + /// + /// Frees the handles that made and clears the release callbacks. + /// The owner's references aren't released one by one: the caller disposes it. + /// + private unsafe static void UndoSetRelease(CArrowArray* cArray) + { + for (long i = 0; i < cArray->n_children; i++) + { + UndoSetRelease(cArray->children[i]); + } + if (cArray->dictionary != null) + { + UndoSetRelease(cArray->dictionary); + } + if (cArray->private_data != null) + { + GCHandle.FromIntPtr((IntPtr)cArray->private_data).Free(); + cArray->private_data = null; + } + cArray->release = default; + } + + /// + /// Sets the release callback of and everything under it, once + /// conversion has succeeded. Until then nothing refers to the owner, so a failed export + /// leaves nothing for a consumer to release. + /// + private unsafe static void SetRelease(ExportedAllocationOwner sharedOwner, CArrowArray* cArray) + { + for (long i = 0; i < cArray->n_children; i++) + { + SetRelease(sharedOwner, cArray->children[i]); + } + if (cArray->dictionary != null) + { + SetRelease(sharedOwner, cArray->dictionary); + } + cArray->private_data = MakePrivateData(sharedOwner); + cArray->release = ReleaseArrayPtr; + } + private unsafe static CArrowArray* MakeArray(ExportedAllocationOwner sharedOwner) { var array = (CArrowArray*)sharedOwner.Allocate(sizeof(CArrowArray)); diff --git a/test/Apache.Arrow.Tests/CDataInterfaceDataTests.cs b/test/Apache.Arrow.Tests/CDataInterfaceDataTests.cs index 2823df07..0838ca87 100644 --- a/test/Apache.Arrow.Tests/CDataInterfaceDataTests.cs +++ b/test/Apache.Arrow.Tests/CDataInterfaceDataTests.cs @@ -141,6 +141,71 @@ public unsafe void ExportArrayPreservesSource() array.Dispose(); } + // A struct whose first child exports and whose second has been disposed, so export fails + // after part of the array has been converted. + private static StructArray StructWithADisposedSecondChild() + { + Int32Array first = new Int32Array.Builder().AppendRange(new[] { 1, 2, 3 }).Build(); + Int32Array second = new Int32Array.Builder().AppendRange(new[] { 4, 5, 6 }).Build(); + var type = new StructType(new[] + { + new Field("first", Int32Type.Default, true), + new Field("second", Int32Type.Default, true), + }); + var array = new StructArray(type, 3, new IArrowArray[] { first, second }, ArrowBuffer.Empty, 0); + second.Dispose(); + return array; + } + + [Fact] + public unsafe void FailedArrayExportLeavesTheArrayReleased() + { + using StructArray array = StructWithADisposedSecondChild(); + CArrowArray* cArray = CArrowArray.Create(); + try + { + Assert.Throws(() => CArrowArrayExporter.ExportArray(array, cArray)); + + // Nothing is left for a consumer to release, or to read + Assert.True(cArray->release == default); + Assert.True(cArray->children == null); + Assert.True(cArray->private_data == null); + } + finally + { + CArrowArray.Free(cArray); + } + } + + [Fact] + public unsafe void FailedRecordBatchExportLeavesTheArrayReleased() + { + Int32Array first = new Int32Array.Builder().AppendRange(new[] { 1, 2, 3 }).Build(); + Int32Array second = new Int32Array.Builder().AppendRange(new[] { 4, 5, 6 }).Build(); + var schema = new Schema.Builder() + .Field(f => f.Name("first").DataType(Int32Type.Default)) + .Field(f => f.Name("second").DataType(Int32Type.Default)) + .Build(); + var batch = new RecordBatch(schema, new IArrowArray[] { first, second }, 3); + second.Dispose(); + + CArrowArray* cArray = CArrowArray.Create(); + try + { + Assert.Throws( + () => CArrowArrayExporter.ExportRecordBatch(batch, cArray)); + + Assert.True(cArray->release == default); + Assert.True(cArray->children == null); + Assert.True(cArray->private_data == null); + } + finally + { + CArrowArray.Free(cArray); + batch.Dispose(); + } + } + [Fact] public unsafe void ExportRecordBatch_LargerThan2GB_Succeeds() {