This is an automated email from the ASF dual-hosted git repository.

CurtHagenlocher pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-dotnet.git


The following commit(s) were added to refs/heads/main by this push:
     new ca17e8a  fix: Handle empty offsets buffers of zero-length arrays in C 
Data and ValueOffsets (#470)
ca17e8a is described below

commit ca17e8afe7512ee9b579ab83379d814761bb5f74
Author: Curt Hagenlocher <[email protected]>
AuthorDate: Sun Oct 18 10:29:24 2026 -0700

    fix: Handle empty offsets buffers of zero-length arrays in C Data and 
ValueOffsets (#470)
    
    ## What's Changed
    
    A zero-length `string`, `binary`, `large_string`, `large_binary`,
    `list`, `large_list` or `map` array may have an empty (0-byte) offsets
    buffer. Arrow C++ and nanoarrow write such arrays to IPC, and
    `ArrowStreamReader` reads them. #462 reported that concatenating them
    fails, and #465 fixes that. Auditing the rest of the library for the
    same input found three more failures, which this PR fixes.
    
    - **C Data export.** `CArrowArrayExporter` exported the empty offsets
    buffer as a null pointer. The spec allows a null pointer only where the
    buffer's size "would be 0". Arrow C++ computes the size of an offsets
    buffer as `offset + length + 1` offsets, so pyarrow rejects the export:
    `ArrowArrayStruct contains null data pointer for a buffer with non-zero
    computed size`. The exporter now exports `offset + 1` zeroed offsets in
    its place.
    - **C Data import.** `CArrowArrayImporter` read `offsets[length]`
    without checking for null. That hit a `Debug.Assert` in Debug builds and
    threw `NullReferenceException` in Release, including on a .NET → .NET
    round trip of an array read from IPC. For lists, it wrapped the null
    pointer in a non-empty buffer. The importer now accepts a null offsets
    buffer for a zero-length array, since older versions of this library
    produce one. For a non-empty array it throws
    `InvalidOperationException`.
    - **`ValueOffsets`.** The public accessor on `BinaryArray`,
    `LargeBinaryArray`, `ListArray` and `LargeListArray`, and so on string
    and map arrays, threw `ArgumentOutOfRangeException`. It now returns a
    single zero offset, keeping the `Length + 1` invariant. Internal callers
    already checked for zero length first.
    
    ### Tests
    The tests use zero-length arrays of each affected type with empty
    offsets buffers, including nested children (`list<string>`, `map<string,
    int32>`):
    - `ValueOffsetsOfZeroLengthArrayWithEmptyOffsets`
    - `ExportZeroLengthArrayWithEmptyOffsets`: the exported offsets are
    non-null and zero, and the array imports back.
    - `ImportZeroLengthArrayWithNullOffsets` and
    `ImportNonEmptyArrayWithNullOffsetsThrows`
    - A Python interop test, `ExportZeroLengthArrayWithEmptyOffsets`:
    pyarrow imports each exported array and validates it with
    `validate(full=True)`. It fails without this change with the C++ error
    quoted above.
    
    I also ran a wider check outside the test suite. pyarrow wrote
    zero-length arrays with minimal buffers for 26 types to IPC. .NET read
    them, round-tripped each through the C Data interface, and concatenated
    it with normal data, and pyarrow validated the results. With this change
    all types pass except `null`, which fails for an unrelated reason fixed
    in #469.
    
    🤖 Generated with [Claude Code](https://claude.com/claude-code)
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    
    ---------
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 src/Apache.Arrow/Arrays/BinaryArray.cs             |   7 +-
 src/Apache.Arrow/Arrays/LargeBinaryArray.cs        |   7 +-
 src/Apache.Arrow/Arrays/LargeListArray.cs          |   7 +-
 src/Apache.Arrow/Arrays/ListArray.cs               |   7 +-
 src/Apache.Arrow/C/CArrowArrayExporter.cs          |  18 ++++
 src/Apache.Arrow/C/CArrowArrayImporter.cs          |  31 +++++-
 test/Apache.Arrow.Tests/CDataInterfaceDataTests.cs | 111 +++++++++++++++++++++
 .../CDataInterfacePythonTests.cs                   |  26 +++++
 8 files changed, 206 insertions(+), 8 deletions(-)

diff --git a/src/Apache.Arrow/Arrays/BinaryArray.cs 
b/src/Apache.Arrow/Arrays/BinaryArray.cs
index 387c644..74c45f0 100644
--- a/src/Apache.Arrow/Arrays/BinaryArray.cs
+++ b/src/Apache.Arrow/Arrays/BinaryArray.cs
@@ -334,7 +334,12 @@ namespace Apache.Arrow
 
         public ArrowBuffer ValueBuffer => Data.Buffers[2];
 
-        public ReadOnlySpan<int> ValueOffsets => 
ValueOffsetsBuffer.Span.CastTo<int>().Slice(Offset, Length + 1);
+        // A zero-length array may have an empty offsets buffer (e.g. when 
read from IPC).
+        private static ReadOnlySpan<int> ZeroOffset => new int[] { 0 };
+
+        public ReadOnlySpan<int> ValueOffsets => Length == 0 && 
ValueOffsetsBuffer.IsEmpty
+            ? ZeroOffset
+            : ValueOffsetsBuffer.Span.CastTo<int>().Slice(Offset, Length + 1);
 
         public ReadOnlySpan<byte> Values => ValueBuffer.Span.CastTo<byte>();
 
diff --git a/src/Apache.Arrow/Arrays/LargeBinaryArray.cs 
b/src/Apache.Arrow/Arrays/LargeBinaryArray.cs
index 7532f4b..960f60b 100644
--- a/src/Apache.Arrow/Arrays/LargeBinaryArray.cs
+++ b/src/Apache.Arrow/Arrays/LargeBinaryArray.cs
@@ -222,7 +222,12 @@ public class LargeBinaryArray : Array, IBinaryArray, 
IReadOnlyList<byte[]>, ICol
 
     public ArrowBuffer ValueBuffer => Data.Buffers[2];
 
-    public ReadOnlySpan<long> ValueOffsets => 
ValueOffsetsBuffer.Span.CastTo<long>().Slice(Offset, Length + 1);
+    // A zero-length array may have an empty offsets buffer (e.g. when read 
from IPC).
+    private static ReadOnlySpan<long> ZeroOffset => new long[] { 0 };
+
+    public ReadOnlySpan<long> ValueOffsets => Length == 0 && 
ValueOffsetsBuffer.IsEmpty
+        ? ZeroOffset
+        : ValueOffsetsBuffer.Span.CastTo<long>().Slice(Offset, Length + 1);
 
     [MethodImpl(MethodImplOptions.AggressiveInlining)]
     public int GetValueLength(int index)
diff --git a/src/Apache.Arrow/Arrays/LargeListArray.cs 
b/src/Apache.Arrow/Arrays/LargeListArray.cs
index 2fed1b4..7220119 100644
--- a/src/Apache.Arrow/Arrays/LargeListArray.cs
+++ b/src/Apache.Arrow/Arrays/LargeListArray.cs
@@ -109,7 +109,12 @@ namespace Apache.Arrow
 
         public ArrowBuffer ValueOffsetsBuffer => Data.Buffers[1];
 
-        public ReadOnlySpan<long> ValueOffsets => 
ValueOffsetsBuffer.Span.CastTo<long>().Slice(Offset, Length + 1);
+        // A zero-length array may have an empty offsets buffer (e.g. when 
read from IPC).
+        private static ReadOnlySpan<long> ZeroOffset => new long[] { 0 };
+
+        public ReadOnlySpan<long> ValueOffsets => Length == 0 && 
ValueOffsetsBuffer.IsEmpty
+            ? ZeroOffset
+            : ValueOffsetsBuffer.Span.CastTo<long>().Slice(Offset, Length + 1);
 
         public LargeListArray(IArrowType dataType, int length,
             ArrowBuffer valueOffsetsBuffer, IArrowArray values,
diff --git a/src/Apache.Arrow/Arrays/ListArray.cs 
b/src/Apache.Arrow/Arrays/ListArray.cs
index c7b1458..0c3e242 100644
--- a/src/Apache.Arrow/Arrays/ListArray.cs
+++ b/src/Apache.Arrow/Arrays/ListArray.cs
@@ -117,7 +117,12 @@ namespace Apache.Arrow
 
         public ArrowBuffer ValueOffsetsBuffer => Data.Buffers[1];
 
-        public ReadOnlySpan<int> ValueOffsets => 
ValueOffsetsBuffer.Span.CastTo<int>().Slice(Offset, Length + 1);
+        // A zero-length array may have an empty offsets buffer (e.g. when 
read from IPC).
+        private static ReadOnlySpan<int> ZeroOffset => new int[] { 0 };
+
+        public ReadOnlySpan<int> ValueOffsets => Length == 0 && 
ValueOffsetsBuffer.IsEmpty
+            ? ZeroOffset
+            : ValueOffsetsBuffer.Span.CastTo<int>().Slice(Offset, Length + 1);
 
         public ListArray(IArrowType dataType, int length,
             ArrowBuffer valueOffsetsBuffer, IArrowArray values,
diff --git a/src/Apache.Arrow/C/CArrowArrayExporter.cs 
b/src/Apache.Arrow/C/CArrowArrayExporter.cs
index 32daad3..882533c 100644
--- a/src/Apache.Arrow/C/CArrowArrayExporter.cs
+++ b/src/Apache.Arrow/C/CArrowArrayExporter.cs
@@ -159,6 +159,17 @@ namespace Apache.Arrow.C
                 {
                     cArray->buffers[array.Buffers.Length] = (byte*)lengths;
                 }
+
+                // A zero-length array may have an empty offsets buffer (e.g. 
when read from IPC),
+                // but consumers expect offset + 1 offsets, so export zeros in 
its place.
+                int offsetWidth = GetOffsetWidth(storageTypeId);
+                if (offsetWidth > 0 && array.Length == 0 && 
array.Buffers[1].IsEmpty)
+                {
+                    int byteLength = checked((array.Offset + 1) * offsetWidth);
+                    IntPtr zeros = sharedOwner.Allocate(byteLength);
+                    new Span<byte>((void*)zeros, byteLength).Clear();
+                    cArray->buffers[1] = (byte*)zeros;
+                }
             }
 
             cArray->n_children = array.Children?.Length ?? 0;
@@ -258,5 +269,12 @@ namespace Apache.Arrow.C
             ((ExportedAllocationOwner)gch.Target).DecRef();
             gch.Free();
         }
+
+        private static int GetOffsetWidth(ArrowTypeId typeId) => typeId switch
+        {
+            ArrowTypeId.Binary or ArrowTypeId.String or ArrowTypeId.List or 
ArrowTypeId.Map => sizeof(int),
+            ArrowTypeId.LargeBinary or ArrowTypeId.LargeString or 
ArrowTypeId.LargeList => sizeof(long),
+            _ => 0,
+        };
     }
 }
diff --git a/src/Apache.Arrow/C/CArrowArrayImporter.cs 
b/src/Apache.Arrow/C/CArrowArrayImporter.cs
index 4a4edd5..a873595 100644
--- a/src/Apache.Arrow/C/CArrowArrayImporter.cs
+++ b/src/Apache.Arrow/C/CArrowArrayImporter.cs
@@ -288,6 +288,21 @@ namespace Apache.Arrow.C
                 }
             }
 
+            // Some producers (including older versions of this library) 
export a null offsets
+            // buffer for a zero-length array. Accept that, but not for a 
non-empty array.
+            private static bool HasOffsetsBuffer(CArrowArray* cArray)
+            {
+                if (cArray->buffers[1] != null)
+                {
+                    return true;
+                }
+                if (cArray->length != 0)
+                {
+                    throw new InvalidOperationException("Array has a non-zero 
length but no offsets buffer");
+                }
+                return false;
+            }
+
             private ArrowBuffer[] ImportByteArrayBuffers(CArrowArray* cArray)
             {
                 if (cArray->n_buffers != 3)
@@ -295,10 +310,14 @@ namespace Apache.Arrow.C
                     throw new InvalidOperationException("Byte arrays are 
expected to have exactly three buffers");
                 }
 
+                if (!HasOffsetsBuffer(cArray))
+                {
+                    return new ArrowBuffer[] { ImportValidityBuffer(cArray), 
ArrowBuffer.Empty, ArrowBuffer.Empty };
+                }
+
                 int length = checked((int)cArray->offset + 
(int)cArray->length);
                 int offsetsLength = (length + 1) * 4;
                 int* offsets = (int*)cArray->buffers[1];
-                Debug.Assert(offsets != null);
                 int valuesLength = offsets[length];
 
                 ArrowBuffer[] buffers = new ArrowBuffer[3];
@@ -346,10 +365,14 @@ namespace Apache.Arrow.C
                         $"is greater than the maximum supported large byte 
array length ({maxLength})");
                 }
 
+                if (!HasOffsetsBuffer(cArray))
+                {
+                    return new ArrowBuffer[] { ImportValidityBuffer(cArray), 
ArrowBuffer.Empty, ArrowBuffer.Empty };
+                }
+
                 int length = checked((int)cArray->offset + 
(int)cArray->length);
                 int offsetsLength = (length + 1) * 8;
                 long* offsets = (long*)cArray->buffers[1];
-                Debug.Assert(offsets != null);
                 long valuesLength = offsets[length];
 
                 if (valuesLength > int.MaxValue)
@@ -379,7 +402,7 @@ namespace Apache.Arrow.C
 
                 ArrowBuffer[] buffers = new ArrowBuffer[2];
                 buffers[0] = ImportValidityBuffer(cArray);
-                buffers[1] = ImportCArrayBuffer(cArray, 1, offsetsLength);
+                buffers[1] = HasOffsetsBuffer(cArray) ? 
ImportCArrayBuffer(cArray, 1, offsetsLength) : ArrowBuffer.Empty;
 
                 return buffers;
             }
@@ -448,7 +471,7 @@ namespace Apache.Arrow.C
 
                 ArrowBuffer[] buffers = new ArrowBuffer[2];
                 buffers[0] = ImportValidityBuffer(cArray);
-                buffers[1] = ImportCArrayBuffer(cArray, 1, offsetsLength);
+                buffers[1] = HasOffsetsBuffer(cArray) ? 
ImportCArrayBuffer(cArray, 1, offsetsLength) : ArrowBuffer.Empty;
 
                 return buffers;
             }
diff --git a/test/Apache.Arrow.Tests/CDataInterfaceDataTests.cs 
b/test/Apache.Arrow.Tests/CDataInterfaceDataTests.cs
index 1936359..5fcabb2 100644
--- a/test/Apache.Arrow.Tests/CDataInterfaceDataTests.cs
+++ b/test/Apache.Arrow.Tests/CDataInterfaceDataTests.cs
@@ -14,6 +14,8 @@
 // limitations under the License.
 
 using System;
+using System.Collections.Generic;
+using System.Linq;
 using System.Runtime.InteropServices;
 using Apache.Arrow.C;
 using Apache.Arrow.Types;
@@ -34,6 +36,115 @@ namespace Apache.Arrow.Tests
             return builder.Build();
         }
 
+        // Zero-length arrays whose offsets buffers (including those of nested 
children) are empty,
+        // as they are when read from IPC written by Arrow C++ or nanoarrow.
+        internal static IEnumerable<IArrowArray> 
GetZeroLengthArraysWithEmptyOffsets()
+        {
+            IArrowArray[] arrays =
+            {
+                new StringArray.Builder().Build(),
+                new BinaryArray.Builder().Build(),
+                new LargeStringArray.Builder().Build(),
+                new LargeBinaryArray.Builder().Build(),
+                new ListArray.Builder(StringType.Default).Build(),
+                new LargeListArray.Builder(Int32Type.Default).Build(),
+                new MapArray.Builder(new MapType(StringType.Default, 
Int32Type.Default)).Build(),
+            };
+            return arrays.Select(array => 
ArrowArrayFactory.BuildArray(WithEmptyOffsets(array.Data)));
+        }
+
+        private static ArrayData WithEmptyOffsets(ArrayData data)
+        {
+            ArrowBuffer[] buffers = data.Buffers.ToArray();
+            switch (data.DataType.TypeId)
+            {
+                case ArrowTypeId.Binary:
+                case ArrowTypeId.String:
+                case ArrowTypeId.LargeBinary:
+                case ArrowTypeId.LargeString:
+                case ArrowTypeId.List:
+                case ArrowTypeId.LargeList:
+                case ArrowTypeId.Map:
+                    buffers[1] = ArrowBuffer.Empty;
+                    break;
+            }
+            ArrayData[] children = 
data.Children?.Select(WithEmptyOffsets).ToArray();
+            return new ArrayData(data.DataType, data.Length, data.NullCount, 
data.Offset, buffers, children);
+        }
+
+        private static long[] GetValueOffsets(IArrowArray array) => array 
switch
+        {
+            BinaryArray a => a.ValueOffsets.ToArray().Select(o => 
(long)o).ToArray(),
+            LargeBinaryArray a => a.ValueOffsets.ToArray(),
+            ListArray a => a.ValueOffsets.ToArray().Select(o => 
(long)o).ToArray(),
+            LargeListArray a => a.ValueOffsets.ToArray(),
+            _ => throw new ArgumentException($"Unexpected array type 
{array.GetType()}"),
+        };
+
+        [Fact]
+        public void ValueOffsetsOfZeroLengthArrayWithEmptyOffsets()
+        {
+            foreach (IArrowArray array in 
GetZeroLengthArraysWithEmptyOffsets())
+            {
+                Assert.Equal(new long[] { 0 }, GetValueOffsets(array));
+            }
+        }
+
+        [Fact]
+        public unsafe void ExportZeroLengthArrayWithEmptyOffsets()
+        {
+            foreach (IArrowArray array in 
GetZeroLengthArraysWithEmptyOffsets())
+            {
+                CArrowArray* cArray = CArrowArray.Create();
+                CArrowArrayExporter.ExportArray(array, cArray);
+
+                // Consumers expect a single zero offset, not a null pointer
+                Assert.True(cArray->buffers[1] != null, 
$"{array.Data.DataType.Name} offsets were not exported");
+                Assert.Equal(0, *(int*)cArray->buffers[1]);
+
+                using (IArrowArray imported = 
CArrowArrayImporter.ImportArray(cArray, array.Data.DataType))
+                {
+                    Assert.Equal(0, imported.Length);
+                    Assert.Equal(new long[] { 0 }, GetValueOffsets(imported));
+                }
+                CArrowArray.Free(cArray);
+            }
+        }
+
+        [Fact]
+        public unsafe void ImportZeroLengthArrayWithNullOffsets()
+        {
+            foreach (IArrowArray array in 
GetZeroLengthArraysWithEmptyOffsets())
+            {
+                CArrowArray* cArray = CArrowArray.Create();
+                CArrowArrayExporter.ExportArray(array, cArray);
+
+                // The C Data interface allows a null pointer where the buffer 
would be empty,
+                // and some producers export a zero-length array's offsets 
that way.
+                cArray->buffers[1] = null;
+
+                using (IArrowArray imported = 
CArrowArrayImporter.ImportArray(cArray, array.Data.DataType))
+                {
+                    Assert.Equal(0, imported.Length);
+                    Assert.Equal(new long[] { 0 }, GetValueOffsets(imported));
+                }
+                CArrowArray.Free(cArray);
+            }
+        }
+
+        [Fact]
+        public unsafe void ImportNonEmptyArrayWithNullOffsetsThrows()
+        {
+            IArrowArray array = GetTestArray();
+            CArrowArray* cArray = CArrowArray.Create();
+            CArrowArrayExporter.ExportArray(array, cArray);
+            cArray->buffers[1] = null;
+
+            Assert.Throws<InvalidOperationException>(() => 
CArrowArrayImporter.ImportArray(cArray, array.Data.DataType));
+            Assert.True(cArray->release == default);
+            CArrowArray.Free(cArray);
+        }
+
         [Fact]
         public unsafe void InitializeArrayZeroed()
         {
diff --git a/test/Apache.Arrow.Tests/CDataInterfacePythonTests.cs 
b/test/Apache.Arrow.Tests/CDataInterfacePythonTests.cs
index fa6c56c..f233266 100644
--- a/test/Apache.Arrow.Tests/CDataInterfacePythonTests.cs
+++ b/test/Apache.Arrow.Tests/CDataInterfacePythonTests.cs
@@ -693,6 +693,32 @@ namespace Apache.Arrow.Tests
             CArrowSchema.Free(cSchema);
         }
 
+        [SkippableFact]
+        public unsafe void ExportZeroLengthArrayWithEmptyOffsets()
+        {
+            foreach (IArrowArray array in 
CDataInterfaceDataTests.GetZeroLengthArraysWithEmptyOffsets())
+            {
+                CArrowArray* cArray = CArrowArray.Create();
+                CArrowArrayExporter.ExportArray(array, cArray);
+                CArrowSchema* cSchema = CArrowSchema.Create();
+                CArrowSchemaExporter.ExportType(array.Data.DataType, cSchema);
+
+                long arrayPtr = ((IntPtr)cArray).ToInt64();
+                long schemaPtr = ((IntPtr)cSchema).ToInt64();
+
+                using (Py.GIL())
+                {
+                    dynamic pa = Py.Import("pyarrow");
+                    dynamic exportedPyArray = 
pa.Array._import_from_c(arrayPtr, schemaPtr);
+                    exportedPyArray.validate(full: true);
+                    Assert.Equal(0, (int)exportedPyArray.__len__());
+                }
+
+                CArrowArray.Free(cArray);
+                CArrowSchema.Free(cSchema);
+            }
+        }
+
         [SkippableFact]
         public unsafe void ExportManagedMemoryArray()
         {

Reply via email to