Copilot commented on code in PR #537:
URL: https://github.com/apache/arrow-dotnet/pull/537#discussion_r4800858482


##########
src/Apache.Arrow/Ipc/ArrowReaderImplementation.cs:
##########
@@ -214,6 +214,35 @@ internal static ByteBuffer 
CreateByteBuffer(ReadOnlyMemory<byte> buffer)
             return new ByteBuffer(new ReadOnlyMemoryBufferAllocator(buffer), 
0);
         }
 
+        /// <summary>
+        /// Builds a record batch whose buffers hold references to the message 
body, so that anything
+        /// that shares them, such as a slice, a retained array or an exported 
array, keeps the body
+        /// alive after the batch is disposed. The batch holds a reference of 
its own, which it
+        /// releases when it is disposed.
+        /// </summary>
+        /// <param name="memoryOwner">
+        /// The message body, of which this takes ownership, including on 
failure.

Review Comment:
   This XML doc contradicts the implementation: `ReadRecordBatch` releases 
`body` in its `finally` block (line 242), and the returned `RecordBatch` is 
constructed with `memoryOwner: null` (line 236), so the batch itself does *not* 
hold and release a body reference. Update the doc to state that the reader 
transfers ownership to per-buffer references and then releases the reader's 
reference immediately after building arrays.



##########
test/Apache.Arrow.Tests/CDataInterfacePythonTests.cs:
##########
@@ -1059,7 +1059,16 @@ public async Task EarlyDisposeOfExportedBatch()
                     CArrowSchema* cSchema = CArrowSchema.Create();
                     CArrowSchemaExporter.ExportSchema(batch.Schema, cSchema);
 
-                    Assert.Throws<InvalidOperationException>(() => 
batch.Dispose());
+                    batch.Dispose();
+
+                    long arrayPtr = ((IntPtr)cArray).ToInt64();
+                    long schemaPtr = ((IntPtr)cSchema).ToInt64();
+                    using (Py.GIL())
+                    {
+                        dynamic pa = Py.Import("pyarrow");
+                        dynamic exportedPyBatch = 
pa.RecordBatch._import_from_c(arrayPtr, schemaPtr);
+                        Assert.True(exportedPyBatch == pyBatch);
+                    }
 
                     CArrowArray.Free(cArray);
                     CArrowSchema.Free(cSchema);

Review Comment:
   After calling `pyarrow.RecordBatch._import_from_c`, ownership of the C Data 
Interface structs is typically transferred to PyArrow. Unconditionally calling 
`CArrowArray.Free` / `CArrowSchema.Free` afterwards risks prematurely releasing 
buffers (or double-releasing) depending on how `Free` is implemented (e.g., if 
it invokes `release`). Consider either (a) not freeing here and letting PyArrow 
own the lifecycle, or (b) only freeing the *struct memory* after verifying the 
importer has nulled `release` (so `Free` can't release buffers still in use).



##########
test/Apache.Arrow.Tests/RecordBatchBodyReferenceTests.cs:
##########
@@ -0,0 +1,450 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using Apache.Arrow.C;
+using Apache.Arrow.Ipc;
+using Apache.Arrow.Memory;
+using Apache.Arrow.Types;
+using Xunit;
+
+namespace Apache.Arrow.Tests
+{
+    /// <summary>
+    /// The buffers of a record batch read from a stream are views of the 
message body, and each
+    /// holds a reference to it. Anything that shares those buffers, such as a 
slice, a retained
+    /// array, a concatenation or an exported array, keeps the body alive 
after the batch is
+    /// disposed, and the body is released along with the last of them.
+    /// </summary>
+    public class RecordBatchBodyReferenceTests
+    {
+        private static readonly int?[] s_ints = { 1, 2, 3, 4, null };
+        private static readonly string[] s_strings =
+        {
+            "the first string, too long to inline",
+            "the second string, too long to inline",
+            "short",
+            null,
+            "the fifth string, too long to inline",
+        };
+        private static readonly int[] s_runs = { 10, 10, 20, 20, 20 };
+
+        public enum Source
+        {
+            // ArrowStreamReader over a MemoryStream, which copies each body 
out of the stream's buffer
+            MemoryStream,
+            // ArrowStreamReader over any other stream
+            Stream,
+            // ArrowFileReader
+            File,
+        }
+
+        public enum Body
+        {
+            Uncompressed,
+            Compressed,
+            // Compressed, but no buffer gets smaller, so the writer stores 
them all uncompressed
+            StoredUncompressed,
+        }
+
+        public static TheoryData<Source, Body> Formats()
+        {
+            var data = new TheoryData<Source, Body>();
+            foreach (Source source in new[] { Source.MemoryStream, 
Source.Stream, Source.File })
+            {
+                foreach (Body body in new[] { Body.Uncompressed, 
Body.Compressed, Body.StoredUncompressed })
+                {
+                    data.Add(source, body);
+                }
+            }
+            return data;
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void ASharedSliceOfTheBatchOutlivesIt(Source source, Body body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch = ReadBatch(source, body, allocator);
+
+            using RecordBatch slice = batch.SliceShared(1, 3);
+            batch.Dispose();
+
+            Assert.Equal(s_ints.Skip(1).Take(3), Ints(slice.Column(0)));
+            Assert.Equal(s_strings.Skip(1).Take(3), Strings(slice.Column(1)));
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void ASharedSliceOfAnArrayOutlivesTheBatch(Source source, Body 
body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch = ReadBatch(source, body, allocator);
+
+            using IArrowArray ints = 
ArrowArrayFactory.SliceShared(batch.Column(0), 0, s_ints.Length);
+            using IArrowArray strings = 
ArrowArrayFactory.SliceShared(batch.Column(1), 0, s_strings.Length);
+            batch.Dispose();
+
+            Assert.Equal(s_ints, Ints(ints));
+            Assert.Equal(s_strings, Strings(strings));
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void RetainedArrayDataOutlivesTheBatch(Source source, Body body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch = ReadBatch(source, body, allocator);
+
+            using IArrowArray ints = 
ArrowArrayFactory.BuildArray(batch.Column(0).Data.Retain());
+            using IArrowArray strings = 
ArrowArrayFactory.BuildArray(batch.Column(1).Data.Retain());
+            batch.Dispose();
+
+            Assert.Equal(s_ints, Ints(ints));
+            Assert.Equal(s_strings, Strings(strings));
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void ConcatenatingOneArrayOutlivesTheBatch(Source source, Body 
body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch = ReadBatch(source, body, allocator);
+
+            using IArrowArray ints = ArrowArrayConcatenator.Concatenate(new[] 
{ batch.Column(0) });
+            batch.Dispose();
+
+            Assert.Equal(s_ints, Ints(ints));
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void ConcatenatedStringViewsOutliveTheBatches(Source source, 
Body body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch first = ReadBatch(source, body, allocator);
+            RecordBatch second = ReadBatch(source, body, allocator);
+
+            // The concatenation shares the inputs' variadic data buffers
+            using IArrowArray strings = ArrowArrayConcatenator.Concatenate(
+                new List<IArrowArray> { first.Column(1), second.Column(1) });
+            first.Dispose();
+            second.Dispose();
+
+            Assert.Equal(s_strings.Concat(s_strings), Strings(strings));
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void ANormalizedRunEndEncodedArrayOutlivesTheBatch(Source 
source, Body body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch = ReadBatch(source, body, allocator);
+
+            using RunEndEncodedArray normalized = 
((RunEndEncodedArray)batch.Column(2)).Normalize();
+            batch.Dispose();
+
+            Assert.Equal(s_runs, Runs(normalized));
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public unsafe void AnExportedBatchOutlivesTheBatch(Source source, Body 
body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch = ReadBatch(source, body, allocator);
+            Schema schema = batch.Schema;
+
+            CArrowArray* cArray = CArrowArray.Create();
+            try
+            {
+                CArrowArrayExporter.ExportRecordBatch(batch, cArray);
+                batch.Dispose();
+
+                using RecordBatch imported = 
CArrowArrayImporter.ImportRecordBatch(cArray, schema);
+                Assert.Equal(s_ints, Ints(imported.Column(0)));
+                Assert.Equal(s_strings, Strings(imported.Column(1)));
+                Assert.Equal(s_runs, Runs(imported.Column(2)));
+            }
+            finally
+            {
+                CArrowArray.Free(cArray);
+            }
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public unsafe void AnExportedArrayOutlivesTheBatch(Source source, Body 
body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch = ReadBatch(source, body, allocator);
+
+            CArrowArray* cArray = CArrowArray.Create();
+            try
+            {
+                CArrowArrayExporter.ExportArray(batch.Column(1), cArray);
+                batch.Dispose();
+
+                using IArrowArray imported = 
CArrowArrayImporter.ImportArray(cArray, StringViewType.Default);
+                Assert.Equal(s_strings, Strings(imported));
+            }
+            finally
+            {
+                CArrowArray.Free(cArray);
+            }
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public unsafe void 
ABatchReadWithTheDefaultAllocatorCanBeDisposedWhileExported(Source source, Body 
body)
+        {
+            RecordBatch batch = ReadBatch(source, body, new 
NativeMemoryAllocator());
+            Schema schema = batch.Schema;
+
+            CArrowArray* cArray = CArrowArray.Create();
+            try
+            {
+                CArrowArrayExporter.ExportRecordBatch(batch, cArray);
+                batch.Dispose();
+
+                using RecordBatch imported = 
CArrowArrayImporter.ImportRecordBatch(cArray, schema);
+                Assert.Equal(s_ints, Ints(imported.Column(0)));
+                Assert.Equal(s_strings, Strings(imported.Column(1)));
+            }
+            finally
+            {
+                CArrowArray.Free(cArray);
+            }
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void 
ABatchReadWithTheDefaultAllocatorCanBeDisposedBeforeItsSlice(Source source, 
Body body)
+        {
+            RecordBatch batch = ReadBatch(source, body, new 
NativeMemoryAllocator());
+
+            using RecordBatch slice = batch.SliceShared(0, s_ints.Length);
+            batch.Dispose();

Review Comment:
   Same disposal issue here: `new NativeMemoryAllocator()` isn't disposed. Wrap 
it in `using var allocator = new NativeMemoryAllocator();` to avoid unmanaged 
leaks and improve test reliability.



##########
test/Apache.Arrow.Tests/RecordBatchBodyReferenceTests.cs:
##########
@@ -0,0 +1,450 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using Apache.Arrow.C;
+using Apache.Arrow.Ipc;
+using Apache.Arrow.Memory;
+using Apache.Arrow.Types;
+using Xunit;
+
+namespace Apache.Arrow.Tests
+{
+    /// <summary>
+    /// The buffers of a record batch read from a stream are views of the 
message body, and each
+    /// holds a reference to it. Anything that shares those buffers, such as a 
slice, a retained
+    /// array, a concatenation or an exported array, keeps the body alive 
after the batch is
+    /// disposed, and the body is released along with the last of them.
+    /// </summary>
+    public class RecordBatchBodyReferenceTests
+    {
+        private static readonly int?[] s_ints = { 1, 2, 3, 4, null };
+        private static readonly string[] s_strings =
+        {
+            "the first string, too long to inline",
+            "the second string, too long to inline",
+            "short",
+            null,
+            "the fifth string, too long to inline",
+        };
+        private static readonly int[] s_runs = { 10, 10, 20, 20, 20 };
+
+        public enum Source
+        {
+            // ArrowStreamReader over a MemoryStream, which copies each body 
out of the stream's buffer
+            MemoryStream,
+            // ArrowStreamReader over any other stream
+            Stream,
+            // ArrowFileReader
+            File,
+        }
+
+        public enum Body
+        {
+            Uncompressed,
+            Compressed,
+            // Compressed, but no buffer gets smaller, so the writer stores 
them all uncompressed
+            StoredUncompressed,
+        }
+
+        public static TheoryData<Source, Body> Formats()
+        {
+            var data = new TheoryData<Source, Body>();
+            foreach (Source source in new[] { Source.MemoryStream, 
Source.Stream, Source.File })
+            {
+                foreach (Body body in new[] { Body.Uncompressed, 
Body.Compressed, Body.StoredUncompressed })
+                {
+                    data.Add(source, body);
+                }
+            }
+            return data;
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void ASharedSliceOfTheBatchOutlivesIt(Source source, Body body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch = ReadBatch(source, body, allocator);
+
+            using RecordBatch slice = batch.SliceShared(1, 3);
+            batch.Dispose();
+
+            Assert.Equal(s_ints.Skip(1).Take(3), Ints(slice.Column(0)));
+            Assert.Equal(s_strings.Skip(1).Take(3), Strings(slice.Column(1)));
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void ASharedSliceOfAnArrayOutlivesTheBatch(Source source, Body 
body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch = ReadBatch(source, body, allocator);
+
+            using IArrowArray ints = 
ArrowArrayFactory.SliceShared(batch.Column(0), 0, s_ints.Length);
+            using IArrowArray strings = 
ArrowArrayFactory.SliceShared(batch.Column(1), 0, s_strings.Length);
+            batch.Dispose();
+
+            Assert.Equal(s_ints, Ints(ints));
+            Assert.Equal(s_strings, Strings(strings));
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void RetainedArrayDataOutlivesTheBatch(Source source, Body body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch = ReadBatch(source, body, allocator);
+
+            using IArrowArray ints = 
ArrowArrayFactory.BuildArray(batch.Column(0).Data.Retain());
+            using IArrowArray strings = 
ArrowArrayFactory.BuildArray(batch.Column(1).Data.Retain());
+            batch.Dispose();
+
+            Assert.Equal(s_ints, Ints(ints));
+            Assert.Equal(s_strings, Strings(strings));
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void ConcatenatingOneArrayOutlivesTheBatch(Source source, Body 
body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch = ReadBatch(source, body, allocator);
+
+            using IArrowArray ints = ArrowArrayConcatenator.Concatenate(new[] 
{ batch.Column(0) });
+            batch.Dispose();
+
+            Assert.Equal(s_ints, Ints(ints));
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void ConcatenatedStringViewsOutliveTheBatches(Source source, 
Body body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch first = ReadBatch(source, body, allocator);
+            RecordBatch second = ReadBatch(source, body, allocator);
+
+            // The concatenation shares the inputs' variadic data buffers
+            using IArrowArray strings = ArrowArrayConcatenator.Concatenate(
+                new List<IArrowArray> { first.Column(1), second.Column(1) });
+            first.Dispose();
+            second.Dispose();
+
+            Assert.Equal(s_strings.Concat(s_strings), Strings(strings));
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void ANormalizedRunEndEncodedArrayOutlivesTheBatch(Source 
source, Body body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch = ReadBatch(source, body, allocator);
+
+            using RunEndEncodedArray normalized = 
((RunEndEncodedArray)batch.Column(2)).Normalize();
+            batch.Dispose();
+
+            Assert.Equal(s_runs, Runs(normalized));
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public unsafe void AnExportedBatchOutlivesTheBatch(Source source, Body 
body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch = ReadBatch(source, body, allocator);
+            Schema schema = batch.Schema;
+
+            CArrowArray* cArray = CArrowArray.Create();
+            try
+            {
+                CArrowArrayExporter.ExportRecordBatch(batch, cArray);
+                batch.Dispose();
+
+                using RecordBatch imported = 
CArrowArrayImporter.ImportRecordBatch(cArray, schema);
+                Assert.Equal(s_ints, Ints(imported.Column(0)));
+                Assert.Equal(s_strings, Strings(imported.Column(1)));
+                Assert.Equal(s_runs, Runs(imported.Column(2)));
+            }
+            finally
+            {
+                CArrowArray.Free(cArray);
+            }
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public unsafe void AnExportedArrayOutlivesTheBatch(Source source, Body 
body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch = ReadBatch(source, body, allocator);
+
+            CArrowArray* cArray = CArrowArray.Create();
+            try
+            {
+                CArrowArrayExporter.ExportArray(batch.Column(1), cArray);
+                batch.Dispose();
+
+                using IArrowArray imported = 
CArrowArrayImporter.ImportArray(cArray, StringViewType.Default);
+                Assert.Equal(s_strings, Strings(imported));
+            }
+            finally
+            {
+                CArrowArray.Free(cArray);
+            }
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public unsafe void 
ABatchReadWithTheDefaultAllocatorCanBeDisposedWhileExported(Source source, Body 
body)
+        {
+            RecordBatch batch = ReadBatch(source, body, new 
NativeMemoryAllocator());

Review Comment:
   `NativeMemoryAllocator` is created without being disposed. Since it 
typically backs unmanaged allocations, this can leak across the test run 
(especially if an assertion fails before cleanup). Use a `using var allocator = 
new NativeMemoryAllocator();` and pass that into `ReadBatch`.



##########
test/Apache.Arrow.Tests/RecordBatchBodyReferenceTests.cs:
##########
@@ -0,0 +1,450 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements. See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using Apache.Arrow.C;
+using Apache.Arrow.Ipc;
+using Apache.Arrow.Memory;
+using Apache.Arrow.Types;
+using Xunit;
+
+namespace Apache.Arrow.Tests
+{
+    /// <summary>
+    /// The buffers of a record batch read from a stream are views of the 
message body, and each
+    /// holds a reference to it. Anything that shares those buffers, such as a 
slice, a retained
+    /// array, a concatenation or an exported array, keeps the body alive 
after the batch is
+    /// disposed, and the body is released along with the last of them.
+    /// </summary>
+    public class RecordBatchBodyReferenceTests
+    {
+        private static readonly int?[] s_ints = { 1, 2, 3, 4, null };
+        private static readonly string[] s_strings =
+        {
+            "the first string, too long to inline",
+            "the second string, too long to inline",
+            "short",
+            null,
+            "the fifth string, too long to inline",
+        };
+        private static readonly int[] s_runs = { 10, 10, 20, 20, 20 };
+
+        public enum Source
+        {
+            // ArrowStreamReader over a MemoryStream, which copies each body 
out of the stream's buffer
+            MemoryStream,
+            // ArrowStreamReader over any other stream
+            Stream,
+            // ArrowFileReader
+            File,
+        }
+
+        public enum Body
+        {
+            Uncompressed,
+            Compressed,
+            // Compressed, but no buffer gets smaller, so the writer stores 
them all uncompressed
+            StoredUncompressed,
+        }
+
+        public static TheoryData<Source, Body> Formats()
+        {
+            var data = new TheoryData<Source, Body>();
+            foreach (Source source in new[] { Source.MemoryStream, 
Source.Stream, Source.File })
+            {
+                foreach (Body body in new[] { Body.Uncompressed, 
Body.Compressed, Body.StoredUncompressed })
+                {
+                    data.Add(source, body);
+                }
+            }
+            return data;
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void ASharedSliceOfTheBatchOutlivesIt(Source source, Body body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch = ReadBatch(source, body, allocator);
+
+            using RecordBatch slice = batch.SliceShared(1, 3);
+            batch.Dispose();
+
+            Assert.Equal(s_ints.Skip(1).Take(3), Ints(slice.Column(0)));
+            Assert.Equal(s_strings.Skip(1).Take(3), Strings(slice.Column(1)));
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void ASharedSliceOfAnArrayOutlivesTheBatch(Source source, Body 
body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch = ReadBatch(source, body, allocator);
+
+            using IArrowArray ints = 
ArrowArrayFactory.SliceShared(batch.Column(0), 0, s_ints.Length);
+            using IArrowArray strings = 
ArrowArrayFactory.SliceShared(batch.Column(1), 0, s_strings.Length);
+            batch.Dispose();
+
+            Assert.Equal(s_ints, Ints(ints));
+            Assert.Equal(s_strings, Strings(strings));
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void RetainedArrayDataOutlivesTheBatch(Source source, Body body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch = ReadBatch(source, body, allocator);
+
+            using IArrowArray ints = 
ArrowArrayFactory.BuildArray(batch.Column(0).Data.Retain());
+            using IArrowArray strings = 
ArrowArrayFactory.BuildArray(batch.Column(1).Data.Retain());
+            batch.Dispose();
+
+            Assert.Equal(s_ints, Ints(ints));
+            Assert.Equal(s_strings, Strings(strings));
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void ConcatenatingOneArrayOutlivesTheBatch(Source source, Body 
body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch = ReadBatch(source, body, allocator);
+
+            using IArrowArray ints = ArrowArrayConcatenator.Concatenate(new[] 
{ batch.Column(0) });
+            batch.Dispose();
+
+            Assert.Equal(s_ints, Ints(ints));
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void ConcatenatedStringViewsOutliveTheBatches(Source source, 
Body body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch first = ReadBatch(source, body, allocator);
+            RecordBatch second = ReadBatch(source, body, allocator);
+
+            // The concatenation shares the inputs' variadic data buffers
+            using IArrowArray strings = ArrowArrayConcatenator.Concatenate(
+                new List<IArrowArray> { first.Column(1), second.Column(1) });
+            first.Dispose();
+            second.Dispose();
+
+            Assert.Equal(s_strings.Concat(s_strings), Strings(strings));
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void ANormalizedRunEndEncodedArrayOutlivesTheBatch(Source 
source, Body body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch = ReadBatch(source, body, allocator);
+
+            using RunEndEncodedArray normalized = 
((RunEndEncodedArray)batch.Column(2)).Normalize();
+            batch.Dispose();
+
+            Assert.Equal(s_runs, Runs(normalized));
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public unsafe void AnExportedBatchOutlivesTheBatch(Source source, Body 
body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch = ReadBatch(source, body, allocator);
+            Schema schema = batch.Schema;
+
+            CArrowArray* cArray = CArrowArray.Create();
+            try
+            {
+                CArrowArrayExporter.ExportRecordBatch(batch, cArray);
+                batch.Dispose();
+
+                using RecordBatch imported = 
CArrowArrayImporter.ImportRecordBatch(cArray, schema);
+                Assert.Equal(s_ints, Ints(imported.Column(0)));
+                Assert.Equal(s_strings, Strings(imported.Column(1)));
+                Assert.Equal(s_runs, Runs(imported.Column(2)));
+            }
+            finally
+            {
+                CArrowArray.Free(cArray);
+            }
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public unsafe void AnExportedArrayOutlivesTheBatch(Source source, Body 
body)
+        {
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch = ReadBatch(source, body, allocator);
+
+            CArrowArray* cArray = CArrowArray.Create();
+            try
+            {
+                CArrowArrayExporter.ExportArray(batch.Column(1), cArray);
+                batch.Dispose();
+
+                using IArrowArray imported = 
CArrowArrayImporter.ImportArray(cArray, StringViewType.Default);
+                Assert.Equal(s_strings, Strings(imported));
+            }
+            finally
+            {
+                CArrowArray.Free(cArray);
+            }
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public unsafe void 
ABatchReadWithTheDefaultAllocatorCanBeDisposedWhileExported(Source source, Body 
body)
+        {
+            RecordBatch batch = ReadBatch(source, body, new 
NativeMemoryAllocator());
+            Schema schema = batch.Schema;
+
+            CArrowArray* cArray = CArrowArray.Create();
+            try
+            {
+                CArrowArrayExporter.ExportRecordBatch(batch, cArray);
+                batch.Dispose();
+
+                using RecordBatch imported = 
CArrowArrayImporter.ImportRecordBatch(cArray, schema);
+                Assert.Equal(s_ints, Ints(imported.Column(0)));
+                Assert.Equal(s_strings, Strings(imported.Column(1)));
+            }
+            finally
+            {
+                CArrowArray.Free(cArray);
+            }
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void 
ABatchReadWithTheDefaultAllocatorCanBeDisposedBeforeItsSlice(Source source, 
Body body)
+        {
+            RecordBatch batch = ReadBatch(source, body, new 
NativeMemoryAllocator());
+
+            using RecordBatch slice = batch.SliceShared(0, s_ints.Length);
+            batch.Dispose();
+
+            Assert.Equal(s_ints, Ints(slice.Column(0)));
+            Assert.Equal(s_strings, Strings(slice.Column(1)));
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void TheBodyIsReleasedWithTheLastReferenceToIt(Source source, 
Body body)
+        {
+            byte[] data = Write(source, body);
+            var allocator = new TestMemoryAllocator();
+            RecordBatch batch;
+            using (ArrowStreamReader reader = CreateReader(data, source, body, 
allocator))
+            {
+                batch = reader.ReadNextRecordBatch();
+            }
+
+            RecordBatch slice = batch.SliceShared(1, 2);
+            IArrowArray retained = 
ArrowArrayFactory.BuildArray(batch.Column(1).Data.Retain());
+            batch.Dispose();
+            Assert.True(allocator.Rented > 0);
+
+            slice.Dispose();
+            Assert.True(allocator.Rented > 0);
+            Assert.Equal(s_strings, Strings(retained));
+
+            retained.Dispose();
+
+            // TestMemoryAllocator's memory has no finalizer, so this was done 
by disposal
+            Assert.Equal(0, allocator.Rented);
+        }
+
+        [Theory]
+        [InlineData(Source.MemoryStream)]
+        [InlineData(Source.Stream)]
+        [InlineData(Source.File)]
+        public void 
ACompressedBodyIsReleasedOnceEveryBufferIsDecompressed(Source source)
+        {
+            // Zeros compress well, so the writer compresses every buffer and 
none views the body
+            var schema = new Schema.Builder().Field(f => 
f.Name("i").DataType(Int32Type.Default)).Build();
+            using Int32Array zeros = new Int32Array.Builder().AppendRange(new 
int[1000]).Build();
+            var options = new IpcOptions { CompressionCodec = 
CompressionCodecType.Zstd, CompressionCodecFactory = Codecs(Body.Compressed) };
+            var stream = new MemoryStream();
+            using (ArrowStreamWriter writer = source == Source.File
+                ? new ArrowFileWriter(stream, schema, leaveOpen: true, options)
+                : new ArrowStreamWriter(stream, schema, leaveOpen: true, 
options))
+            {
+                writer.WriteRecordBatch(new RecordBatch(schema, new 
IArrowArray[] { zeros }, zeros.Length));
+                writer.WriteEnd();
+            }
+
+            var allocator = new TestMemoryAllocator();
+            using ArrowStreamReader reader = CreateReader(stream.ToArray(), 
source, Body.Compressed, allocator);
+            using RecordBatch batch = reader.ReadNextRecordBatch();
+
+            // Only the decompressed values remain
+            Assert.Equal(1, allocator.Rented);
+            Assert.All(((Int32Array)batch.Column(0)).Values.ToArray(), value 
=> Assert.Equal(0, value));
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void ReadingIntoUnzeroedMemoryGivesTheSameValues(Source source, 
Body body)
+        {
+            var allocator = new GarbageMemoryAllocator(extraLength: 13);
+            RecordBatch batch = ReadBatch(source, body, allocator);
+
+            using RecordBatch slice = batch.SliceShared(0, s_ints.Length);
+            batch.Dispose();
+            Assert.Equal(s_ints, Ints(slice.Column(0)));
+            Assert.Equal(s_strings, Strings(slice.Column(1)));
+            Assert.Equal(s_runs, Runs(slice.Column(2)));
+            Assert.True(allocator.Outstanding > 0);
+
+            slice.Dispose();
+            Assert.Equal(0, allocator.Outstanding);
+        }
+
+        [Fact]
+        public void BatchesReadFromMemoryViewItAndOwnNothing()
+        {
+            byte[] data = Write(Source.Stream, Body.Uncompressed);
+            using var reader = new ArrowStreamReader(new 
ReadOnlyMemory<byte>(data));
+            RecordBatch batch = reader.ReadNextRecordBatch();
+
+            using RecordBatch slice = batch.SliceShared(0, s_ints.Length);
+            batch.Dispose();
+
+            // The caller owns the memory, which the slice still views
+            Assert.Equal(s_ints, Ints(slice.Column(0)));
+            Assert.Equal(s_strings, Strings(slice.Column(1)));
+        }
+
+        private static IEnumerable<int?> Ints(IArrowArray array)
+        {
+            var ints = (Int32Array)array;
+            return Enumerable.Range(0, ints.Length).Select(i => 
ints.GetValue(i));
+        }
+
+        private static IEnumerable<string> Strings(IArrowArray array)
+        {
+            var strings = (StringViewArray)array;
+            return Enumerable.Range(0, strings.Length).Select(i => 
strings.GetString(i));
+        }
+
+        private static IEnumerable<int> Runs(IArrowArray array)
+        {
+            var ree = (RunEndEncodedArray)array;
+            var values = (Int32Array)ree.Values;
+            return Enumerable.Range(0, ree.Length)
+                .Select(i => values.GetValue(ree.FindPhysicalIndex(i)).Value);
+        }
+
+        private static RecordBatch ReadBatch(Source source, Body body, 
MemoryAllocator allocator)
+        {
+            byte[] data = Write(source, body);
+            using ArrowStreamReader reader = CreateReader(data, source, body, 
allocator);
+            return reader.ReadNextRecordBatch();
+        }
+
+        private static byte[] Write(Source source, Body body)
+        {
+            var runEndType = new RunEndEncodedType(Int32Type.Default, 
Int32Type.Default);
+            var schema = new Schema.Builder()
+                .Field(f => f.Name("i").DataType(Int32Type.Default))
+                .Field(f => f.Name("s").DataType(StringViewType.Default))
+                .Field(f => f.Name("r").DataType(runEndType).Nullable(false))
+                .Build();
+
+            using Int32Array ints = new Int32Array.Builder().AppendRange(new[] 
{ 1, 2, 3, 4 }).AppendNull().Build();
+            using StringViewArray strings = new 
StringViewArray.Builder().AppendRange(s_strings).Build();
+            using Int32Array runEnds = new 
Int32Array.Builder().AppendRange(new[] { 2, 5 }).Build();
+            using Int32Array runValues = new 
Int32Array.Builder().AppendRange(new[] { 10, 20 }).Build();
+            var batch = new RecordBatch(
+                schema,
+                new IArrowArray[] { ints, strings, new 
RunEndEncodedArray(runEnds, runValues) },
+                s_ints.Length);
+
+            var options = body == Body.Uncompressed
+                ? new IpcOptions()
+                : new IpcOptions { CompressionCodec = 
CompressionCodecType.Zstd, CompressionCodecFactory = Codecs(body) };
+            var stream = new MemoryStream();
+            using (ArrowStreamWriter writer = source == Source.File
+                ? new ArrowFileWriter(stream, schema, leaveOpen: true, options)
+                : new ArrowStreamWriter(stream, schema, leaveOpen: true, 
options))
+            {
+                writer.WriteRecordBatch(batch);
+                writer.WriteEnd();
+            }
+            return stream.ToArray();
+        }
+
+        private static ArrowStreamReader CreateReader(byte[] data, Source 
source, Body body, MemoryAllocator allocator)
+        {
+            switch (source)
+            {
+                case Source.MemoryStream:
+                    return new ArrowStreamReader(new MemoryStream(data), 
allocator, Codecs(body), leaveOpen: false);
+                case Source.Stream:
+                    return new ArrowStreamReader(new OpaqueStream(data), 
allocator, Codecs(body), leaveOpen: false);
+                default:
+                    return new ArrowFileReader(new MemoryStream(data), 
allocator, Codecs(body), leaveOpen: false);
+            }
+        }
+
+        private static DictionaryReferenceTests.DeflateCodecFactory 
Codecs(Body body) =>
+            new DictionaryReferenceTests.DeflateCodecFactory { Incompressible 
= body == Body.StoredUncompressed };
+
+        /// <summary>

Review Comment:
   This introduces a hard dependency from `RecordBatchBodyReferenceTests` onto 
another test class’ nested type. To reduce brittleness (e.g., 
refactors/renames), consider moving `DeflateCodecFactory` to a shared test 
helper (or duplicating the minimal factory here) so these tests don't depend on 
`DictionaryReferenceTests` internals.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to