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


##########
src/Apache.Arrow/Ipc/ArrowReaderImplementation.cs:
##########
@@ -126,42 +126,67 @@ private static bool MatchEnum(Flatbuf.MessageHeader 
messageHeader, Type flatBuff
         /// Create a record batch or dictionary batch from Flatbuf.Message.
         /// </summary>
         /// <remarks>
+        /// <para>
         /// This method adds data to _dictionaryMemo and returns null when the 
message type is DictionaryBatch.
-        /// </remarks>>
+        /// </para>
+        /// <para>
+        /// Takes ownership of <paramref name="memoryOwner"/>, the message 
body: it either passes it
+        /// to the result or releases it, including when the message cannot be 
read.
+        /// </para>
+        /// </remarks>
         /// <returns>
         /// The record batch when the message type is RecordBatch.
         /// Null when the message type is not RecordBatch.
         /// </returns>
         protected RecordBatch CreateArrowObjectFromMessage(
             Flatbuf.Message message, ByteBuffer bodyByteBuffer, 
IMemoryOwner<byte> memoryOwner)
         {
-            switch (message.HeaderType)
+            bool bodyKept = false;
+            try
             {
-                case Flatbuf.MessageHeader.Schema:
-                    // TODO: Read schema and verify equality?
-                    break;
-                case Flatbuf.MessageHeader.DictionaryBatch:
-                    Flatbuf.DictionaryBatch dictionaryBatch = 
message.Header<Flatbuf.DictionaryBatch>().Value;
-                    ReadDictionaryBatch(message.Version, dictionaryBatch, 
bodyByteBuffer, memoryOwner);
-                    break;
-                case Flatbuf.MessageHeader.RecordBatch:
-                    Flatbuf.RecordBatch rb = 
message.Header<Flatbuf.RecordBatch>().Value;
-                    if (rb.Length < 0 || rb.Length > int.MaxValue)
-                    {
-                        throw new InvalidDataException(
-                            $"Cannot read batch. Message body of {rb.Length} 
rows is out of range.");
-                    }
+                switch (message.HeaderType)
+                {
+                    case Flatbuf.MessageHeader.Schema:
+                        // TODO: Read schema and verify equality?
+                        break;
+                    case Flatbuf.MessageHeader.DictionaryBatch:
+                        Flatbuf.DictionaryBatch dictionaryBatch = 
message.Header<Flatbuf.DictionaryBatch>().Value;
+                        ReadDictionaryBatch(message.Version, dictionaryBatch, 
bodyByteBuffer, memoryOwner);

Review Comment:
   A dictionary read can fail after `BuildArrays` succeeds. For example, a 
compressed delta dictionary arriving before its base dictionary makes 
`AddDeltaDictionary` throw, leaving the newly decompressed buffers undisposed 
even though the body is released. Release the newly read arrays when dictionary 
installation fails, while leaving existing memo dictionaries untouched.



##########
src/Apache.Arrow/Ipc/ArrowReaderImplementation.cs:
##########
@@ -126,42 +126,67 @@ private static bool MatchEnum(Flatbuf.MessageHeader 
messageHeader, Type flatBuff
         /// Create a record batch or dictionary batch from Flatbuf.Message.
         /// </summary>
         /// <remarks>
+        /// <para>
         /// This method adds data to _dictionaryMemo and returns null when the 
message type is DictionaryBatch.
-        /// </remarks>>
+        /// </para>
+        /// <para>
+        /// Takes ownership of <paramref name="memoryOwner"/>, the message 
body: it either passes it
+        /// to the result or releases it, including when the message cannot be 
read.
+        /// </para>
+        /// </remarks>
         /// <returns>
         /// The record batch when the message type is RecordBatch.
         /// Null when the message type is not RecordBatch.
         /// </returns>
         protected RecordBatch CreateArrowObjectFromMessage(
             Flatbuf.Message message, ByteBuffer bodyByteBuffer, 
IMemoryOwner<byte> memoryOwner)
         {
-            switch (message.HeaderType)
+            bool bodyKept = false;
+            try
             {
-                case Flatbuf.MessageHeader.Schema:
-                    // TODO: Read schema and verify equality?
-                    break;
-                case Flatbuf.MessageHeader.DictionaryBatch:
-                    Flatbuf.DictionaryBatch dictionaryBatch = 
message.Header<Flatbuf.DictionaryBatch>().Value;
-                    ReadDictionaryBatch(message.Version, dictionaryBatch, 
bodyByteBuffer, memoryOwner);
-                    break;
-                case Flatbuf.MessageHeader.RecordBatch:
-                    Flatbuf.RecordBatch rb = 
message.Header<Flatbuf.RecordBatch>().Value;
-                    if (rb.Length < 0 || rb.Length > int.MaxValue)
-                    {
-                        throw new InvalidDataException(
-                            $"Cannot read batch. Message body of {rb.Length} 
rows is out of range.");
-                    }
+                switch (message.HeaderType)
+                {
+                    case Flatbuf.MessageHeader.Schema:
+                        // TODO: Read schema and verify equality?
+                        break;
+                    case Flatbuf.MessageHeader.DictionaryBatch:
+                        Flatbuf.DictionaryBatch dictionaryBatch = 
message.Header<Flatbuf.DictionaryBatch>().Value;
+                        ReadDictionaryBatch(message.Version, dictionaryBatch, 
bodyByteBuffer, memoryOwner);
+
+                        // The dictionary's arrays refer to the body, so it 
must stay alive. Nothing
+                        // owns it, so it is reclaimed only by finalization, 
as before.
+                        bodyKept = true;
+                        break;
+                    case Flatbuf.MessageHeader.RecordBatch:
+                        Flatbuf.RecordBatch rb = 
message.Header<Flatbuf.RecordBatch>().Value;
+                        if (rb.Length < 0 || rb.Length > int.MaxValue)
+                        {
+                            throw new InvalidDataException(
+                                $"Cannot read batch. Message body of 
{rb.Length} rows is out of range.");
+                        }
 
-                    List<IArrowArray> arrays = BuildArrays(message.Version, 
Schema, bodyByteBuffer, rb);
-                    LastBatchCustomMetadata = 
ReadMessageCustomMetadata(message);
-                    return new RecordBatch(Schema, memoryOwner, arrays, 
(int)rb.Length);
-                default:
-                    // NOTE: Skip unsupported message type
-                    Debug.WriteLine($"Skipping unsupported message type 
'{message.HeaderType}'");
-                    break;
-            }
+                        List<IArrowArray> arrays = 
BuildArrays(message.Version, Schema, bodyByteBuffer, rb);
+                        LastBatchCustomMetadata = 
ReadMessageCustomMetadata(message);

Review Comment:
   If custom metadata contains a null key or corrupt offset, 
`ReadMessageCustomMetadata` throws after `BuildArrays` has allocated 
decompressed buffers. The new `finally` releases only the message body, leaving 
those arrays undisposed because they never reach a `RecordBatch`. Please parse 
metadata before building arrays, or release the arrays when this later step 
fails.



##########
src/Apache.Arrow/Ipc/ArrowStreamWriter.cs:
##########
@@ -987,7 +1020,21 @@ private Tuple<ArrowRecordBatchFlatBufferBuilder, 
VectorOffset, VectorOffset> Pre
                 : null;
 
             var recordBatchBuilder = new 
ArrowRecordBatchFlatBufferBuilder(compressionCodec, _allocator, 
_fallbackCompressionStream);
+            try
+            {
+                return PrepareWritingRecordBatch(recordBatchBuilder, fields, 
arrays);
+            }
+            catch
+            {
+                // The caller only takes ownership of the builder once this 
returns.
+                recordBatchBuilder.Dispose();

Review Comment:
   This cleanup only releases buffers already added to `_buffers`. 
`CreateBuffer` allocates `bufferOwner` before calling `TryCompress`, so a 
throwing compression codec leaves the current output allocation untracked; a 
locally owned rewritten-offset buffer can also be stranded there. Please make 
`CreateBuffer` release both owners on failure before ownership transfers to the 
builder, and cover a throwing compressor in the failure tests.



##########
test/Apache.Arrow.Tests/FailurePathReleaseTests.cs:
##########
@@ -0,0 +1,401 @@
+// 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.IO;
+using System.IO.Compression;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Apache.Arrow.Ipc;
+using Apache.Arrow.Types;
+using Xunit;
+
+namespace Apache.Arrow.Tests
+{
+    /// <summary>
+    /// Memory that Arrow allocates must be released when an operation fails 
partway through, not
+    /// left for a finalizer. Each test checks that nothing is still allocated 
straight after the
+    /// failure, before any garbage collection could hide a leak.
+    /// </summary>
+    public class FailurePathReleaseTests
+    {
+        // Concatenation
+
+        [Fact]
+        public void ConcatenatingFixedWidthReleasesValidityWhenValuesFail()
+        {
+            using Int32Array valid = new 
Int32Array.Builder().Append(1).AppendNull().Append(3).Build();
+            ArrayData malformed = MalformedInt32(length: 10);
+            var allocator = new TestMemoryAllocator();
+
+            Assert.ThrowsAny<Exception>(() => 
ArrayDataConcatenator.Concatenate(new[] { valid.Data, malformed }, allocator));
+
+            Assert.Equal(0, allocator.Rented);
+        }
+
+        [Fact]
+        public void ConcatenatingStringsReleasesBuiltBuffersWhenDataFails()
+        {
+            using StringArray valid = new 
StringArray.Builder().Append("a").AppendNull().Append("bc").Build();
+            // Offsets claim 30 bytes of data, but the data buffer has only 3
+            var offsets = new ArrowBuffer.Builder<int>().AppendRange(new[] { 
0, 10, 20, 30 }).Build();
+            var malformed = new ArrayData(StringType.Default, 3, 0, 0,
+                new[] { ArrowBuffer.Empty, offsets, new ArrowBuffer(new byte[] 
{ 1, 2, 3 }) });
+            var allocator = new TestMemoryAllocator();
+
+            Assert.ThrowsAny<Exception>(() => 
ArrayDataConcatenator.Concatenate(new[] { valid.Data, malformed }, allocator));
+
+            Assert.Equal(0, allocator.Rented);
+        }
+
+        [Fact]
+        public void ConcatenatingStructsReleasesSiblingsWhenAChildFails()
+        {
+            var type = new StructType(new[]
+            {
+                new Field("x", Int32Type.Default, true),
+                new Field("y", Int32Type.Default, true),
+            });
+            using Int32Array x1 = new 
Int32Array.Builder().Append(1).AppendNull().Build();
+            using Int32Array y1 = new 
Int32Array.Builder().Append(2).Append(3).Build();
+            using Int32Array x2 = new 
Int32Array.Builder().AppendNull().Append(4).Build();
+            var first = new ArrayData(type, 2, 0, 0, new[] { ArrowBuffer.Empty 
}, new[] { x1.Data, y1.Data });
+            var second = new ArrayData(type, 2, 0, 0, new[] { 
ArrowBuffer.Empty }, new[] { x2.Data, MalformedInt32(length: 2) });
+            var allocator = new TestMemoryAllocator();
+
+            Assert.ThrowsAny<Exception>(() => 
ArrayDataConcatenator.Concatenate(new[] { first, second }, allocator));
+
+            Assert.Equal(0, allocator.Rented);
+            // The inputs are untouched
+            Assert.Equal(new int?[] { 1, null }, x1.ToList(includeNulls: 
true));
+        }
+
+        [Fact]
+        public void 
ConcatenatingDictionariesReleasesTheCombinedDictionaryWhenIndicesFail()
+        {
+            var type = new DictionaryType(Int32Type.Default, 
StringType.Default, false);
+            using StringArray dictionary1 = new 
StringArray.Builder().Append("a").Append("b").Build();
+            using StringArray dictionary2 = new 
StringArray.Builder().Append("c").AppendNull().Build();
+            using Int32Array indices = new 
Int32Array.Builder().Append(0).AppendNull().Append(1).Build();
+            var valid = new ArrayData(type, 3, 1, 0, indices.Data.Buffers, 
null, dictionary1.Data);
+            // Its indices buffer is too short for its length, so shifting the 
indices fails
+            var malformed = new ArrayData(type, 3, 0, 0,
+                new[] { ArrowBuffer.Empty, new ArrowBuffer(new byte[4]) }, 
null, dictionary2.Data);
+            var allocator = new TestMemoryAllocator();
+
+            Assert.ThrowsAny<Exception>(() => 
ArrayDataConcatenator.Concatenate(new[] { valid, malformed }, allocator));
+
+            Assert.Equal(0, allocator.Rented);
+        }
+
+        [Fact]
+        public void SuccessfulConcatenationKeepsItsBuffers()
+        {
+            using Int32Array first = new 
Int32Array.Builder().Append(1).AppendNull().Build();
+            using Int32Array second = new 
Int32Array.Builder().Append(3).Build();
+            var allocator = new TestMemoryAllocator();
+
+            ArrayData result = ArrayDataConcatenator.Concatenate(new[] { 
first.Data, second.Data }, allocator);
+
+            Assert.True(allocator.Rented > 0);
+            Assert.Equal(new int?[] { 1, null, 3 }, new 
Int32Array(result).ToList(includeNulls: true));
+            result.Dispose();
+            Assert.Equal(0, allocator.Rented);
+        }
+
+        // Reading
+
+        public static TheoryData<int, bool> DecompressionFailures()
+        {
+            // The batch has three compressed buffers: the values of "a", then 
of the struct's
+            // children "x" and "y". Fail on each, so that earlier fields, 
earlier siblings and
+            // nothing at all have been read when it fails.
+            var data = new TheoryData<int, bool>();
+            foreach (int failOn in new[] { 1, 2, 3 })

Review Comment:
   Calls 1–3 do not reach either struct child: the writer emits a compressed 
header for each empty validity buffer, and the reader calls `Decompress` for 
those too. These calls therefore fail on `a`'s validity, `a`'s values, and 
`s`'s validity, leaving nested-field and sibling cleanup untested. Please 
include calls 5 and 7, which decompress `x` and `y` values respectively.



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