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 8f7e2d69 fix(arrow/cdata): drain tasks after cancel and free per-task
handle in async consumer (#1643)
8f7e2d69 is described below
commit 8f7e2d691961b34d10a2ba1f4ccb73e29a9b3329
Author: Ayaan <[email protected]>
AuthorDate: Tue Nov 24 22:28:59 2026 +0530
fix(arrow/cdata): drain tasks after cancel and free per-task handle in
async consumer (#1643)
### Rationale for this change
Fixes #1642.
Follow-ups noted on #1609, from the C Device Data Interface spec:
- After `cancel` the consumer stopped reading `taskQueue`, so tasks the
producer still sent were never passed to `extract_data`. The spec says a
consumer that doesn't want a task must still call `extract_data` (with
`NULL`) so the producer can clean up, and that more `on_next_task` calls
can follow `cancel`. When the queue filled up, `on_next_task` also
blocked.
- `asyncTaskExtract` released the record but never deleted the task's
`cgo.Handle` or freed its heap slot, so every extracted task leaked
both.
### What changes are included in this PR?
- `asyncTaskQueue` keeps draining `taskQueue` after it returns, calling
`extract_data` with `NULL` for each task until `release` closes the
queue. This runs after the record stream is closed, so consumers of the
stream are not delayed.
- `asyncTaskExtract` deletes the task's `cgo.Handle` and frees its slot
once it has been used (including the `NULL` case).
### Are these changes tested?
Yes. `TestAsyncDrainTasksAfterCancel` runs a producer that sends more
tasks than the queue holds after `cancel` and checks each is extracted
with `NULL`. `TestAsyncTaskExtractNull` now checks the handle is
deleted. Those two fail on main and pass here.
`TestAsyncTaskExtractTwice` checks that a second `extract_data` call on
the same task returns `EINVAL`. `go test -race -count=20 -run TestAsync
./arrow/cdata` and the `arrow/cdata` suite under `-asan` pass.
### Are there any user-facing changes?
No.
Notes:
- `extract_data` must still be called exactly once per task. A second
call returns `EINVAL`.
- Tasks still buffered when `release` returns may be extracted with
`NULL` afterwards, as the main loop already did.
- If the consumer cancels and stops reading `Stream`, the loop can still
block on `recordStream <- ...` and never reach the drain. That is
pre-existing and out of scope here.
---------
Signed-off-by: Ayaan <[email protected]>
---
arrow/cdata/cdata_exports.go | 10 ++++++
arrow/cdata/cdata_test.go | 68 ++++++++++++++++++++++++++++++++++---
arrow/cdata/cdata_test_framework.go | 36 ++++++++++++++++++++
arrow/cdata/exports.go | 12 ++++++-
4 files changed, 121 insertions(+), 5 deletions(-)
diff --git a/arrow/cdata/cdata_exports.go b/arrow/cdata/cdata_exports.go
index 663bd3cb..ee0f74be 100644
--- a/arrow/cdata/cdata_exports.go
+++ b/arrow/cdata/cdata_exports.go
@@ -530,6 +530,16 @@ type cAsyncStreamHandler struct {
}
func asyncTaskQueue(ctx context.Context, schema *arrow.Schema, recordStream
chan<- RecordMessage, taskQueue <-chan taskState, h *cAsyncStreamHandler) {
+ // Runs after close(recordStream). A producer may still send tasks after
+ // cancel; extract them with NULL, as the spec asks, so it can clean up.
+ // release closes taskQueue, which ends the loop.
+ defer func() {
+ for task := range taskQueue {
+ if task.err == nil && task.task.extract_data != nil {
+ C.goExtractTaskData(&task.task, nil)
+ }
+ }
+ }()
defer close(recordStream)
for {
select {
diff --git a/arrow/cdata/cdata_test.go b/arrow/cdata/cdata_test.go
index ef3dd0e0..cab4cac7 100644
--- a/arrow/cdata/cdata_test.go
+++ b/arrow/cdata/cdata_test.go
@@ -1805,12 +1805,72 @@ func TestAsyncTaskExtractNull(t *testing.T) {
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)}
+ task := CArrowAsyncTask{private_data: createHandle(hnd)}
assert.Zero(t, int(asyncTaskExtract(&task, nil)))
+ // extract_data owns the task's handle (and its slot, which ASan checks)
+ assert.Panics(t, func() { hnd.Value() }, "handle not deleted")
+}
+
+// A second extract_data call on the same task is a consumer bug; it must
+// fail with EINVAL, not touch the freed handle.
+func TestAsyncTaskExtractTwice(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)
+
+ task := CArrowAsyncTask{private_data: createHandle(cgo.NewHandle(rec))}
+ assert.Zero(t, int(asyncTaskExtract(&task, nil)))
+ assert.Equal(t, cEINVAL, int(asyncTaskExtract(&task, nil)))
+}
+
+// A producer may send tasks after cancel; the consumer must still pass each
+// to extract_data, with NULL, so the producer can clean up.
+func TestAsyncDrainTasksAfterCancel(t *testing.T) {
+ const queueSize, nTasks = 2, 6 // more tasks than the queue holds
+
+ handler := testAsyncHandler()
+ defer freeAsyncHandler(handler)
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ ch := CreateAsyncDeviceStreamHandler(ctx, queueSize, 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)
+ asyncCancelThenProduce(handler, &schema, nTasks)
+ }()
+ // even if the test fails early: cancel (the producer waits for it),
wait
+ // for the producer, then free it
+ defer freeAsyncProducer()
+ defer func() {
+ cancel()
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second): // producer blocked on a
full queue
+ t.Error("producer never finished: tasks after cancel
are not drained")
+ }
+ }()
+
+ asyncStream := <-ch
+ require.NoError(t, asyncStream.Err)
+ cancel()
+ for range asyncStream.Stream {
+ }
+
+ assert.Eventually(t, func() bool {
+ _, extracts := asyncProducerCounts()
+ return extracts == nTasks
+ }, 5*time.Second, time.Millisecond, "tasks sent after cancel must be
extracted with NULL")
}
func TestAsyncPropagateError(t *testing.T) {
diff --git a/arrow/cdata/cdata_test_framework.go
b/arrow/cdata/cdata_test_framework.go
index 478eb5c1..2df30e44 100644
--- a/arrow/cdata/cdata_test_framework.go
+++ b/arrow/cdata/cdata_test_framework.go
@@ -104,6 +104,34 @@ package cdata
// return rc;
// }
//
+// static volatile int g_async_cancelled;
+//
+// static void test_async_cancel_flag(struct ArrowAsyncProducer* p) {
__atomic_store_n(&g_async_cancelled, 1, __ATOMIC_SEQ_CST); }
+//
+// // counts only extracts whose out is NULL
+// static int test_async_extract_null(struct ArrowAsyncTask* task, struct
ArrowDeviceArray* out) {
+// if (out == NULL) __atomic_fetch_add(&g_async_extracts, 1,
__ATOMIC_SEQ_CST);
+// return 0;
+// }
+//
+// // run_async_cancel_producer waits for cancel, then, as the spec allows,
+// // still sends n tasks and releases.
+// static int run_async_cancel_producer(struct ArrowAsyncDeviceStreamHandler*
handler, struct ArrowSchema* schema, int n) {
+// g_async_cancelled = 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_flag;
+// handler->producer = g_async_producer;
+// int rc = handler->on_schema(handler, schema);
+// while (rc == 0 && !__atomic_load_n(&g_async_cancelled,
__ATOMIC_SEQ_CST)) {}
+// for (int i = 0; rc == 0 && i < n; i++) {
+// struct ArrowAsyncTask task = {test_async_extract_null, NULL};
+// rc = handler->on_next_task(handler, &task, NULL);
+// }
+// handler->release(handler);
+// return rc;
+// }
+//
// void release_test_arr(struct ArrowArray* arr);
//
// static int32_t* get_data() {
@@ -148,6 +176,7 @@ import (
)
const (
+ cEINVAL = int(C.EINVAL)
flagIsNullable = C.ARROW_FLAG_NULLABLE
flagMapKeysSorted = C.ARROW_FLAG_MAP_KEYS_SORTED
)
@@ -268,6 +297,13 @@ func asyncProduceThenRelease(handler
*CArrowAsyncDeviceStreamHandler, schema *CA
C.run_async_producer(handler, schema, C.int(n))
}
+// asyncCancelThenProduce runs a producer that waits for cancel, sends n
+// tasks and releases handler. Call freeAsyncProducer once the consumer is
+// done. asyncProducerCounts then returns the tasks extracted with NULL.
+func asyncCancelThenProduce(handler *CArrowAsyncDeviceStreamHandler, schema
*CArrowSchema, n int) {
+ C.run_async_cancel_producer(handler, schema, C.int(n))
+}
+
// asyncProducerCounts returns the request calls made after release and
// the tasks extracted.
func asyncProducerCounts() (late, extracts int) {
diff --git a/arrow/cdata/exports.go b/arrow/cdata/exports.go
index 26dc5483..eb33e0fc 100644
--- a/arrow/cdata/exports.go
+++ b/arrow/cdata/exports.go
@@ -330,9 +330,19 @@ func asyncProducerCancel(producer *CArrowAsyncProducer) {
//export asyncTaskExtract
func asyncTaskExtract(task *CArrowAsyncTask, out *CArrowDeviceArray) C.int {
+ // a second call on the same task is a consumer bug; fail instead of
use-after-free
+ if task.private_data == nil {
+ return C.EINVAL
+ }
h := getHandle(task.private_data)
rec := h.Value().(arrow.RecordBatch)
- defer rec.Release()
+ // extract_data runs once per task and owns the task's handle and slot
+ defer func() {
+ rec.Release()
+ h.Delete()
+ C.free(task.private_data)
+ task.private_data = nil
+ }()
// a NULL out means the consumer doesn't want the data
if out == nil {