Copilot commented on code in PR #527: URL: https://github.com/apache/arrow-dotnet/pull/527#discussion_r4789483746
########## test/Apache.Arrow.Tests/DictionaryReferencePythonTests.cs: ########## @@ -0,0 +1,134 @@ +// 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; as + // before, only a finalizer can reclaim them, and TestMemoryAllocator's memory has none, + // so the count is exact. The dictionary built by combining the first dictionary with + // its delta has been released. + Assert.Equal(3, allocator.Rented); Review Comment: Same brittleness issue as the non-Python test: asserting an exact allocation count (`3`) is tightly coupled to current internal allocation behavior. Consider asserting that the allocation count decreases appropriately after disposing batches (or that only message bodies remain via a baseline/delta approach), so the test validates ownership semantics without breaking on benign allocator/internal changes. ########## test/Apache.Arrow.Tests/DictionaryReferenceTests.cs: ########## @@ -0,0 +1,276 @@ +// 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; as before, only a + // finalizer can reclaim it, and TestMemoryAllocator's memory has none, so the count is + // exact. Everything the dictionary itself allocated has been released. + Assert.Equal(1, allocator.Rented); Review Comment: The test asserts an exact allocator rent count (`Assert.Equal(1, allocator.Rented)`), which is brittle against internal implementation changes (e.g., additional small allocations, buffering strategy tweaks, or future IPC framing changes). To keep the intent while reducing fragility, assert on a delta relative to a baseline (before/after) or assert upper/lower bounds tied to owned dictionary allocations rather than a hard-coded absolute count. ########## 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 creates a new `List<IArrowArray>` for every delta concatenation. If this path is hot while reading streams with many dictionary deltas, this adds avoidable allocations. Consider using an array (e.g., `new IArrowArray[] { currentDictionary, deltaDictionary }`) or another overload that avoids allocating a `List`. ########## test/Apache.Arrow.Tests/DictionaryReferenceTests.cs: ########## @@ -0,0 +1,276 @@ +// 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; as before, only a + // finalizer can reclaim it, and TestMemoryAllocator's memory has none, so the count is + // exact. Everything the dictionary itself allocated has been released. + Assert.Equal(1, allocator.Rented); Review Comment: In `DictionariesAreReleasedWithTheReaderAndTheirBatches`, `reader` isn't wrapped in `using`/`try-finally`. If an exception occurs while reading batches, the reader may not be disposed, which can skew allocator assertions and leak resources during the test run. Consider wrapping `reader` in a `using` (and similarly ensuring `batches` are disposed in a `finally`) while preserving the intended disposal ordering. ########## test/Apache.Arrow.Tests/DictionaryReferenceTests.cs: ########## @@ -0,0 +1,276 @@ +// 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; as before, only a + // finalizer can reclaim it, and TestMemoryAllocator's memory has none, so the count is + // exact. 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); + + // The factory compresses with Deflate whatever codec type is requested; the type only + // has to be one that the writer marks as compressed. + 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 + { + public void Compress(ReadOnlyMemory<byte> source, Stream destination) + { + using var deflate = new DeflateStream(destination, CompressionLevel.Fastest, leaveOpen: true); + deflate.Write(source.ToArray(), 0, source.Length); + } + + public int Decompress(ReadOnlyMemory<byte> source, Memory<byte> destination) + { + using var deflate = new DeflateStream(new MemoryStream(source.ToArray()), CompressionMode.Decompress); + byte[] output = new byte[destination.Length]; + int total = 0; + int read; + while (total < output.Length && (read = deflate.Read(output, total, output.Length - total)) > 0) + { + total += read; + } Review Comment: `Decompress` will silently truncate output if the decompressed data is larger than `destination.Length` (because the loop stops when the destination buffer is full). Even though this is test-only, silent truncation can hide real codec/IPC issues and make failures harder to diagnose. Prefer throwing (e.g., `InvalidDataException`) when the stream still has data after filling the destination buffer, so tests fail loudly if sizing/metadata is wrong. -- 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]
