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


##########
test/Apache.Arrow.Tests/DictionaryReferencePythonTests.cs:
##########
@@ -0,0 +1,133 @@
+// 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.Collections.Generic;
+using System.IO;
+using System.Linq;
+using Apache.Arrow.Ipc;
+using Apache.Arrow.Memory;
+using Python.Runtime;
+using Xunit;
+
+namespace Apache.Arrow.Tests
+{
+    /// <summary>
+    /// Reads streams in which pyarrow extends a dictionary with a delta and 
then replaces it, which
+    /// <see cref="ArrowStreamWriter"/> can't write.
+    /// </summary>
+    [Collection("PythonNet")]
+    public class DictionaryReferencePythonTests
+    {
+        public DictionaryReferencePythonTests(PythonNetFixture pythonNet)
+        {
+            pythonNet.EnsureInitialized();
+        }
+
+        [SkippableFact]
+        public void BatchesKeepTheirDictionariesThroughDeltasAndReplacements()
+        {
+            byte[] data = WriteStream();
+            using var allocator = new PoisonMemoryAllocator();
+
+            List<RecordBatch> batches = ReadAll(data, allocator);
+
+            // The reader has combined the first dictionary with a delta, then 
replaced the result
+            // and been disposed; each batch still has the dictionary it was 
read with.
+            Assert.Equal(3, batches.Count);
+            AssertBatch(batches[0], new[] { "a", "b" }, new[] { "a", "b", "a" 
});
+            AssertBatch(batches[1], new[] { "a", "b", "c" }, new[] { "c", "b", 
"a" });
+            AssertBatch(batches[2], new[] { "x", "y" }, new[] { "y", "x" });
+
+            foreach (RecordBatch batch in batches)
+            {
+                batch.Dispose();
+            }
+        }
+
+        [SkippableFact]
+        public void CombinedAndReplacedDictionariesAreReleased()
+        {
+            byte[] data = WriteStream();
+            var allocator = new TestMemoryAllocator();
+
+            foreach (RecordBatch batch in ReadAll(data, allocator))
+            {
+                batch.Dispose();
+            }
+
+            // What remains are the bodies of the three dictionary messages, 
which nothing owns:
+            // they are reclaimed by finalization, as before. The dictionary 
built by combining
+            // the first dictionary with its delta has been released.
+            Assert.Equal(3, allocator.Rented);

Review Comment:
   This assertion has the same flakiness risk as the non-Python test: it 
assumes the unowned dictionary message bodies have *not* been reclaimed by 
finalization yet. Depending on GC timing, `allocator.Rented` could be less than 
3 when this runs. Consider asserting an upper bound (<= 3) and/or forcing GC + 
waiting for finalizers before asserting the eventual steady state (likely 0).



##########
src/Apache.Arrow/Ipc/DictionaryMemo.cs:
##########
@@ -107,11 +107,48 @@ public void AddOrReplaceDictionary(long id, IArrowArray 
dictionary)
             _idToDictionary[id] = dictionary;
         }
 
-        public void AddDeltaDictionary(long id, IArrowArray deltaDictionary, 
MemoryAllocator allocator = default)
+        /// <summary>
+        /// Adds or replaces a dictionary the memo owns, releasing the one it 
replaces. Readers own
+        /// their dictionaries; each record batch holds its own reference.
+        /// </summary>
+        public void ReplaceOwnedDictionary(long id, IArrowArray dictionary)
         {
-            IArrowArray currentDictionary = _idToDictionary[id];
-            IArrowArray dictionary = ArrowArrayConcatenator.Concatenate(new 
List<IArrowArray> { currentDictionary, deltaDictionary }, allocator);
-            AddOrReplaceDictionary(id, dictionary);
+            _idToDictionary.TryGetValue(id, out IArrowArray previous);
+            _idToDictionary[id] = dictionary;
+            if (!ReferenceEquals(previous, dictionary))
+            {
+                previous?.Dispose();
+            }
+        }
+
+        /// <summary>
+        /// Appends a delta to a dictionary the memo owns, releasing both the 
delta and the
+        /// dictionary it replaces.
+        /// </summary>
+        public void AddOwnedDeltaDictionary(long id, IArrowArray 
deltaDictionary, MemoryAllocator allocator = default)
+        {
+            try
+            {
+                IArrowArray currentDictionary = _idToDictionary[id];
+                IArrowArray dictionary = 
ArrowArrayConcatenator.Concatenate(new List<IArrowArray> { currentDictionary, 
deltaDictionary }, allocator);

Review Comment:
   This allocates a `List<IArrowArray>` on every delta append. If 
`ArrowArrayConcatenator.Concatenate` accepts an `IReadOnlyList<IArrowArray>` or 
similar, you can avoid the list allocation by passing a small fixed array (or 
another allocation-free wrapper) for the two inputs.



##########
test/Apache.Arrow.Tests/DictionaryReferenceTests.cs:
##########
@@ -0,0 +1,273 @@
+// 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 Apache.Arrow.Ipc;
+using Apache.Arrow.Memory;
+using Apache.Arrow.Types;
+using Xunit;
+
+namespace Apache.Arrow.Tests
+{
+    /// <summary>
+    /// A reader owns the dictionaries it reads, and each record batch holds 
its own reference to
+    /// the dictionaries it uses, so batches and the reader can be disposed in 
any order. A
+    /// dictionary's buffers are allocations owned by the reader when the 
stream is compressed.
+    /// </summary>
+    public class DictionaryReferenceTests
+    {
+        private const int Rows = 50;
+        private const int Batches = 3;
+
+        public static TheoryData<bool, bool> Formats() => new TheoryData<bool, 
bool>
+        {
+            // file format, compressed
+            { false, true },
+            { true, true },
+            { false, false },
+            { true, false },
+        };
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void BatchesCanBeDisposedAsTheyAreRead(bool file, bool 
compressed)
+        {
+            byte[] data = Write(file, compressed);
+            using var allocator = new PoisonMemoryAllocator();
+            using ArrowStreamReader reader = CreateReader(data, file, 
allocator);
+
+            for (int i = 0; i < Batches; i++)
+            {
+                using RecordBatch batch = reader.ReadNextRecordBatch();
+                AssertValues(batch);
+            }
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void BatchesCanBeDisposedOutOfOrder(bool file, bool compressed)
+        {
+            byte[] data = Write(file, compressed);
+            using var allocator = new PoisonMemoryAllocator();
+            using ArrowStreamReader reader = CreateReader(data, file, 
allocator);
+
+            using RecordBatch first = reader.ReadNextRecordBatch();
+            reader.ReadNextRecordBatch().Dispose();
+
+            AssertValues(first);
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void BatchesCanOutliveTheReader(bool file, bool compressed)
+        {
+            byte[] data = Write(file, compressed);
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch;
+            using (ArrowStreamReader reader = CreateReader(data, file, 
allocator))
+            {
+                batch = reader.ReadNextRecordBatch();
+            }
+
+            AssertValues(batch);
+            batch.Dispose();
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void DictionariesAreReleasedWithTheReaderAndTheirBatches(bool 
file, bool compressed)
+        {
+            byte[] data = Write(file, compressed);
+            var allocator = new TestMemoryAllocator();
+            ArrowStreamReader reader = CreateReader(data, file, allocator);
+            RecordBatch[] batches = Enumerable.Range(0, Batches).Select(_ => 
reader.ReadNextRecordBatch()).ToArray();
+
+            reader.Dispose();
+            foreach (RecordBatch batch in batches.Take(Batches - 1))
+            {
+                batch.Dispose();
+            }
+            Assert.True(allocator.Rented > 0);
+            AssertValues(batches[Batches - 1]);
+
+            batches[Batches - 1].Dispose();
+
+            // What remains is the dictionary message's body, which nothing 
owns: it is reclaimed by
+            // finalization, as before. Everything the dictionary itself 
allocated has been released.
+            Assert.Equal(1, allocator.Rented);

Review Comment:
   This assertion is potentially flaky because it relies on *finalization 
timing* (the comment explicitly says the remaining allocation is reclaimed by 
finalization). If the GC/finalizer runs during the test, `allocator.Rented` may 
already be `0`, causing intermittent failures. Prefer asserting a range (e.g., 
0..1) and/or explicitly forcing `GC.Collect()` + 
`GC.WaitForPendingFinalizers()` and then asserting `allocator.Rented == 0`.



##########
test/Apache.Arrow.Tests/DictionaryReferenceTests.cs:
##########
@@ -0,0 +1,273 @@
+// 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 Apache.Arrow.Ipc;
+using Apache.Arrow.Memory;
+using Apache.Arrow.Types;
+using Xunit;
+
+namespace Apache.Arrow.Tests
+{
+    /// <summary>
+    /// A reader owns the dictionaries it reads, and each record batch holds 
its own reference to
+    /// the dictionaries it uses, so batches and the reader can be disposed in 
any order. A
+    /// dictionary's buffers are allocations owned by the reader when the 
stream is compressed.
+    /// </summary>
+    public class DictionaryReferenceTests
+    {
+        private const int Rows = 50;
+        private const int Batches = 3;
+
+        public static TheoryData<bool, bool> Formats() => new TheoryData<bool, 
bool>
+        {
+            // file format, compressed
+            { false, true },
+            { true, true },
+            { false, false },
+            { true, false },
+        };
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void BatchesCanBeDisposedAsTheyAreRead(bool file, bool 
compressed)
+        {
+            byte[] data = Write(file, compressed);
+            using var allocator = new PoisonMemoryAllocator();
+            using ArrowStreamReader reader = CreateReader(data, file, 
allocator);
+
+            for (int i = 0; i < Batches; i++)
+            {
+                using RecordBatch batch = reader.ReadNextRecordBatch();
+                AssertValues(batch);
+            }
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void BatchesCanBeDisposedOutOfOrder(bool file, bool compressed)
+        {
+            byte[] data = Write(file, compressed);
+            using var allocator = new PoisonMemoryAllocator();
+            using ArrowStreamReader reader = CreateReader(data, file, 
allocator);
+
+            using RecordBatch first = reader.ReadNextRecordBatch();
+            reader.ReadNextRecordBatch().Dispose();
+
+            AssertValues(first);
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void BatchesCanOutliveTheReader(bool file, bool compressed)
+        {
+            byte[] data = Write(file, compressed);
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch;
+            using (ArrowStreamReader reader = CreateReader(data, file, 
allocator))
+            {
+                batch = reader.ReadNextRecordBatch();
+            }
+
+            AssertValues(batch);
+            batch.Dispose();
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void DictionariesAreReleasedWithTheReaderAndTheirBatches(bool 
file, bool compressed)
+        {
+            byte[] data = Write(file, compressed);
+            var allocator = new TestMemoryAllocator();
+            ArrowStreamReader reader = CreateReader(data, file, allocator);
+            RecordBatch[] batches = Enumerable.Range(0, Batches).Select(_ => 
reader.ReadNextRecordBatch()).ToArray();
+
+            reader.Dispose();
+            foreach (RecordBatch batch in batches.Take(Batches - 1))
+            {
+                batch.Dispose();
+            }
+            Assert.True(allocator.Rented > 0);
+            AssertValues(batches[Batches - 1]);
+
+            batches[Batches - 1].Dispose();
+
+            // What remains is the dictionary message's body, which nothing 
owns: it is reclaimed by
+            // finalization, as before. Everything the dictionary itself 
allocated has been released.
+            Assert.Equal(1, allocator.Rented);
+        }
+
+        // DictionaryMemo directly, for cases ArrowStreamWriter can't write. 
DictionaryReferencePythonTests
+        // reads deltas and replacements written by pyarrow.
+
+        [Fact]
+        public void ReplacingADictionaryReleasesTheMemosReference()
+        {
+            var allocator = new TestMemoryAllocator();
+            var memo = new DictionaryMemo();
+            StringArray first = Strings(allocator, "a", "b");
+            int firstAllocations = allocator.Rented;
+            memo.ReplaceOwnedDictionary(0, first);
+            ArrayData batchReference = first.Data.Retain();
+
+            StringArray second = Strings(allocator, "c");
+            int bothAllocations = allocator.Rented;
+            memo.ReplaceOwnedDictionary(0, second);
+
+            // The batch's reference keeps the replaced dictionary until it is 
released
+            Assert.Same(second, memo.GetDictionary(0));
+            Assert.Equal(bothAllocations, allocator.Rented);
+            Assert.Equal("b", new StringArray(batchReference).GetString(1));
+
+            batchReference.Dispose();
+            Assert.Equal(bothAllocations - firstAllocations, allocator.Rented);
+
+            memo.DisposeOwnedDictionaries();
+            Assert.Equal(0, allocator.Rented);
+        }
+
+        [Fact]
+        public void ADeltaIsCombinedAndBothPartsAreReleased()
+        {
+            var allocator = new TestMemoryAllocator();
+            var memo = new DictionaryMemo();
+            StringArray first = Strings(allocator, "a", "b");
+            memo.ReplaceOwnedDictionary(0, first);
+            ArrayData batchReference = first.Data.Retain();
+
+            memo.AddOwnedDeltaDictionary(0, Strings(allocator, "c"), 
allocator);
+
+            var combined = (StringArray)memo.GetDictionary(0);
+            Assert.Equal(new[] { "a", "b", "c" }, Enumerable.Range(0, 
combined.Length).Select(i => combined.GetString(i)));
+            Assert.Equal("b", new StringArray(batchReference).GetString(1));
+
+            batchReference.Dispose();
+            memo.DisposeOwnedDictionaries();
+            Assert.Equal(0, allocator.Rented);
+        }
+
+        [Fact]
+        public void ADeltaThatCantBeCombinedIsReleasedAndTheDictionaryKept()
+        {
+            var allocator = new TestMemoryAllocator();
+            var memo = new DictionaryMemo();
+            StringArray first = Strings(allocator, "a", "b");
+            int firstAllocations = allocator.Rented;
+            memo.ReplaceOwnedDictionary(0, first);
+            Int32Array delta = new 
Int32Array.Builder().Append(1).Build(allocator);
+
+            Assert.ThrowsAny<Exception>(() => memo.AddOwnedDeltaDictionary(0, 
delta, allocator));
+
+            Assert.Same(first, memo.GetDictionary(0));
+            Assert.Equal("b", first.GetString(1));
+            Assert.Equal(firstAllocations, allocator.Rented);
+
+            memo.DisposeOwnedDictionaries();
+            Assert.Equal(0, allocator.Rented);
+        }
+
+        private static StringArray Strings(MemoryAllocator allocator, params 
string[] values) =>
+            new StringArray.Builder().AppendRange(values).Build(allocator);
+
+        private static string Value(int i) => "dictionary value " + i;
+
+        private static void AssertValues(RecordBatch batch)
+        {
+            var column = (DictionaryArray)batch.Column(0);
+            var dictionary = (StringArray)column.Dictionary;
+            var indices = (Int32Array)column.Indices;
+            Assert.Equal(Rows, column.Length);
+            for (int i = 0; i < Rows; i++)
+            {
+                Assert.Equal(Value(i % 10), 
dictionary.GetString(indices.GetValue(i).Value));
+            }
+        }
+
+        private static byte[] Write(bool file, bool compressed)
+        {
+            var type = new DictionaryType(Int32Type.Default, 
StringType.Default, false);
+            var schema = new Schema.Builder().Field(f => 
f.Name("d").DataType(type).Nullable(false)).Build();
+            using StringArray dictionary = new StringArray.Builder()
+                .AppendRange(Enumerable.Range(0, 10).Select(Value)).Build();
+            using Int32Array indices = new Int32Array.Builder()
+                .AppendRange(Enumerable.Range(0, Rows).Select(i => i % 
10)).Build();
+            var batch = new RecordBatch(schema, new IArrowArray[] { new 
DictionaryArray(type, indices, dictionary) }, Rows);
+
+            var options = compressed
+                ? new IpcOptions { CompressionCodec = 
CompressionCodecType.Zstd, CompressionCodecFactory = new DeflateCodecFactory() }
+                : new IpcOptions();
+            var stream = new MemoryStream();
+            using (ArrowStreamWriter writer = file
+                ? new ArrowFileWriter(stream, schema, leaveOpen: true, options)
+                : new ArrowStreamWriter(stream, schema, leaveOpen: true, 
options))
+            {
+                for (int i = 0; i < Batches; i++)
+                {
+                    writer.WriteRecordBatch(batch);
+                }
+                writer.WriteEnd();
+            }
+            return stream.ToArray();
+        }
+
+        private static ArrowStreamReader CreateReader(byte[] data, bool file, 
MemoryAllocator allocator)
+        {
+            var stream = new MemoryStream(data);
+            return file
+                ? new ArrowFileReader(stream, allocator, new 
DeflateCodecFactory(), leaveOpen: false)
+                : new ArrowStreamReader(stream, allocator, new 
DeflateCodecFactory(), leaveOpen: false);
+        }
+
+        /// <summary>
+        /// Compresses with Deflate, whatever codec type is requested.
+        /// </summary>
+        private sealed class DeflateCodecFactory : ICompressionCodecFactory
+        {
+            public ICompressionCodec CreateCodec(CompressionCodecType 
compressionCodecType) => new DeflateCodec();
+
+            public ICompressionCodec CreateCodec(CompressionCodecType 
compressionCodecType, int? compressionLevel) => new DeflateCodec();
+
+            private sealed class DeflateCodec : ICompressionCodec

Review Comment:
   The test sets `CompressionCodecType.Zstd` but injects a 
`DeflateCodecFactory` that always uses Deflate. Even if intentional for 
testing, the naming is misleading and makes codec/type mismatches harder to 
reason about. Consider renaming `DeflateCodecFactory` (and the nested codec) to 
something explicitly test-oriented (e.g., `TestCompressionCodecFactory` / 
`FakeCodecFactory`) and/or add a short comment at the `IpcOptions` construction 
clarifying that the codec type is intentionally ignored by the factory.



##########
test/Apache.Arrow.Tests/DictionaryReferenceTests.cs:
##########
@@ -0,0 +1,273 @@
+// 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 Apache.Arrow.Ipc;
+using Apache.Arrow.Memory;
+using Apache.Arrow.Types;
+using Xunit;
+
+namespace Apache.Arrow.Tests
+{
+    /// <summary>
+    /// A reader owns the dictionaries it reads, and each record batch holds 
its own reference to
+    /// the dictionaries it uses, so batches and the reader can be disposed in 
any order. A
+    /// dictionary's buffers are allocations owned by the reader when the 
stream is compressed.
+    /// </summary>
+    public class DictionaryReferenceTests
+    {
+        private const int Rows = 50;
+        private const int Batches = 3;
+
+        public static TheoryData<bool, bool> Formats() => new TheoryData<bool, 
bool>
+        {
+            // file format, compressed
+            { false, true },
+            { true, true },
+            { false, false },
+            { true, false },
+        };
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void BatchesCanBeDisposedAsTheyAreRead(bool file, bool 
compressed)
+        {
+            byte[] data = Write(file, compressed);
+            using var allocator = new PoisonMemoryAllocator();
+            using ArrowStreamReader reader = CreateReader(data, file, 
allocator);
+
+            for (int i = 0; i < Batches; i++)
+            {
+                using RecordBatch batch = reader.ReadNextRecordBatch();
+                AssertValues(batch);
+            }
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void BatchesCanBeDisposedOutOfOrder(bool file, bool compressed)
+        {
+            byte[] data = Write(file, compressed);
+            using var allocator = new PoisonMemoryAllocator();
+            using ArrowStreamReader reader = CreateReader(data, file, 
allocator);
+
+            using RecordBatch first = reader.ReadNextRecordBatch();
+            reader.ReadNextRecordBatch().Dispose();
+
+            AssertValues(first);
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void BatchesCanOutliveTheReader(bool file, bool compressed)
+        {
+            byte[] data = Write(file, compressed);
+            using var allocator = new PoisonMemoryAllocator();
+            RecordBatch batch;
+            using (ArrowStreamReader reader = CreateReader(data, file, 
allocator))
+            {
+                batch = reader.ReadNextRecordBatch();
+            }
+
+            AssertValues(batch);
+            batch.Dispose();
+        }
+
+        [Theory]
+        [MemberData(nameof(Formats))]
+        public void DictionariesAreReleasedWithTheReaderAndTheirBatches(bool 
file, bool compressed)
+        {
+            byte[] data = Write(file, compressed);
+            var allocator = new TestMemoryAllocator();
+            ArrowStreamReader reader = CreateReader(data, file, allocator);
+            RecordBatch[] batches = Enumerable.Range(0, Batches).Select(_ => 
reader.ReadNextRecordBatch()).ToArray();
+
+            reader.Dispose();
+            foreach (RecordBatch batch in batches.Take(Batches - 1))
+            {
+                batch.Dispose();
+            }
+            Assert.True(allocator.Rented > 0);
+            AssertValues(batches[Batches - 1]);
+
+            batches[Batches - 1].Dispose();
+
+            // What remains is the dictionary message's body, which nothing 
owns: it is reclaimed by
+            // finalization, as before. Everything the dictionary itself 
allocated has been released.
+            Assert.Equal(1, allocator.Rented);
+        }
+
+        // DictionaryMemo directly, for cases ArrowStreamWriter can't write. 
DictionaryReferencePythonTests
+        // reads deltas and replacements written by pyarrow.
+
+        [Fact]
+        public void ReplacingADictionaryReleasesTheMemosReference()
+        {
+            var allocator = new TestMemoryAllocator();
+            var memo = new DictionaryMemo();
+            StringArray first = Strings(allocator, "a", "b");
+            int firstAllocations = allocator.Rented;
+            memo.ReplaceOwnedDictionary(0, first);
+            ArrayData batchReference = first.Data.Retain();
+
+            StringArray second = Strings(allocator, "c");
+            int bothAllocations = allocator.Rented;
+            memo.ReplaceOwnedDictionary(0, second);
+
+            // The batch's reference keeps the replaced dictionary until it is 
released
+            Assert.Same(second, memo.GetDictionary(0));
+            Assert.Equal(bothAllocations, allocator.Rented);
+            Assert.Equal("b", new StringArray(batchReference).GetString(1));
+
+            batchReference.Dispose();
+            Assert.Equal(bothAllocations - firstAllocations, allocator.Rented);
+
+            memo.DisposeOwnedDictionaries();
+            Assert.Equal(0, allocator.Rented);
+        }
+
+        [Fact]
+        public void ADeltaIsCombinedAndBothPartsAreReleased()
+        {
+            var allocator = new TestMemoryAllocator();
+            var memo = new DictionaryMemo();
+            StringArray first = Strings(allocator, "a", "b");
+            memo.ReplaceOwnedDictionary(0, first);
+            ArrayData batchReference = first.Data.Retain();
+
+            memo.AddOwnedDeltaDictionary(0, Strings(allocator, "c"), 
allocator);
+
+            var combined = (StringArray)memo.GetDictionary(0);
+            Assert.Equal(new[] { "a", "b", "c" }, Enumerable.Range(0, 
combined.Length).Select(i => combined.GetString(i)));
+            Assert.Equal("b", new StringArray(batchReference).GetString(1));
+
+            batchReference.Dispose();
+            memo.DisposeOwnedDictionaries();
+            Assert.Equal(0, allocator.Rented);
+        }
+
+        [Fact]
+        public void ADeltaThatCantBeCombinedIsReleasedAndTheDictionaryKept()
+        {
+            var allocator = new TestMemoryAllocator();
+            var memo = new DictionaryMemo();
+            StringArray first = Strings(allocator, "a", "b");
+            int firstAllocations = allocator.Rented;
+            memo.ReplaceOwnedDictionary(0, first);
+            Int32Array delta = new 
Int32Array.Builder().Append(1).Build(allocator);
+
+            Assert.ThrowsAny<Exception>(() => memo.AddOwnedDeltaDictionary(0, 
delta, allocator));
+
+            Assert.Same(first, memo.GetDictionary(0));
+            Assert.Equal("b", first.GetString(1));
+            Assert.Equal(firstAllocations, allocator.Rented);
+
+            memo.DisposeOwnedDictionaries();
+            Assert.Equal(0, allocator.Rented);
+        }
+
+        private static StringArray Strings(MemoryAllocator allocator, params 
string[] values) =>
+            new StringArray.Builder().AppendRange(values).Build(allocator);
+
+        private static string Value(int i) => "dictionary value " + i;
+
+        private static void AssertValues(RecordBatch batch)
+        {
+            var column = (DictionaryArray)batch.Column(0);
+            var dictionary = (StringArray)column.Dictionary;
+            var indices = (Int32Array)column.Indices;
+            Assert.Equal(Rows, column.Length);
+            for (int i = 0; i < Rows; i++)
+            {
+                Assert.Equal(Value(i % 10), 
dictionary.GetString(indices.GetValue(i).Value));
+            }
+        }
+
+        private static byte[] Write(bool file, bool compressed)
+        {
+            var type = new DictionaryType(Int32Type.Default, 
StringType.Default, false);
+            var schema = new Schema.Builder().Field(f => 
f.Name("d").DataType(type).Nullable(false)).Build();
+            using StringArray dictionary = new StringArray.Builder()
+                .AppendRange(Enumerable.Range(0, 10).Select(Value)).Build();
+            using Int32Array indices = new Int32Array.Builder()
+                .AppendRange(Enumerable.Range(0, Rows).Select(i => i % 
10)).Build();
+            var batch = new RecordBatch(schema, new IArrowArray[] { new 
DictionaryArray(type, indices, dictionary) }, Rows);
+
+            var options = compressed
+                ? new IpcOptions { CompressionCodec = 
CompressionCodecType.Zstd, CompressionCodecFactory = new DeflateCodecFactory() }
+                : new IpcOptions();

Review Comment:
   The test sets `CompressionCodecType.Zstd` but injects a 
`DeflateCodecFactory` that always uses Deflate. Even if intentional for 
testing, the naming is misleading and makes codec/type mismatches harder to 
reason about. Consider renaming `DeflateCodecFactory` (and the nested codec) to 
something explicitly test-oriented (e.g., `TestCompressionCodecFactory` / 
`FakeCodecFactory`) and/or add a short comment at the `IpcOptions` construction 
clarifying that the codec type is intentionally ignored by the factory.



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