CurtHagenlocher commented on code in PR #503: URL: https://github.com/apache/arrow-dotnet/pull/503#discussion_r4578691764
########## src/Apache.Arrow/C/CArrowAsyncDeviceStreamProducer.cs: ########## @@ -0,0 +1,618 @@ +// 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.Diagnostics.CodeAnalysis; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using Apache.Arrow.Ipc; + +namespace Apache.Arrow.C +{ + /// <summary> + /// Produces data from an <see cref="IArrowArrayStream"/> by pushing it through + /// an <see cref="CArrowAsyncDeviceStreamHandler"/>. + /// </summary> + [Experimental("ArrowAsyncDeviceStreamApi")] + public static class CArrowAsyncDeviceStreamProducer + { + private const int EINVAL = 22; + private const int EOTHER = 131; + +#if NET5_0_OR_GREATER + private static unsafe delegate* unmanaged<CArrowAsyncProducer*, long, void> RequestPtr => &OnRequest; + private static unsafe delegate* unmanaged<CArrowAsyncProducer*, void> CancelPtr => &OnCancel; + private static unsafe delegate* unmanaged<CArrowAsyncTask*, CArrowDeviceArray*, int> ExtractDataPtr => &ExtractData; +#else + internal unsafe delegate void RequestDelegate(CArrowAsyncProducer* producer, long n); + private static unsafe readonly NativeDelegate<RequestDelegate> s_request = new NativeDelegate<RequestDelegate>(OnRequest); + private static unsafe IntPtr RequestPtr => s_request.Pointer; + internal unsafe delegate void CancelDelegate(CArrowAsyncProducer* producer); + private static unsafe readonly NativeDelegate<CancelDelegate> s_cancel = new NativeDelegate<CancelDelegate>(OnCancel); + private static unsafe IntPtr CancelPtr => s_cancel.Pointer; + internal unsafe delegate int ExtractDataDelegate(CArrowAsyncTask* task, CArrowDeviceArray* deviceArray); + private static unsafe readonly NativeDelegate<ExtractDataDelegate> s_extractData = new NativeDelegate<ExtractDataDelegate>(ExtractData); + private static unsafe IntPtr ExtractDataPtr => s_extractData.Pointer; +#endif + + /// <summary> + /// Produce data from an <see cref="IArrowArrayStream"/> by pushing it through + /// the provided handler. The producer populates the handler's producer field + /// and calls on_schema before this method returns; batches are then delivered + /// asynchronously as the consumer requests them. + /// </summary> + /// <remarks> + /// Handler callbacks are never invoked concurrently, and the handler's release + /// callback is called exactly once, as the last call on the handler. The + /// source stream is disposed after release. As with the C stream exporters, + /// the producer takes ownership of each batch the source returns and disposes + /// it once the consumer has released (or declined) the exported data. + /// </remarks> + /// <param name="arrayStream">The source stream to produce from.</param> + /// <param name="handler">The consumer-allocated handler to push data through.</param> + public static unsafe void Produce(IArrowArrayStream arrayStream, CArrowAsyncDeviceStreamHandler* handler) + { + if (arrayStream == null) + { + throw new ArgumentNullException(nameof(arrayStream)); + } + if (handler == null) + { + throw new ArgumentNullException(nameof(handler)); + } + + var state = new ProducerState(arrayStream, handler); + state.Start(); + } + +#if NET5_0_OR_GREATER + [UnmanagedCallersOnly] +#endif + private unsafe static void OnRequest(CArrowAsyncProducer* producer, long n) + { + // Exceptions must not escape an unmanaged callback. request() has no + // return value; errors it detects are reported later via on_error. + try + { + var state = ProducerState.FromPointer(producer->private_data); + state.Request(n); + } + catch (Exception) + { + } + } + +#if NET5_0_OR_GREATER + [UnmanagedCallersOnly] +#endif + private unsafe static void OnCancel(CArrowAsyncProducer* producer) + { + // Exceptions must not escape an unmanaged callback. + try + { + var state = ProducerState.FromPointer(producer->private_data); + state.Cancel(); + } + catch (Exception) + { + } + } + +#if NET5_0_OR_GREATER + [UnmanagedCallersOnly] +#endif + private unsafe static int ExtractData(CArrowAsyncTask* task, CArrowDeviceArray* deviceArray) + { + // Consumers may extract after the producer has finished and released + // the handler (arrow-go does), so this must only depend on the task. + TaskState taskState = null; + try + { + // extract_data is called exactly once per task, so the task's + // GCHandle is always freed here. Clearing private_data makes an + // erroneous second call fail cleanly instead of touching a freed handle. + GCHandle gch = GCHandle.FromIntPtr((IntPtr)task->private_data); + task->private_data = null; + try + { + taskState = (TaskState)gch.Target; + if (deviceArray != null) + { + // Like the C stream exporters, take over the source stream's + // reference: the exported array disposes the batch when released + // (or right away if the export fails). + CArrowDeviceArrayExporter.ExportRecordBatch(taskState.Batch, deviceArray, transferOwnership: true); + } + else + { + // The consumer doesn't want the data. + taskState.Batch.Dispose(); + } + return 0; + } + finally + { + gch.Free(); + } + } + catch (Exception ex) + { + // The spec says a failed extract_data is followed by on_error. + taskState?.Producer.ReportError(EOTHER, ex.Message); + return EOTHER; + } + } + + /// <summary> + /// What the produce loop should do next. + /// </summary> + private enum Step + { + /// <summary>No demand: the loop exits until the next request().</summary> + Idle, + /// <summary>Read a batch from the source and deliver it.</summary> + Produce, + /// <summary>Report a pending error, then release.</summary> + Error, + /// <summary>Cancelled: release without further callbacks.</summary> + Release, + } + + /// <summary> + /// State for one produced stream. + /// </summary> + /// <remarks> + /// All handler callbacks after on_schema are made from a single produce loop, + /// and at most one loop runs at a time (<see cref="_running"/>), so callbacks + /// are never concurrent. request() and cancel() only update state under + /// <see cref="_gate"/> and start the loop if it isn't running; they never call + /// back into the handler themselves, as the spec requires. + /// </remarks> + private sealed unsafe class ProducerState + { + private readonly IArrowArrayStream _arrayStream; + private readonly CArrowAsyncDeviceStreamHandler* _handler; + private CArrowAsyncProducer* _producer; + + private readonly object _gate = new object(); + private long _demand; + private bool _schemaDelivered; + private bool _running; + private bool _cancelled; + private bool _finished; + private bool _hasPendingError; + private int _pendingErrorCode; + private string _pendingErrorMessage; + + public ProducerState(IArrowArrayStream arrayStream, CArrowAsyncDeviceStreamHandler* handler) + { + _arrayStream = arrayStream; + _handler = handler; + } + + public IArrowArrayStream ArrayStream => _arrayStream; + + public static ProducerState FromPointer(void* ptr) + { + GCHandle gch = GCHandle.FromIntPtr((IntPtr)ptr); + return (ProducerState)gch.Target; + } + + public void Start() + { + // Allocate and populate the producer struct + _producer = CArrowAsyncProducer.Create(); + _producer->device_type = ArrowDeviceType.Cpu; + _producer->request = RequestPtr; + _producer->cancel = CancelPtr; + _producer->additional_metadata = null; + + GCHandle gch = GCHandle.Alloc(this); + _producer->private_data = (void*)GCHandle.ToIntPtr(gch); + + // Set the producer on the handler before calling on_schema + _handler->producer = _producer; + + // Deliver the schema. If it can't be exported, the consumer still + // has to hear about it: on_error followed by release. + CArrowSchema cSchema = new CArrowSchema(); + try + { + CArrowSchemaExporter.ExportSchema(_arrayStream.Schema, &cSchema); + } + catch (Exception ex) + { + FailWithError(EOTHER, ex.Message); + return; + } + + // The consumer may call request() or cancel() from within on_schema. + // That only records state: the loop doesn't start until on_schema + // has returned, so on_next_task can't overlap it. +#if NET5_0_OR_GREATER + int errno = _handler->on_schema(_handler, &cSchema); +#else + int errno = NativeDelegate.GetDelegateForFunctionPointer<CArrowAsyncDeviceStreamConsumer.OnSchemaDelegate>(_handler->on_schema)(_handler, &cSchema); +#endif + + // A consumer that fails may not have taken ownership of the schema. + if (cSchema.release != default) + { +#if NET5_0_OR_GREATER + cSchema.release(&cSchema); +#else + NativeDelegate.GetDelegateForFunctionPointer<CArrowSchemaExporter.ReleaseArrowSchema>(cSchema.release)(&cSchema); +#endif + } + + if (errno != 0) + { + // Per the spec: no on_error after a failed on_schema, just release. + Finish(); + return; + } + + bool startLoop; + lock (_gate) + { + _schemaDelivered = true; + startLoop = TryClaimLoopLocked(); + } + if (startLoop) + { + StartLoop(); + } + } + + public void Request(long n) + { + bool startLoop; + lock (_gate) + { + // After cancel, request must be a no-op. + if (_cancelled || _finished) + { + return; + } + + if (n <= 0) + { + SetPendingErrorLocked(EINVAL, $"request() called with invalid n = {n}; n must be positive."); + } + else + { + _demand = n > long.MaxValue - _demand ? long.MaxValue : _demand + n; + } + + startLoop = TryClaimLoopLocked(); + } + if (startLoop) + { + StartLoop(); + } + } + + public void Cancel() + { + bool startLoop; + lock (_gate) + { + // cancel must be idempotent. + if (_cancelled || _finished) + { + return; + } + + _cancelled = true; + startLoop = TryClaimLoopLocked(); + } + if (startLoop) + { + StartLoop(); + } + } + + /// <summary> + /// Report an error to the consumer from outside the produce loop + /// (currently, a failed extract_data). Ignored once the stream is done. + /// </summary> + public void ReportError(int code, string message) + { + bool startLoop; + lock (_gate) + { + if (_finished) + { + return; + } + + SetPendingErrorLocked(code, message); + startLoop = TryClaimLoopLocked(); + } + if (startLoop) + { + StartLoop(); + } + } + + private void SetPendingErrorLocked(int code, string message) + { + if (!_hasPendingError) + { + _hasPendingError = true; + _pendingErrorCode = code; + _pendingErrorMessage = message; + } + } + + /// <summary> + /// Returns true if the caller should start the produce loop, in which case + /// <see cref="_running"/> has been set and the caller owns starting it. + /// </summary> + private bool TryClaimLoopLocked() + { + if (_running || _finished || !_schemaDelivered) + { + return false; + } + + if (_cancelled || _hasPendingError || _demand > 0) + { + _running = true; + return true; + } + + return false; + } + + private void StartLoop() + { + // A separate task keeps request() from ever calling back into the + // handler synchronously. + Task.Run(() => RunProduceLoopAsync(this)); + } + + /// <summary> + /// Decide the loop's next step. When there's nothing to do, this marks + /// the loop as stopped under the same lock that request() takes, so a + /// concurrent request() either is seen here or starts a new loop. + /// </summary> + public Step TakeNextStep(out int errorCode, out string errorMessage) + { + errorCode = 0; + errorMessage = null; + lock (_gate) + { + if (_hasPendingError) + { + errorCode = _pendingErrorCode; + errorMessage = _pendingErrorMessage; + return Step.Error; + } + + if (_cancelled) + { + return Step.Release; + } + + if (_demand == 0) + { + _running = false; + return Step.Idle; + } + + _demand--; + return Step.Produce; + } + } + + /// <summary> + /// Deliver a batch (or end of stream, if null) to the consumer. Returns + /// false if the stream is now finished. + /// Separated from the async loop because unsafe pointer operations + /// cannot appear in async methods. + /// </summary> + public bool DeliverBatch(RecordBatch batch) + { + if (batch == null) + { + SignalEndOfStream(); + Finish(); + return false; + } + + bool cancelled; + lock (_gate) + { + cancelled = _cancelled; + } + if (cancelled) + { + // Cancelled while reading: drop the batch and just release. + batch.Dispose(); + Finish(); + return false; + } + + var taskState = new TaskState(this, batch); + GCHandle taskGch = GCHandle.Alloc(taskState); + CArrowAsyncTask cTask = new CArrowAsyncTask(); + cTask.extract_data = ExtractDataPtr; + cTask.private_data = (void*)GCHandle.ToIntPtr(taskGch); + +#if NET5_0_OR_GREATER + int errno = _handler->on_next_task(_handler, &cTask, null); +#else + int errno = NativeDelegate.GetDelegateForFunctionPointer<CArrowAsyncDeviceStreamConsumer.OnNextTaskDelegate>(_handler->on_next_task)(_handler, &cTask, null); +#endif + if (errno != 0) + { + // Per the spec: no on_error after a failed on_next_task, just release. + // The task's GCHandle can't be freed safely here: the consumer may + // have extracted from a copy of the task, which already freed it. + Finish(); + return false; + } + + return true; + } + + public void FailWithError(int code, string message) + { + lock (_gate) + { + // Nothing may follow release. + if (_finished) + { + return; + } + } + + SignalError(code, message); + Finish(); + } + + private void SignalEndOfStream() + { +#if NET5_0_OR_GREATER + _handler->on_next_task(_handler, null, null); +#else + NativeDelegate.GetDelegateForFunctionPointer<CArrowAsyncDeviceStreamConsumer.OnNextTaskDelegate>(_handler->on_next_task)(_handler, null, null); +#endif + } + + private void SignalError(int code, string message) + { + byte* msgPtr = null; + try + { + if (message != null) + { + msgPtr = StringUtil.ToCStringUtf8(message); + } +#if NET5_0_OR_GREATER + _handler->on_error(_handler, code, msgPtr, null); +#else + NativeDelegate.GetDelegateForFunctionPointer<CArrowAsyncDeviceStreamConsumer.OnErrorDelegate>(_handler->on_error)(_handler, code, msgPtr, null); +#endif + } + finally + { + if (msgPtr != null) + { + Marshal.FreeHGlobal((IntPtr)msgPtr); + } + } + } + + /// <summary> + /// Release the handler and free the producer. Only called from Start or + /// the produce loop, never concurrently, and at most once. + /// </summary> + public void Finish() + { + lock (_gate) + { + if (_finished) + { + return; + } + _finished = true; + } + +#if NET5_0_OR_GREATER + _handler->release(_handler); +#else + NativeDelegate.GetDelegateForFunctionPointer<CArrowAsyncDeviceStreamConsumer.ReleaseHandlerDelegate>(_handler->release)(_handler); +#endif + + // The spec only requires the producer struct to stay valid until + // release is called, so it can be freed now. + GCHandle gch = GCHandle.FromIntPtr((IntPtr)_producer->private_data); + gch.Free(); + CArrowAsyncProducer.Free(_producer); + _producer = null; + + _arrayStream.Dispose(); + } + } + + /// <summary> + /// The produce loop, kept outside ProducerState so that it is not in an + /// unsafe context (await is not allowed in unsafe contexts). + /// </summary> + private static async Task RunProduceLoopAsync(ProducerState state) + { + try + { + while (true) + { + switch (state.TakeNextStep(out int errorCode, out string errorMessage)) + { + case Step.Idle: + return; + case Step.Error: + state.FailWithError(errorCode, errorMessage); + return; + case Step.Release: + state.Finish(); + return; + } + + RecordBatch batch; + try + { + batch = await state.ArrayStream.ReadNextRecordBatchAsync().ConfigureAwait(false); Review Comment: Fixed in 81be4ae. The produce loop now passes a producer-owned cancellation token to `ReadNextRecordBatchAsync`, and `cancel()` cancels it. The `Cancel()` call runs on the thread pool, because the read's continuation could otherwise run inline inside the consumer's `cancel()` call. A read that fails after cancellation just releases, with no `on_error`. The new `CancelInterruptsPendingSourceRead` test covers this, and it fails without the fix. ########## test/Apache.Arrow.Tests/CAsyncDeviceStreamGoInteropTests.cs: ########## @@ -0,0 +1,426 @@ +// 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. + +#if NET5_0_OR_GREATER + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using Apache.Arrow.C; +using Apache.Arrow.Ipc; +using Xunit; + +namespace Apache.Arrow.Tests +{ + /// <summary> + /// Interop tests for the C Async Device Stream Interface against arrow-go. + /// See test/arrow-go-interop for the Go side. + /// </summary> + [Experimental("ArrowAsyncDeviceStreamApi")] + public class CAsyncDeviceStreamGoInteropTests : IClassFixture<ArrowGoInteropFixture> + { + // Must match injectedErrorMessage in test/arrow-go-interop/main.go. + private const string GoInjectedErrorMessage = "arrow-go-interop: injected producer failure"; + + private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(30); + + private readonly ArrowGoInteropFixture _go; + + public CAsyncDeviceStreamGoInteropTests(ArrowGoInteropFixture go) + { + _go = go; + _go.EnsureAvailable(); + } + + // ---- arrow-go producer -> .NET consumer ---- + + [SkippableFact] + public async Task GoProducerToDotNetConsumer() + { + List<RecordBatch> batches = CreateBatches(3); + + await WithDotNetConsumer(async (received, produceWith) => + { + Task produce = produceWith(new BatchListStream(batches), -1); + + await AssertStreamEquals(batches, received); + await produce.WaitAsync(Timeout); + }); + } + + [SkippableFact] + public async Task GoProducerToDotNetConsumerEmptyStream() + { + Schema schema = CreateBatches(1)[0].Schema; + + await WithDotNetConsumer(async (received, produceWith) => + { + Task produce = produceWith(new BatchListStream(schema, new List<RecordBatch>()), -1); + + Assert.Null(await received.ReadNextRecordBatchAsync().AsTask().WaitAsync(Timeout)); + SchemaComparer.Compare(schema, received.Schema); + await produce.WaitAsync(Timeout); + }); + } + + [SkippableFact] + public async Task GoProducerErrorReachesDotNetConsumer() + { + List<RecordBatch> batches = CreateBatches(3); + + await WithDotNetConsumer(async (received, produceWith) => + { + Task produce = produceWith(new BatchListStream(batches), 1); + + RecordBatch first = await received.ReadNextRecordBatchAsync().AsTask().WaitAsync(Timeout); + Assert.NotNull(first); + ArrowReaderVerifier.CompareBatches(batches[0], first, strictCompare: false); + first.Dispose(); + + Exception readError = await Assert.ThrowsAnyAsync<Exception>( + () => received.ReadNextRecordBatchAsync().AsTask().WaitAsync(Timeout)); + Assert.Contains(GoInjectedErrorMessage, readError.Message); + + // arrow-go's producer reports the same error to its caller. + ArrowGoInteropException produceError = await Assert.ThrowsAsync<ArrowGoInteropException>( + () => produce.WaitAsync(Timeout)); + Assert.Contains(GoInjectedErrorMessage, produceError.Message); + }); + } + + [SkippableFact] + public async Task DotNetConsumerDisposeCancelsGoProducer() + { + RecordBatch batch = CreateBatches(1)[0]; + + await WithDotNetConsumer(async (received, produceWith) => + { + Task produce = produceWith(new EndlessStream(batch), -1); + + for (int i = 0; i < 5; i++) + { + RecordBatch result = await received.ReadNextRecordBatchAsync().AsTask().WaitAsync(Timeout); + Assert.NotNull(result); + result.Dispose(); + } + + // Disposing calls the producer's cancel; arrow-go must then stop, + // release the handler, and return without an error. + received.Dispose(); + await produce.WaitAsync(Timeout); + }); + } + + // ---- .NET producer -> arrow-go consumer ---- + + // arrow-go requests queueSize batches up front, then one per batch consumed, + // so small queue sizes exercise the producer's handling of repeated request() calls. + [SkippableTheory] + [InlineData(1)] + [InlineData(2)] + [InlineData(16)] + public async Task DotNetProducerToGoConsumer(int queueSize) + { + List<RecordBatch> batches = CreateBatches(8); + + await WithGoConsumer((ulong)queueSize, new BatchListStream(batches), async result => + { + await AssertStreamEquals(batches, result); + }); + } + + [SkippableFact] + public async Task GoConsumerCancelStopsDotNetProducer() + { + RecordBatch batch = CreateBatches(1)[0]; + + await WithGoConsumer(2, new EndlessStream(batch), async (result, consumer) => + { + for (int i = 0; i < 5; i++) + { + RecordBatch received = await result.ReadNextRecordBatchAsync().AsTask().WaitAsync(Timeout); + Assert.NotNull(received); + received.Dispose(); + } + + // arrow-go calls the producer's cancel; the .NET producer must then + // release the handler, which ends arrow-go's stream. Any batches + // already in flight may still arrive first. + consumer.Cancel(); + while (await result.ReadNextRecordBatchAsync().AsTask().WaitAsync(Timeout) is RecordBatch extra) + { + extra.Dispose(); + } + }); + } + + [SkippableFact] + public async Task DotNetProducerToGoConsumerEmptyStream() + { + Schema schema = CreateBatches(1)[0].Schema; + + await WithGoConsumer(4, new BatchListStream(schema, new List<RecordBatch>()), async result => + { + SchemaComparer.Compare(schema, result.Schema); + Assert.Null(await result.ReadNextRecordBatchAsync().AsTask().WaitAsync(Timeout)); + }); + } + + [SkippableFact] + public async Task DotNetProducerErrorReachesGoConsumer() + { + List<RecordBatch> batches = CreateBatches(3); + const string message = "dotnet source failure"; + + await WithGoConsumer(1, new BatchListStream(batches, failAfter: 1, failureMessage: message), async result => + { + RecordBatch first = await result.ReadNextRecordBatchAsync().AsTask().WaitAsync(Timeout); + Assert.NotNull(first); + ArrowReaderVerifier.CompareBatches(batches[0], first, strictCompare: false); + first.Dispose(); + + Exception readError = await Assert.ThrowsAnyAsync<Exception>( + () => result.ReadNextRecordBatchAsync().AsTask().WaitAsync(Timeout)); + Assert.Contains(message, readError.Message); + }); + } + + // ---- helpers ---- + + private delegate Task ProduceWith(IArrowArrayStream source, long failAfter); + + /// <summary> + /// Runs <paramref name="body"/> with a .NET consumer whose handler arrow-go + /// produces into. The consumer frees the handler itself when arrow-go + /// releases it. + /// </summary> + private async Task WithDotNetConsumer(Func<IArrowArrayStream, ProduceWith, Task> body) + { + IntPtr handlerPtr; + IArrowArrayStream received; + unsafe + { + received = CArrowAsyncDeviceStreamConsumer.CreateStream(out CArrowAsyncDeviceStreamHandler* handler); + handlerPtr = (IntPtr)handler; + } + + Task produce = null; + try + { + await body(received, (source, failAfter) => + { + unsafe + { + produce = _go.ProduceFromStreamAsync(source, (CArrowAsyncDeviceStreamHandler*)handlerPtr, failAfter); + } + return produce; + }); + } + finally + { + received.Dispose(); + + // Don't leave arrow-go's producer running into the next test. Tests + // that care about its outcome have already asserted on it. + if (produce != null) + { + try + { + await produce.WaitAsync(Timeout); + } + catch (Exception) + { + } + } + } + } + + /// <summary> + /// Runs <paramref name="body"/> with what arrow-go consumes when the .NET + /// producer produces <paramref name="source"/> into it. + /// </summary> + private Task WithGoConsumer(ulong queueSize, IArrowArrayStream source, Func<IArrowArrayStream, Task> body) + { + return WithGoConsumer(queueSize, source, (result, _) => body(result)); + } + + private async Task WithGoConsumer(ulong queueSize, IArrowArrayStream source, Func<IArrowArrayStream, ArrowGoInteropFixture.GoConsumer, Task> body) + { + IntPtr handlerPtr; + ArrowGoInteropFixture.GoConsumer consumer; + unsafe + { + CArrowAsyncDeviceStreamHandler* handler = CArrowAsyncDeviceStreamHandler.Create(); + handlerPtr = (IntPtr)handler; + consumer = _go.CreateConsumer(handler, queueSize); + } + + try + { + // arrow-go's on_schema blocks until someone is waiting for the stream. + Task<IArrowArrayStream> resultTask = consumer.ToStreamAsync(); + unsafe + { + CArrowAsyncDeviceStreamProducer.Produce(source, (CArrowAsyncDeviceStreamHandler*)handlerPtr); + } + + using (IArrowArrayStream result = await resultTask.WaitAsync(Timeout)) + { + await body(result, consumer); + } + } + finally + { + bool released = await WaitForHandlerReleaseAsync(handlerPtr); + consumer.Dispose(); Review Comment: Fixed in 81be4ae. `WithGoConsumer` still leaks the allocations on a timeout, but now asserts that release was seen afterwards. The assert sits after the `try`/`finally`, so it can't hide a failure from the test body. ########## test/Apache.Arrow.Tests/CAsyncDeviceStreamTests.cs: ########## @@ -0,0 +1,780 @@ +// 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.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; +using Apache.Arrow.C; +using Apache.Arrow.Ipc; +using Apache.Arrow.Types; +using Xunit; + +namespace Apache.Arrow.Tests +{ + [Experimental("ArrowAsyncDeviceStreamApi")] + public class CAsyncDeviceStreamTests + { + private RecordBatch CreateBatch(int startValue, int count) + { + var builder = new Int32Array.Builder(); + for (int i = 0; i < count; i++) + { + builder.Append(startValue + i); + } + + return new RecordBatch.Builder() + .Append("values", false, col => col.Int32(b => + { + for (int i = 0; i < count; i++) + { + b.Append(startValue + i); + } + })) + .Build(); + } + + [Fact] + public async Task RoundTripSingleBatch() + { + RecordBatch batch = CreateBatch(1, 5); + IArrowArrayStream source = new TestArrayStream(batch.Schema, batch); + + IArrowArrayStream received; + unsafe + { + received = CArrowAsyncDeviceStreamConsumer.CreateStream(out CArrowAsyncDeviceStreamHandler* handler); + CArrowAsyncDeviceStreamProducer.Produce(source, handler); + } + + using (received) + { + RecordBatch result = await received.ReadNextRecordBatchAsync(); + Assert.NotNull(result); + Assert.Equal(5, result.Length); + + Int32Array values = (Int32Array)result.Column(0); + Assert.Equal(1, values.GetValue(0)); + Assert.Equal(5, values.GetValue(4)); + + result.Dispose(); + + RecordBatch end = await received.ReadNextRecordBatchAsync(); + Assert.Null(end); + } + } + + [Fact] + public async Task RoundTripMultipleBatches() + { + RecordBatch batch1 = CreateBatch(0, 3); + RecordBatch batch2 = CreateBatch(10, 3); + RecordBatch batch3 = CreateBatch(20, 3); + IArrowArrayStream source = new TestArrayStream(batch1.Schema, batch1, batch2, batch3); + + IArrowArrayStream received; + unsafe + { + received = CArrowAsyncDeviceStreamConsumer.CreateStream(out CArrowAsyncDeviceStreamHandler* handler); + CArrowAsyncDeviceStreamProducer.Produce(source, handler); + } + + using (received) + { + RecordBatch r1 = await received.ReadNextRecordBatchAsync(); + Assert.NotNull(r1); + Assert.Equal(0, ((Int32Array)r1.Column(0)).GetValue(0)); + r1.Dispose(); + + RecordBatch r2 = await received.ReadNextRecordBatchAsync(); + Assert.NotNull(r2); + Assert.Equal(10, ((Int32Array)r2.Column(0)).GetValue(0)); + r2.Dispose(); + + RecordBatch r3 = await received.ReadNextRecordBatchAsync(); + Assert.NotNull(r3); + Assert.Equal(20, ((Int32Array)r3.Column(0)).GetValue(0)); + r3.Dispose(); + + RecordBatch end = await received.ReadNextRecordBatchAsync(); + Assert.Null(end); + } + } + + [Fact] + public async Task EmptyStream() + { + Schema schema = new Schema.Builder() + .Field(f => f.Name("x").DataType(Int32Type.Default)) + .Build(); + IArrowArrayStream source = new TestArrayStream(schema); + + IArrowArrayStream received; + unsafe + { + received = CArrowAsyncDeviceStreamConsumer.CreateStream(out CArrowAsyncDeviceStreamHandler* handler); + CArrowAsyncDeviceStreamProducer.Produce(source, handler); + } + + using (received) + { + Assert.Equal("x", received.Schema.FieldsList[0].Name); + + RecordBatch end = await received.ReadNextRecordBatchAsync(); + Assert.Null(end); + } + } + + [Fact] + public async Task SchemaIsPreserved() + { + Schema schema = new Schema.Builder() + .Field(f => f.Name("col_a").DataType(Int64Type.Default).Nullable(true)) + .Field(f => f.Name("col_b").DataType(StringType.Default).Nullable(false)) + .Build(); + IArrowArrayStream source = new TestArrayStream(schema); + + IArrowArrayStream received; + unsafe + { + received = CArrowAsyncDeviceStreamConsumer.CreateStream(out CArrowAsyncDeviceStreamHandler* handler); + CArrowAsyncDeviceStreamProducer.Produce(source, handler); + } + + using (received) + { + // Wait for end of stream so schema is definitely available + RecordBatch end = await received.ReadNextRecordBatchAsync(); + Assert.Null(end); + + Assert.Equal(2, received.Schema.FieldsList.Count); + Assert.Equal("col_a", received.Schema.FieldsList[0].Name); + Assert.Equal(ArrowTypeId.Int64, received.Schema.FieldsList[0].DataType.TypeId); + Assert.Equal("col_b", received.Schema.FieldsList[1].Name); + Assert.Equal(ArrowTypeId.String, received.Schema.FieldsList[1].DataType.TypeId); + } + } + + [Fact] + public unsafe void InitializeStructsZeroed() + { + CArrowAsyncTask task = default; + Assert.True(task.extract_data == default); + Assert.True(task.private_data == null); + + CArrowAsyncProducer* producer = CArrowAsyncProducer.Create(); + Assert.Equal((ArrowDeviceType)0, producer->device_type); + Assert.True(producer->request == default); + Assert.True(producer->cancel == default); + Assert.True(producer->additional_metadata == null); + Assert.True(producer->private_data == null); + CArrowAsyncProducer.Free(producer); + + CArrowAsyncDeviceStreamHandler* handler = CArrowAsyncDeviceStreamHandler.Create(); + Assert.True(handler->on_schema == default); + Assert.True(handler->on_next_task == default); + Assert.True(handler->on_error == default); + Assert.True(handler->release == default); + Assert.True(handler->producer == null); + Assert.True(handler->private_data == null); + CArrowAsyncDeviceStreamHandler.Free(handler); + } + + [Fact] + public async Task ProducerSetsDeviceTypeCpu() + { + RecordBatch batch = CreateBatch(1, 1); + IArrowArrayStream source = new TestArrayStream(batch.Schema, batch); + + IArrowArrayStream received; + unsafe + { + received = CArrowAsyncDeviceStreamConsumer.CreateStream(out CArrowAsyncDeviceStreamHandler* handler); + CArrowAsyncDeviceStreamProducer.Produce(source, handler); + } + + using (received) + { + RecordBatch r = await received.ReadNextRecordBatchAsync(); + Assert.NotNull(r); + // If we got data, the producer was using CPU device type + // (verified by the fact that CArrowDeviceArrayImporter accepted it) + r.Dispose(); + + RecordBatch end = await received.ReadNextRecordBatchAsync(); + Assert.Null(end); + } + } + + [Fact] + public async Task CancelledReadDoesNotLoseBatch() + { + RecordBatch batch = CreateBatch(42, 2); + var gate = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); + var source = new GatedArrayStream(batch.Schema, gate.Task, batch); + + IArrowArrayStream received; + unsafe + { + received = CArrowAsyncDeviceStreamConsumer.CreateStream(out CArrowAsyncDeviceStreamHandler* handler); + CArrowAsyncDeviceStreamProducer.Produce(source, handler); + } + + using (received) + { + // Start a read while the producer is blocked, then cancel it. + using (var cts = new CancellationTokenSource()) + { + Task<RecordBatch> pending = received.ReadNextRecordBatchAsync(cts.Token).AsTask(); + cts.Cancel(); + await Assert.ThrowsAnyAsync<OperationCanceledException>(() => pending); + } + + // Let the producer deliver; the batch must go to the next read, + // not to the cancelled one. + gate.SetResult(true); + + RecordBatch result = await received.ReadNextRecordBatchAsync(); + Assert.NotNull(result); + Assert.Equal(42, ((Int32Array)result.Column(0)).GetValue(0)); + result.Dispose(); + + RecordBatch end = await received.ReadNextRecordBatchAsync(); + Assert.Null(end); + } + } + + [Fact] + public async Task SchemaExportFailureSignalsErrorAndReleases() + { + var source = new ThrowingSchemaArrayStream("schema export failed"); + + IArrowArrayStream received; + unsafe + { + received = CArrowAsyncDeviceStreamConsumer.CreateStream(out CArrowAsyncDeviceStreamHandler* handler); + CArrowAsyncDeviceStreamProducer.Produce(source, handler); + } + + using (received) + { + Exception readError = await Assert.ThrowsAnyAsync<Exception>( + () => received.ReadNextRecordBatchAsync().AsTask()); + Assert.Contains("schema export failed", readError.Message); + + Exception schemaError = Assert.ThrowsAny<Exception>(() => received.Schema); + Assert.Contains("schema export failed", schemaError.Message); + + // The producer finished, so it must have disposed its source. + Assert.True(source.IsDisposed); + } + } + + [Theory] + [InlineData(1)] + [InlineData(3)] + [InlineData(64)] + public async Task ManyBatchesArriveInOrder(long queueSize) + { + // Small queue sizes make the consumer call request() repeatedly while the + // producer is running, which used to start overlapping produce loops. + const int count = 200; + var batches = new RecordBatch[count]; + for (int i = 0; i < count; i++) + { + batches[i] = CreateBatch(i * 10, 1 + i % 7); + } + var source = new YieldingArrayStream(batches[0].Schema, batches); + + IArrowArrayStream received; + unsafe + { + received = CArrowAsyncDeviceStreamConsumer.CreateStream(out CArrowAsyncDeviceStreamHandler* handler, queueSize); + CArrowAsyncDeviceStreamProducer.Produce(source, handler); + } + + using (received) + { + for (int i = 0; i < count; i++) + { + RecordBatch result = await received.ReadNextRecordBatchAsync(); + Assert.NotNull(result); + Assert.Equal(batches[i].Length, result.Length); + Assert.Equal(i * 10, ((Int32Array)result.Column(0)).GetValue(0)); + result.Dispose(); + } + + Assert.Null(await received.ReadNextRecordBatchAsync()); + } + + // The producer must never read its source from two loops at once. + Assert.Equal(1, source.MaxConcurrentReads); + } + + [Fact] + public async Task DisposingConsumerCancelsAndReleases() + { + RecordBatch batch = CreateBatch(0, 4); + var source = new EndlessArrayStream(batch); + + IArrowArrayStream received; + unsafe + { + received = CArrowAsyncDeviceStreamConsumer.CreateStream(out CArrowAsyncDeviceStreamHandler* handler, queueSize: 2); + CArrowAsyncDeviceStreamProducer.Produce(source, handler); + } + + for (int i = 0; i < 5; i++) + { + RecordBatch result = await received.ReadNextRecordBatchAsync(); + Assert.NotNull(result); + result.Dispose(); + } + + received.Dispose(); + + // Cancelling must lead to release (and no on_error). The producer + // disposes its source right after calling release. + Assert.True(await WaitUntilAsync(() => source.IsDisposed), "Producer did not release after cancel."); + } + + [Fact] + public async Task DisposingConsumerBeforeReadingReleases() + { + var source = new EndlessArrayStream(CreateBatch(0, 1)); + + unsafe + { + IArrowArrayStream received = CArrowAsyncDeviceStreamConsumer.CreateStream(out CArrowAsyncDeviceStreamHandler* handler); + CArrowAsyncDeviceStreamProducer.Produce(source, handler); + received.Dispose(); + } + + Assert.True(await WaitUntilAsync(() => source.IsDisposed), "Producer did not release after cancel."); + } + + [Theory] + [InlineData(0L)] + [InlineData(-1L)] + [InlineData(long.MinValue)] + public async Task InvalidRequestReportsErrorAndReleases(long n) + { + var source = new TestArrayStream(CreateBatch(0, 3).Schema, CreateBatch(0, 3), CreateBatch(3, 3)); + var consumer = new RecordingConsumer(requestInOnSchema: n); + + unsafe + { + CArrowAsyncDeviceStreamProducer.Produce(source, consumer.Handler); + } + + Task released = consumer.Released; + Assert.True(await Task.WhenAny(released, Task.Delay(TimeSpan.FromSeconds(10))) == released, "Handler was not released."); + + // The spec says n <= 0 is invalid and the producer should call on_error; + // after on_error comes release, and nothing is delivered. + IReadOnlyList<string> events = consumer.Events; + Assert.Equal(3, events.Count); + Assert.Equal("schema", events[0]); + Assert.StartsWith("error:22:", events[1]); // EINVAL + Assert.Contains("must be positive", events[1]); + Assert.Equal("release", events[2]); + Assert.False(consumer.SawOverlappingCallbacks); + Assert.True(source.IsDisposed); Review Comment: Fixed in 81be4ae. The test now waits for `source.IsDisposed` with `WaitUntilAsync`. -- 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]
