This is an automated email from the ASF dual-hosted git repository.

zeroshade pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-go.git


The following commit(s) were added to refs/heads/main by this push:
     new b80f8c1d fix(arrow/cdata): don't call the async producer after the 
handler is released (#1609)
b80f8c1d is described below

commit b80f8c1da9fd746a1df50db018f5a7d76ed334ee
Author: Ayaan <[email protected]>
AuthorDate: Fri Nov 20 03:45:18 2026 +0530

    fix(arrow/cdata): don't call the async producer after the handler is 
released (#1609)
    
    ### Rationale for this change
    
    Fixes #1572.
    
    The spec only requires an `ArrowAsyncProducer` to stay valid until just 
before the producer calls `release` on the handler. The handler from 
`CreateAsyncDeviceStreamHandler` can still have tasks queued at that point, and 
`asyncTaskQueue` called `request(1)` on the producer for each of them, so a 
producer that frees itself after `release`, like the .NET producer in the 
issue, could still be called.
    
    Separately, `asyncTaskExtract` wrote through `out` without a NULL check, 
although the spec lets a consumer pass NULL when it doesn't want the data.
    
    ### What changes are included in this PR?
    
    - `cAsyncStreamHandler` guards `producer` with a mutex. `release` clears 
it, and `asyncTaskQueue` now takes the handler and calls `request` and `cancel` 
only while `producer` is set. Tasks that were already queued are still 
extracted as before; only the calls into the producer stop.
    - `asyncTaskExtract` returns 0 without writing when `out` is NULL. The 
record is still released.
    
    `release` now waits while a `request` or `cancel` call from the consumer is 
in progress. The spec text in `CDeviceDataInterface.rst` only forbids `request` 
from synchronously calling `on_next_task` or `on_error`, and `cancel` from 
calling any handler other than `on_error`. `abi.h` adds that, while not 
cancelled, later calls to `on_next_task`, `on_error` or `release` "should be 
scheduled by the producer to be called later", but that is a `should`. If a 
producer calls `release` synchron [...]
    
    ### Are these changes tested?
    
    Yes, two tests in `arrow/cdata/cdata_test.go` with helpers in 
`cdata_test_framework.go`:
    
    - `TestAsyncNoRequestAfterRelease`: a C producer sends three tasks and the 
end of the stream, then calls `release`. Its `extract_data` waits until 
`release` has returned, so at least two tasks are still queued when the handler 
is released. The test counts `request` calls made after `release` returns and 
checks that `extract_data` is called for all three tasks. On main it fails in 
10 of 10 runs; with this change no `request` call is made after `release`.
    - `TestAsyncTaskExtractNull`: calls `asyncTaskExtract` with a NULL `out` 
using a checked allocator. On main it panics with a nil pointer dereference; 
here it returns 0 and the checked allocator reports no outstanding allocations.
    
    `go test -tags test,assert -short ./arrow/cdata/...`, the same with 
`noasm`, `go test -race -tags test -count=20 -run TestAsync ./arrow/cdata/` and 
`golangci-lint run ./arrow/cdata/...` pass on Linux amd64 with Go 1.27.1. I 
didn't run the full module tests or test against a real external producer.
    
    ### Are there any user-facing changes?
    
    No API changes. A producer can now free its `ArrowAsyncProducer` after 
calling `release` without the consumer calling into it, and consumers can pass 
NULL to `extract_data`.
---
 arrow/cdata/cdata_exports.go        | 21 ++++++++++---
 arrow/cdata/cdata_test.go           | 48 +++++++++++++++++++++++++++++
 arrow/cdata/cdata_test_framework.go | 61 +++++++++++++++++++++++++++++++++++++
 arrow/cdata/exports.go              | 12 ++++++--
 4 files changed, 135 insertions(+), 7 deletions(-)

diff --git a/arrow/cdata/cdata_exports.go b/arrow/cdata/cdata_exports.go
index f89d0e25..faa31caa 100644
--- a/arrow/cdata/cdata_exports.go
+++ b/arrow/cdata/cdata_exports.go
@@ -55,6 +55,7 @@ import (
        "runtime/cgo"
        "strconv"
        "strings"
+       "sync"
        "unsafe"
 
        "github.com/apache/arrow-go/v18/arrow"
@@ -515,17 +516,24 @@ func (rr *cRecordReader) release() {
 }
 
 type cAsyncStreamHandler struct {
+       // mu guards producer: once release returns the producer may be freed,
+       // so it must not be called again.
+       mu        sync.Mutex
        producer  *CArrowAsyncProducer
        taskQueue chan taskState
        ctx       context.Context
 }
 
-func asyncTaskQueue(ctx context.Context, schema *arrow.Schema, recordStream 
chan<- RecordMessage, taskQueue <-chan taskState, producer 
*CArrowAsyncProducer) {
+func asyncTaskQueue(ctx context.Context, schema *arrow.Schema, recordStream 
chan<- RecordMessage, taskQueue <-chan taskState, h *cAsyncStreamHandler) {
        defer close(recordStream)
        for {
                select {
                case <-ctx.Done():
-                       C.goCallCancel(producer)
+                       h.mu.Lock()
+                       if h.producer != nil {
+                               C.goCallCancel(h.producer)
+                       }
+                       h.mu.Unlock()
                        return
                case task, ok := <-taskQueue:
                        // if the queue closes or we receive a nil task, we're 
done
@@ -539,7 +547,11 @@ func asyncTaskQueue(ctx context.Context, schema 
*arrow.Schema, recordStream chan
                        }
 
                        // request another batch now that we've processed this 
one
-                       C.goCallRequest(producer, C.int64_t(1))
+                       h.mu.Lock()
+                       if h.producer != nil {
+                               C.goCallRequest(h.producer, C.int64_t(1))
+                       }
+                       h.mu.Unlock()
 
                        var out CArrowDeviceArray
                        if C.goExtractTaskData(&task.task, &out) != C.int(0) {
@@ -577,6 +589,7 @@ func (h *cAsyncStreamHandler) onError(code C.int, message, 
metadata *C.char) {
 
 func (h *cAsyncStreamHandler) release() {
        close(h.taskQueue)
+       h.mu.Lock()
        h.taskQueue, h.producer = nil, nil
-       h.producer = nil
+       h.mu.Unlock()
 }
diff --git a/arrow/cdata/cdata_test.go b/arrow/cdata/cdata_test.go
index c2d12159..75d10211 100644
--- a/arrow/cdata/cdata_test.go
+++ b/arrow/cdata/cdata_test.go
@@ -1703,6 +1703,54 @@ func TestAsyncReleaseAfterOnSchemaFailure(t *testing.T) {
        }
 }
 
+// A producer may free its ArrowAsyncProducer once release returns, so the
+// consumer must not call request() for tasks still buffered at that point.
+func TestAsyncNoRequestAfterRelease(t *testing.T) {
+       handler := testAsyncHandler()
+       defer freeAsyncHandler(handler)
+
+       ch := CreateAsyncDeviceStreamHandler(context.Background(), 4, handler)
+       var schema CArrowSchema
+       ExportArrowSchema(arrow.NewSchema([]arrow.Field{{Name: "a", Type: 
arrow.PrimitiveTypes.Int32}}, nil), &schema)
+
+       done := make(chan struct{})
+       go func() {
+               defer close(done)
+               asyncProduceThenRelease(handler, &schema, 3)
+       }()
+
+       asyncStream := <-ch
+       require.NoError(t, asyncStream.Err)
+       for range asyncStream.Stream {
+       }
+       <-done
+       defer freeAsyncProducer()
+
+       late, extracts := asyncProducerCounts()
+       assert.Zero(t, late, "request called after release")
+       assert.Equal(t, 3, extracts, "buffered tasks must still be extracted")
+}
+
+// A consumer may pass NULL to extract_data when it doesn't want the data.
+func TestAsyncTaskExtractNull(t *testing.T) {
+       mem := memory.NewCheckedAllocator(memory.DefaultAllocator)
+       defer mem.AssertSize(t, 0)
+
+       bldr := array.NewInt32Builder(mem)
+       defer bldr.Release()
+       bldr.AppendValues([]int32{1, 2, 3}, nil)
+       arr := bldr.NewArray()
+       defer arr.Release()
+       rec := array.NewRecordBatch(arrow.NewSchema([]arrow.Field{{Name: "a", 
Type: arrow.PrimitiveTypes.Int32}}, nil), []arrow.Array{arr}, 3)
+
+       // a Go-side handle slot (not createHandle's malloc) so nothing is left 
to free
+       hnd := cgo.NewHandle(rec)
+       defer hnd.Delete()
+       hptr := uintptr(hnd)
+       task := CArrowAsyncTask{private_data: unsafe.Pointer(&hptr)}
+       assert.Zero(t, int(asyncTaskExtract(&task, nil)))
+}
+
 func TestAsyncPropagateError(t *testing.T) {
        reclist := arrdata.Records["primitives"]
 
diff --git a/arrow/cdata/cdata_test_framework.go 
b/arrow/cdata/cdata_test_framework.go
index 7dfb95cd..478eb5c1 100644
--- a/arrow/cdata/cdata_test_framework.go
+++ b/arrow/cdata/cdata_test_framework.go
@@ -22,6 +22,7 @@ package cdata
 // #include <stdlib.h>
 // #include <stdint.h>
 // #include <string.h>
+// #include <errno.h>
 // #include "abi.h"
 // #include "helpers.h"
 //
@@ -60,6 +61,49 @@ package cdata
 //     handler->release(handler);
 // }
 //
+// static volatile int g_async_released;
+// static volatile int g_async_late_requests;
+// static volatile int g_async_extracts;
+// static struct ArrowAsyncProducer* g_async_producer;
+//
+// static void test_async_request(struct ArrowAsyncProducer* p, int64_t n) {
+//     if (__atomic_load_n(&g_async_released, __ATOMIC_SEQ_CST)) 
__atomic_fetch_add(&g_async_late_requests, 1, __ATOMIC_SEQ_CST);
+// }
+//
+// static int async_late_requests() { return g_async_late_requests; }
+// static int async_extracts() { return g_async_extracts; }
+// static void free_async_producer() { free(g_async_producer); }
+//
+// static void test_async_cancel(struct ArrowAsyncProducer* p) {}
+//
+// static int test_async_extract(struct ArrowAsyncTask* task, struct 
ArrowDeviceArray* out) {
+//     // stay busy until release so the later tasks are still buffered then
+//     while (!__atomic_load_n(&g_async_released, __ATOMIC_SEQ_CST)) {}
+//     __atomic_fetch_add(&g_async_extracts, 1, __ATOMIC_SEQ_CST);
+//     return EINVAL; // no data; consumer skips the task
+// }
+//
+// // run_async_producer acts as a conforming producer: n tasks, end of
+// // stream, then release. request() calls after release are counted.
+// static int run_async_producer(struct ArrowAsyncDeviceStreamHandler* 
handler, struct ArrowSchema* schema, int n) {
+//     __atomic_store_n(&g_async_released, 0, __ATOMIC_SEQ_CST);
+//     g_async_late_requests = g_async_extracts = 0;
+//     g_async_producer = get_test_async_producer(ARROW_DEVICE_CPU);
+//     g_async_producer->request = test_async_request;
+//     g_async_producer->cancel = test_async_cancel;
+//     handler->producer = g_async_producer;
+//     int rc = handler->on_schema(handler, schema);
+//     for (int i = 0; rc == 0 && i < n; i++) {
+//             struct ArrowAsyncTask task = {test_async_extract, NULL};
+//             rc = handler->on_next_task(handler, &task, NULL);
+//     }
+//     if (rc == 0) rc = handler->on_next_task(handler, NULL, NULL);
+//     handler->release(handler);
+//     // from here the producer may be freed
+//     __atomic_store_n(&g_async_released, 1, __ATOMIC_SEQ_CST);
+//     return rc;
+// }
+//
 // void release_test_arr(struct ArrowArray* arr);
 //
 // static int32_t* get_data() {
@@ -217,6 +261,23 @@ func asyncOnSchemaThenRelease(handler 
*CArrowAsyncDeviceStreamHandler, schema *C
        return status, handler.release == nil
 }
 
+// asyncProduceThenRelease runs a producer that sends n tasks and end of
+// stream and then releases handler. Call freeAsyncProducer once the
+// consumer is done.
+func asyncProduceThenRelease(handler *CArrowAsyncDeviceStreamHandler, schema 
*CArrowSchema, n int) {
+       C.run_async_producer(handler, schema, C.int(n))
+}
+
+// asyncProducerCounts returns the request calls made after release and
+// the tasks extracted.
+func asyncProducerCounts() (late, extracts int) {
+       return int(C.async_late_requests()), int(C.async_extracts())
+}
+
+func freeAsyncProducer() {
+       C.free_async_producer()
+}
+
 func testNested(fmts, names []string, isnull []bool) **CArrowSchema {
        if len(fmts) != len(names) {
                panic("testing nested lists must have same size fmts and names")
diff --git a/arrow/cdata/exports.go b/arrow/cdata/exports.go
index 03dc8ace..26dc5483 100644
--- a/arrow/cdata/exports.go
+++ b/arrow/cdata/exports.go
@@ -247,14 +247,15 @@ func asyncStreamOnSchema(self 
*CArrowAsyncDeviceStreamHandler, schema *CArrowSch
        handler.ch <- AsyncRecordBatchStream{Schema: sc,
                AdditionalMetadata: meta, Stream: recordStream}
 
-       self.private_data = createHandle(cgo.NewHandle(&cAsyncStreamHandler{
+       streamHandler := &cAsyncStreamHandler{
                producer:  self.producer,
                ctx:       handler.ctx,
                taskQueue: taskQueue,
-       }))
+       }
+       self.private_data = createHandle(cgo.NewHandle(streamHandler))
 
        C.goCallRequest(self.producer, C.int64_t(handler.queueSize))
-       go asyncTaskQueue(handler.ctx, sc, recordStream, taskQueue, 
self.producer)
+       go asyncTaskQueue(handler.ctx, sc, recordStream, taskQueue, 
streamHandler)
        return 0
 }
 
@@ -333,6 +334,11 @@ func asyncTaskExtract(task *CArrowAsyncTask, out 
*CArrowDeviceArray) C.int {
        rec := h.Value().(arrow.RecordBatch)
        defer rec.Release()
 
+       // a NULL out means the consumer doesn't want the data
+       if out == nil {
+               return C.int(0)
+       }
+
        out.device_id, out.device_type = C.int64_t(-1), C.ARROW_DEVICE_CPU
        ExportArrowRecordBatch(rec, &out.array, nil)
        return C.int(0)

Reply via email to