-
Notifications
You must be signed in to change notification settings - Fork 22
perf: speed up MemoryStream IPC stream reads #340
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
CurtHagenlocher
merged 6 commits into
apache:main
from
InCerryGit:perf/stream-reader-managed-memory
Apr 28, 2026
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
49bae51
perf: speed up MemoryStream IPC stream reads
InCerryGit 585f9d6
test: benchmark MemoryStream IPC reader paths
InCerryGit 90bdc8b
Merge remote-tracking branch 'refs/remotes/apache/main' into perf/str…
InCerryGit 182ed6b
fix: support older compression test target frameworks
InCerryGit c160714
refactor: extract MemoryStream IPC reader
InCerryGit 5fe093d
fix: address MemoryStream reader review feedback
InCerryGit File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
214 changes: 214 additions & 0 deletions
214
src/Apache.Arrow/Ipc/ArrowMemoryStreamReaderImplementation.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,214 @@ | ||
| // 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; | ||
| using System.IO; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Apache.Arrow.Memory; | ||
|
|
||
| namespace Apache.Arrow.Ipc | ||
| { | ||
| /// <summary> | ||
| /// Reads Arrow IPC streams from a <see cref="MemoryStream"/> whose backing buffer is publicly visible. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// Message metadata can be read directly from the exposed stream buffer, but record batch bodies are | ||
| /// still copied into allocator-owned buffers to preserve <see cref="ArrowStreamReader"/> ownership semantics. | ||
| /// </remarks> | ||
| internal sealed class ArrowMemoryStreamReaderImplementation : ArrowStreamReaderImplementation | ||
| { | ||
| private readonly MemoryStream _stream; | ||
| private readonly Memory<byte> _streamMemory; | ||
|
|
||
| public ArrowMemoryStreamReaderImplementation( | ||
| MemoryStream stream, | ||
| MemoryAllocator allocator, | ||
| ICompressionCodecFactory compressionCodecFactory, | ||
| bool leaveOpen, | ||
| ExtensionTypeRegistry extensionRegistry) | ||
| : base(stream, allocator, compressionCodecFactory, leaveOpen, extensionRegistry) | ||
| { | ||
| _stream = stream; | ||
|
|
||
| if (!stream.TryGetBuffer(out ArraySegment<byte> streamBuffer)) | ||
| { | ||
| throw new InvalidOperationException("Expected MemoryStream to expose its backing buffer."); | ||
| } | ||
|
|
||
| _streamMemory = streamBuffer.Array.AsMemory(streamBuffer.Offset, streamBuffer.Count); | ||
| } | ||
|
|
||
| public override ValueTask<RecordBatch> ReadNextRecordBatchAsync(CancellationToken cancellationToken) | ||
| { | ||
| cancellationToken.ThrowIfCancellationRequested(); | ||
|
|
||
| try | ||
| { | ||
| return new ValueTask<RecordBatch>(ReadNextRecordBatch()); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| return new ValueTask<RecordBatch>(Task.FromException<RecordBatch>(ex)); | ||
| } | ||
| } | ||
|
|
||
| public override RecordBatch ReadNextRecordBatch() | ||
| { | ||
| ReadSchema(); | ||
|
|
||
| ReadResult result = default; | ||
| do | ||
| { | ||
| result = ReadMessageFromMemory(); | ||
| } while (result.Batch == null && result.MessageLength > 0); | ||
|
|
||
| return result.Batch; | ||
| } | ||
|
|
||
| public override ValueTask<Schema> ReadSchemaAsync(CancellationToken cancellationToken = default) | ||
| { | ||
| cancellationToken.ThrowIfCancellationRequested(); | ||
|
|
||
| if (HasReadSchema) | ||
| { | ||
| return new ValueTask<Schema>(_schema); | ||
| } | ||
|
|
||
| try | ||
| { | ||
| ReadSchema(); | ||
| return new ValueTask<Schema>(_schema); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| return new ValueTask<Schema>(Task.FromException<Schema>(ex)); | ||
| } | ||
| } | ||
|
|
||
| public override void ReadSchema() | ||
| { | ||
| if (HasReadSchema) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| int schemaMessageLength = ReadMessageLengthFromMemory(throwOnFullRead: true, returnOnEmptyStream: true); | ||
| if (schemaMessageLength == 0) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| Memory<byte> schemaBuffer = ReadMemory(schemaMessageLength); | ||
| _schema = MessageSerializer.GetSchema(ReadMessage<Flatbuf.Schema>(CreateByteBuffer(schemaBuffer)), ref _dictionaryMemo, _extensionRegistry); | ||
| } | ||
|
|
||
| private ReadResult ReadMessageFromMemory() | ||
| { | ||
| int messageLength = ReadMessageLengthFromMemory(throwOnFullRead: false, returnOnEmptyStream: false); | ||
| if (messageLength == 0) | ||
| { | ||
| return default; | ||
| } | ||
|
|
||
| Memory<byte> messageBuffer = ReadMemory(messageLength); | ||
| Flatbuf.Message message = Flatbuf.Message.GetRootAsMessage(CreateByteBuffer(messageBuffer)); | ||
|
|
||
| if (message.BodyLength > int.MaxValue) | ||
| { | ||
| throw new OverflowException( | ||
| $"Arrow IPC message body length ({message.BodyLength}) is larger than " + | ||
| $"the maximum supported message size ({int.MaxValue})"); | ||
| } | ||
|
|
||
| int bodyLength = (int)message.BodyLength; | ||
| Memory<byte> sourceBodyBuffer = ReadMemory(bodyLength); | ||
| IMemoryOwner<byte> bodyBufferOwner = AllocateMessageBodyBuffer(bodyLength); | ||
| Memory<byte> bodyBuffer = bodyBufferOwner.Memory.Slice(0, bodyLength); | ||
| sourceBodyBuffer.CopyTo(bodyBuffer); | ||
| Google.FlatBuffers.ByteBuffer bodybb = CreateByteBuffer(bodyBuffer); | ||
|
|
||
| // Keep stream-reader ownership semantics: batches outlive the source MemoryStream buffer. | ||
| return new ReadResult(messageLength, CreateArrowObjectFromMessage(message, bodybb, bodyBufferOwner)); | ||
| } | ||
|
|
||
| private int ReadMessageLengthFromMemory(bool throwOnFullRead, bool returnOnEmptyStream) | ||
| { | ||
| if (_stream.Position == _stream.Length && returnOnEmptyStream) | ||
| { | ||
| return 0; | ||
| } | ||
|
|
||
| if (!TryReadInt32(throwOnFullRead, out int messageLength)) | ||
| { | ||
| return 0; | ||
| } | ||
|
|
||
| if (messageLength == MessageSerializer.IpcContinuationToken && | ||
| !TryReadInt32(throwOnFullRead, out messageLength)) | ||
| { | ||
| return 0; | ||
| } | ||
|
|
||
| return messageLength; | ||
| } | ||
|
|
||
| private bool TryReadInt32(bool throwOnFullRead, out int value) | ||
| { | ||
| value = 0; | ||
|
|
||
| if (!TryReadMemory(sizeof(int), throwOnFullRead, out Memory<byte> buffer)) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| value = BitUtility.ReadInt32(buffer); | ||
| return true; | ||
| } | ||
|
|
||
| private bool TryReadMemory(int length, bool throwOnFullRead, out Memory<byte> buffer) | ||
| { | ||
| buffer = default; | ||
|
|
||
| long remainingLength = _stream.Length - _stream.Position; | ||
| if (remainingLength < length) | ||
| { | ||
| if (throwOnFullRead) | ||
| { | ||
| throw new InvalidOperationException("Unexpectedly reached the end of the stream before a full buffer was read."); | ||
| } | ||
|
|
||
| _stream.Position = _stream.Length; | ||
| return false; | ||
| } | ||
|
|
||
| buffer = ReadMemory(length); | ||
| return true; | ||
| } | ||
|
|
||
| private Memory<byte> ReadMemory(int length) | ||
| { | ||
| if (length == 0) | ||
| { | ||
| return Memory<byte>.Empty; | ||
| } | ||
|
|
||
| Memory<byte> buffer = _streamMemory.Slice(checked((int)_stream.Position), length); | ||
| _stream.Position += length; | ||
| return buffer; | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.