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


##########
test/Apache.Arrow.Tests/CDataInterfacePythonTests.cs:
##########
@@ -1030,12 +1030,12 @@ public async Task ExportBatchReadFromIpc()
         [SkippableFact]
         public async Task EarlyDisposeOfExportedBatch()
         {
-            // Reading IPC data from a Stream creates Arrow buffers backed by 
ReadOnlyMemory that point
-            // to slices of a single memory buffer owned by the RecordBatch 
(unless compression is used).
-            // Using the exported data after the RecordBatch has been disposed 
could cause
-            // memory corruption or access violations.
+            // Reading IPC data from a Stream creates buffers that are slices 
of the message body
+            // (unless compression is used). Each holds a reference to the 
body, so the exported
+            // data keeps it alive after the RecordBatch has been disposed.
 
             var originalBatch = GetTestRecordBatch();
+            dynamic pyBatch = GetPythonRecordBatch();

Review Comment:
   `pyBatch` is created outside a `Py.GIL()` scope, and the assertion uses 
`==`, which may not perform value equality for pyarrow `RecordBatch` (and can 
yield unexpected semantics depending on pyarrow/pythonnet). Create/hold Python 
objects under the GIL and compare via a value-based API (e.g., 
`exportedPyBatch.equals(pyBatch)` or comparing converted representations) to 
ensure the test actually validates data equality deterministically.



##########
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:
   `CArrowArray.Free(cArray)` / `CArrowSchema.Free(cSchema)` are not protected 
by a `finally`. If `Py.Import`, `_import_from_c`, or the assertion throws, the 
native structs won't be freed, which can leak unmanaged resources and make test 
failures harder to diagnose. Wrap the Python import/assert block in a `try` and 
free both pointers in a `finally`.



##########
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);
+                    }

Review Comment:
   `pyBatch` is created outside a `Py.GIL()` scope, and the assertion uses 
`==`, which may not perform value equality for pyarrow `RecordBatch` (and can 
yield unexpected semantics depending on pyarrow/pythonnet). Create/hold Python 
objects under the GIL and compare via a value-based API (e.g., 
`exportedPyBatch.equals(pyBatch)` or comparing converted representations) to 
ensure the test actually validates data equality deterministically.



##########
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();

Review Comment:
   `new NativeMemoryAllocator()` is created without being disposed. Since other 
allocators in this file are disposed (e.g., `PoisonMemoryAllocator`), it’s 
important to ensure `NativeMemoryAllocator` is also disposed to avoid leaking 
unmanaged memory across the test run. Consider `using var allocator = new 
NativeMemoryAllocator();` and pass `allocator` to `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();

Review Comment:
   `slice` and `retained` are disposed manually after multiple assertions. If 
an assertion fails before disposal, these objects (and the allocator’s rented 
memory) may be left outstanding, which can cascade into later test failures. 
Prefer `using` declarations (or a `try/finally`) for `slice` and `retained` to 
guarantee cleanup even when assertions fail.



##########
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) },

Review Comment:
   `RunEndEncodedArray` is constructed inline and never disposed, and 
`RecordBatch` itself is not disposed. Even though this is test code, these 
types typically own/track disposable buffers; leaving them undisposed can 
create resource pressure and make failures more order-dependent. Consider 
disposing the `RecordBatch` (e.g., via `using`) and/or constructing the 
`RunEndEncodedArray` as a named disposable so its lifetime is explicit.



-- 
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