Skip to content

Commit

Permalink
apacheGH-32240: [C#] Support decompression of IPC format buffers (apa…
Browse files Browse the repository at this point in the history
…che#33603)

# Which issue does this PR close?

Closes apache#32240 / https://issues.apache.org/jira/browse/ARROW-16921

# What changes are included in this PR?

This PR implements decompression support for Arrow IPC format files and streams in the dotnet/C# library.

The main concern raised in the above Jira issue was that we don't want to add new NuGet package dependencies to support decompression formats that won't be needed by most users, so a default `CompressionProvider` implementation has been added that uses reflection to use the `ZstdNet` package for ZSTD decompression and `K4os.Compression.LZ4.Streams` and `CommunityToolkit.HighPerformance` for LZ4 Frame support if they are available. The `netstandard1.3` target has decompression support disabled due to some reflection functionality being missing, and neither `ZstdNet` or `K4os.Compression.LZ4.Streams` support `netstandard1.3`.

The `ArrowFileReader` and `ArrowStreamReader` constructors accept an `ICompressionProvider` parameter to allow users to provide their own compression provider if they want to use different dependencies.

### Alternatives to consider

An alternative approach that could be considered instead of reflection is to use these extra dependencies as build time dependencies but not make them dependencies of the NuGet package. I tested this out in adamreeve@4544afd and it seems to work reasonably well too but required bumping the version of `System.Runtime.CompilerServices.Unsafe` under the `netstandard2.0` and `netcoreapp3.1` targets. This reduces all the reflection boilerplate but seems pretty hacky as now Apache.Arrow.dll depends on these extra dlls and we rely on the dotnet runtime behaviour of not trying to load them until they're used. So I think the reflection approach is better.

Another alternative would be to move decompression support into a separate NuGet package (eg.  `Apache.Arrow.Compression`) that depends on `Apache.Arrow` and has an implementation of `ICompressionProvider` that users can pass in to the `ArrowFileReader` constructor, or maybe has a way to register itself with the `Apache.Arrow` package so it only needs to be configured once. That would seem cleaner to me but I'm not sure how much work it would be to set up a whole new package.

# Are these changes tested?

Yes, new unit tests have been added. Test files have been created with a Python script that is included in the PR due to only decompression support being added and not compression support.

# Are there any user-facing changes?

Yes, this implements a new feature but in a backwards compatible way.
* Closes: apache#32240

Authored-by: Adam Reeve <adreeve@gmail.com>
Signed-off-by: Will Jones <willjones127@gmail.com>
  • Loading branch information
adamreeve authored and sjperkins committed Feb 10, 2023
1 parent 20d13e1 commit f949e81
Show file tree
Hide file tree
Showing 22 changed files with 546 additions and 30 deletions.
19 changes: 17 additions & 2 deletions csharp/src/Apache.Arrow/Ipc/ArrowFileReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,18 +35,33 @@ public ArrowFileReader(Stream stream)
{
}

public ArrowFileReader(Stream stream, ICompressionCodecFactory compressionCodecFactory)
: this(stream, allocator: null, compressionCodecFactory, leaveOpen: false)
{
}

public ArrowFileReader(Stream stream, MemoryAllocator allocator)
: this(stream, allocator, leaveOpen: false)
{
}

public ArrowFileReader(Stream stream, MemoryAllocator allocator, ICompressionCodecFactory compressionCodecFactory)
: this(stream, allocator, compressionCodecFactory, leaveOpen: false)
{
}

public ArrowFileReader(Stream stream, bool leaveOpen)
: this(stream, allocator: null, leaveOpen)
: this(stream, allocator: null, compressionCodecFactory: null, leaveOpen)
{
}

public ArrowFileReader(Stream stream, MemoryAllocator allocator, bool leaveOpen)
: base(new ArrowFileReaderImplementation(stream, allocator, leaveOpen))
: this(stream, allocator, compressionCodecFactory: null, leaveOpen)
{
}

public ArrowFileReader(Stream stream, MemoryAllocator allocator, ICompressionCodecFactory compressionCodecFactory, bool leaveOpen)
: base(new ArrowFileReaderImplementation(stream, allocator, compressionCodecFactory, leaveOpen))
{
}

Expand Down
4 changes: 2 additions & 2 deletions csharp/src/Apache.Arrow/Ipc/ArrowFileReaderImplementation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ internal sealed class ArrowFileReaderImplementation : ArrowStreamReaderImplement

private ArrowFooter _footer;

public ArrowFileReaderImplementation(Stream stream, MemoryAllocator allocator, bool leaveOpen)
: base(stream, allocator, leaveOpen)
public ArrowFileReaderImplementation(Stream stream, MemoryAllocator allocator, ICompressionCodecFactory compressionCodecFactory, bool leaveOpen)
: base(stream, allocator, compressionCodecFactory, leaveOpen)
{
}

Expand Down
72 changes: 54 additions & 18 deletions csharp/src/Apache.Arrow/Ipc/ArrowReaderImplementation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Apache.Arrow.Flatbuf;
using Apache.Arrow.Types;
using Apache.Arrow.Memory;
using Type = System.Type;

namespace Apache.Arrow.Ipc
{
Expand All @@ -34,13 +36,15 @@ internal abstract class ArrowReaderImplementation : IDisposable
private protected DictionaryMemo _dictionaryMemo;
private protected DictionaryMemo DictionaryMemo => _dictionaryMemo ??= new DictionaryMemo();
private protected readonly MemoryAllocator _allocator;
private readonly ICompressionCodecFactory _compressionCodecFactory;

private protected ArrowReaderImplementation() : this(null)
private protected ArrowReaderImplementation() : this(null, null)
{ }

private protected ArrowReaderImplementation(MemoryAllocator allocator)
private protected ArrowReaderImplementation(MemoryAllocator allocator, ICompressionCodecFactory compressionCodecFactory)
{
_allocator = allocator ?? MemoryAllocator.Default.Value;
_compressionCodecFactory = compressionCodecFactory;
}

public void Dispose()
Expand Down Expand Up @@ -174,6 +178,7 @@ private List<IArrowArray> BuildArrays(
return arrays;
}

using var bufferCreator = GetBufferCreator(recordBatchMessage.Compression);
var recordBatchEnumerator = new RecordBatchEnumerator(in recordBatchMessage);
int schemaFieldIndex = 0;
do
Expand All @@ -182,23 +187,52 @@ private List<IArrowArray> BuildArrays(
Flatbuf.FieldNode fieldNode = recordBatchEnumerator.CurrentNode;

ArrayData arrayData = field.DataType.IsFixedPrimitive()
? LoadPrimitiveField(ref recordBatchEnumerator, field, in fieldNode, messageBuffer)
: LoadVariableField(ref recordBatchEnumerator, field, in fieldNode, messageBuffer);
? LoadPrimitiveField(ref recordBatchEnumerator, field, in fieldNode, messageBuffer, bufferCreator)
: LoadVariableField(ref recordBatchEnumerator, field, in fieldNode, messageBuffer, bufferCreator);

arrays.Add(ArrowArrayFactory.BuildArray(arrayData));
} while (recordBatchEnumerator.MoveNextNode());

return arrays;
}

private IBufferCreator GetBufferCreator(BodyCompression? compression)
{
if (!compression.HasValue)
{
return new NoOpBufferCreator();
}

var method = compression.Value.Method;
if (method != BodyCompressionMethod.BUFFER)
{
throw new NotImplementedException($"Compression method {method} is not supported");
}

var codec = compression.Value.Codec;
if (_compressionCodecFactory == null)
{
throw new Exception(
$"Body is compressed with codec {codec} but no {nameof(ICompressionCodecFactory)} has been configured to decompress buffers");
}
var decompressor = codec switch
{
Apache.Arrow.Flatbuf.CompressionType.LZ4_FRAME => _compressionCodecFactory.CreateCodec(CompressionCodecType.Lz4Frame),
Apache.Arrow.Flatbuf.CompressionType.ZSTD => _compressionCodecFactory.CreateCodec(CompressionCodecType.Zstd),
_ => throw new NotImplementedException($"Compression codec {codec} is not supported")
};
return new DecompressingBufferCreator(decompressor, _allocator);
}

private ArrayData LoadPrimitiveField(
ref RecordBatchEnumerator recordBatchEnumerator,
Field field,
in Flatbuf.FieldNode fieldNode,
ByteBuffer bodyData)
ByteBuffer bodyData,
IBufferCreator bufferCreator)
{

ArrowBuffer nullArrowBuffer = BuildArrowBuffer(bodyData, recordBatchEnumerator.CurrentBuffer);
ArrowBuffer nullArrowBuffer = BuildArrowBuffer(bodyData, recordBatchEnumerator.CurrentBuffer, bufferCreator);
if (!recordBatchEnumerator.MoveNextBuffer())
{
throw new Exception("Unable to move to the next buffer.");
Expand All @@ -224,13 +258,13 @@ private ArrayData LoadPrimitiveField(
}
else
{
ArrowBuffer valueArrowBuffer = BuildArrowBuffer(bodyData, recordBatchEnumerator.CurrentBuffer);
ArrowBuffer valueArrowBuffer = BuildArrowBuffer(bodyData, recordBatchEnumerator.CurrentBuffer, bufferCreator);
recordBatchEnumerator.MoveNextBuffer();

arrowBuff = new[] { nullArrowBuffer, valueArrowBuffer };
}

ArrayData[] children = GetChildren(ref recordBatchEnumerator, field, bodyData);
ArrayData[] children = GetChildren(ref recordBatchEnumerator, field, bodyData, bufferCreator);

IArrowArray dictionary = null;
if (field.DataType.TypeId == ArrowTypeId.Dictionary)
Expand All @@ -246,20 +280,21 @@ private ArrayData LoadVariableField(
ref RecordBatchEnumerator recordBatchEnumerator,
Field field,
in Flatbuf.FieldNode fieldNode,
ByteBuffer bodyData)
ByteBuffer bodyData,
IBufferCreator bufferCreator)
{

ArrowBuffer nullArrowBuffer = BuildArrowBuffer(bodyData, recordBatchEnumerator.CurrentBuffer);
ArrowBuffer nullArrowBuffer = BuildArrowBuffer(bodyData, recordBatchEnumerator.CurrentBuffer, bufferCreator);
if (!recordBatchEnumerator.MoveNextBuffer())
{
throw new Exception("Unable to move to the next buffer.");
}
ArrowBuffer offsetArrowBuffer = BuildArrowBuffer(bodyData, recordBatchEnumerator.CurrentBuffer);
ArrowBuffer offsetArrowBuffer = BuildArrowBuffer(bodyData, recordBatchEnumerator.CurrentBuffer, bufferCreator);
if (!recordBatchEnumerator.MoveNextBuffer())
{
throw new Exception("Unable to move to the next buffer.");
}
ArrowBuffer valueArrowBuffer = BuildArrowBuffer(bodyData, recordBatchEnumerator.CurrentBuffer);
ArrowBuffer valueArrowBuffer = BuildArrowBuffer(bodyData, recordBatchEnumerator.CurrentBuffer, bufferCreator);
recordBatchEnumerator.MoveNextBuffer();

int fieldLength = (int)fieldNode.Length;
Expand All @@ -276,7 +311,7 @@ private ArrayData LoadVariableField(
}

ArrowBuffer[] arrowBuff = new[] { nullArrowBuffer, offsetArrowBuffer, valueArrowBuffer };
ArrayData[] children = GetChildren(ref recordBatchEnumerator, field, bodyData);
ArrayData[] children = GetChildren(ref recordBatchEnumerator, field, bodyData, bufferCreator);

IArrowArray dictionary = null;
if (field.DataType.TypeId == ArrowTypeId.Dictionary)
Expand All @@ -291,7 +326,8 @@ private ArrayData LoadVariableField(
private ArrayData[] GetChildren(
ref RecordBatchEnumerator recordBatchEnumerator,
Field field,
ByteBuffer bodyData)
ByteBuffer bodyData,
IBufferCreator bufferCreator)
{
if (!(field.DataType is NestedType type)) return null;

Expand All @@ -304,15 +340,15 @@ private ArrayData[] GetChildren(

Field childField = type.Fields[index];
ArrayData child = childField.DataType.IsFixedPrimitive()
? LoadPrimitiveField(ref recordBatchEnumerator, childField, in childFieldNode, bodyData)
: LoadVariableField(ref recordBatchEnumerator, childField, in childFieldNode, bodyData);
? LoadPrimitiveField(ref recordBatchEnumerator, childField, in childFieldNode, bodyData, bufferCreator)
: LoadVariableField(ref recordBatchEnumerator, childField, in childFieldNode, bodyData, bufferCreator);

children[index] = child;
}
return children;
}

private ArrowBuffer BuildArrowBuffer(ByteBuffer bodyData, Flatbuf.Buffer buffer)
private ArrowBuffer BuildArrowBuffer(ByteBuffer bodyData, Flatbuf.Buffer buffer, IBufferCreator bufferCreator)
{
if (buffer.Length <= 0)
{
Expand All @@ -323,7 +359,7 @@ private ArrowBuffer BuildArrowBuffer(ByteBuffer bodyData, Flatbuf.Buffer buffer)
int length = (int)buffer.Length;

var data = bodyData.ToReadOnlyMemory(offset, length);
return new ArrowBuffer(data);
return bufferCreator.CreateBuffer(data);
}
}

Expand Down
23 changes: 19 additions & 4 deletions csharp/src/Apache.Arrow/Ipc/ArrowStreamReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,26 +31,41 @@ public class ArrowStreamReader : IArrowReader, IDisposable
public Schema Schema => _implementation.Schema;

public ArrowStreamReader(Stream stream)
: this(stream, allocator: null, leaveOpen: false)
: this(stream, allocator: null, compressionCodecFactory: null, leaveOpen: false)
{
}

public ArrowStreamReader(Stream stream, MemoryAllocator allocator)
: this(stream, allocator, leaveOpen: false)
: this(stream, allocator, compressionCodecFactory: null, leaveOpen: false)
{
}

public ArrowStreamReader(Stream stream, ICompressionCodecFactory compressionCodecFactory)
: this(stream, allocator: null, compressionCodecFactory, leaveOpen: false)
{
}

public ArrowStreamReader(Stream stream, bool leaveOpen)
: this(stream, allocator: null, leaveOpen)
: this(stream, allocator: null, compressionCodecFactory: null, leaveOpen)
{
}

public ArrowStreamReader(Stream stream, MemoryAllocator allocator, bool leaveOpen)
: this(stream, allocator, compressionCodecFactory: null, leaveOpen)
{
}

public ArrowStreamReader(Stream stream, ICompressionCodecFactory compressionCodecFactory, bool leaveOpen)
: this(stream, allocator: null, compressionCodecFactory, leaveOpen)
{
}

public ArrowStreamReader(Stream stream, MemoryAllocator allocator, ICompressionCodecFactory compressionCodecFactory, bool leaveOpen)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));

_implementation = new ArrowStreamReaderImplementation(stream, allocator, leaveOpen);
_implementation = new ArrowStreamReaderImplementation(stream, allocator, compressionCodecFactory, leaveOpen);
}

public ArrowStreamReader(ReadOnlyMemory<byte> buffer)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ internal class ArrowStreamReaderImplementation : ArrowReaderImplementation
public Stream BaseStream { get; }
private readonly bool _leaveOpen;

public ArrowStreamReaderImplementation(Stream stream, MemoryAllocator allocator, bool leaveOpen) : base(allocator)
public ArrowStreamReaderImplementation(Stream stream, MemoryAllocator allocator, ICompressionCodecFactory compressionCodecFactory, bool leaveOpen) : base(allocator, compressionCodecFactory)
{
BaseStream = stream;
_leaveOpen = leaveOpen;
Expand Down
23 changes: 23 additions & 0 deletions csharp/src/Apache.Arrow/Ipc/CompressionCodecType.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// 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.

namespace Apache.Arrow.Ipc
{
public enum CompressionCodecType
{
Lz4Frame,
Zstd,
}
}
69 changes: 69 additions & 0 deletions csharp/src/Apache.Arrow/Ipc/DecompressingBufferCreator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// 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.Buffers.Binary;
using Apache.Arrow.Memory;

namespace Apache.Arrow.Ipc
{
/// <summary>
/// Creates Arrow buffers from compressed data
/// </summary>
internal sealed class DecompressingBufferCreator : IBufferCreator
{
private readonly ICompressionCodec _compressionCodec;
private readonly MemoryAllocator _allocator;

public DecompressingBufferCreator(ICompressionCodec compressionCodec, MemoryAllocator allocator)
{
_compressionCodec = compressionCodec;
_allocator = allocator;
}

public ArrowBuffer CreateBuffer(ReadOnlyMemory<byte> source)
{
// See the BodyCompressionMethod enum in format/Message.fbs
// for documentation on the Buffer compression method used here.

if (source.Length < 8)
{
throw new Exception($"Invalid compressed data buffer size ({source.Length}), expected at least 8 bytes");
}

// First 8 bytes give the uncompressed data length
var uncompressedLength = BinaryPrimitives.ReadInt64LittleEndian(source.Span.Slice(0, 8));
if (uncompressedLength == -1)
{
// The buffer is not actually compressed
return new ArrowBuffer(source.Slice(8));
}

var outputData = _allocator.Allocate(Convert.ToInt32(uncompressedLength));
var decompressedLength = _compressionCodec.Decompress(source.Slice(8), outputData.Memory);
if (decompressedLength != uncompressedLength)
{
throw new Exception($"Expected to decompress {uncompressedLength} bytes, but got {decompressedLength} bytes");
}

return new ArrowBuffer(outputData);
}

public void Dispose()
{
_compressionCodec.Dispose();
}
}
}
Loading

0 comments on commit f949e81

Please sign in to comment.