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 1855f8df fix(arrow/cdata): don't reuse freed handler state on release 
after a failed on_schema (#1575)
1855f8df is described below

commit 1855f8dfb36086bb14c1d5132418c8622e11b31c
Author: Ahmed Laban <[email protected]>
AuthorDate: Mon Nov 16 12:14:22 2026 -0500

    fix(arrow/cdata): don't reuse freed handler state on release after a failed 
on_schema (#1575)
    
    ### Rationale for this change
    
    Fixes #1573.
    
    If the `on_schema` callback of a handler from
    `CreateAsyncDeviceStreamHandler` fails, the handler's `release` callback
    panics afterwards with `runtime/cgo: misuse of an invalid Handle`.
    `on_schema` fails when the producer's device type isn't CPU or when
    `ImportCArrowSchema` returns an error. The spec says a producer should
    then call `release` rather than `on_error`, so any conforming producer
    hits this. arrow-go's own `exportAsyncProducer` does the same, since it
    always calls `release` in a defer.
    
    The cause is in `asyncStreamOnSchema`. It defers
    `C.free(self.private_data)` and `h.Delete()`, so they run on the failure
    paths too. Those paths return `EINVAL` without clearing
    `self.private_data`, so `asyncStreamRelease` then reads the handle from
    freed memory and would free `private_data` a second time.
    
    ### What changes are included in this PR?
    
    - `asyncStreamOnSchema` sets `self.private_data = nil` right after
    deferring the cleanup of the old state. The deferred calls already
    captured the old pointer and handle. On success `private_data` is
    replaced with the stream handler's handle as before, so that path is
    unchanged.
    - `asyncStreamRelease` handles `private_data == nil`: the state is
    already gone, so it only marks the handler as released (`release =
    nil`).
    
    This PR doesn't touch #1572, the separate issue about `request()` being
    called after release.
    
    ### Are these changes tested?
    
    Yes. I added `TestAsyncReleaseAfterOnSchemaFailure` to
    `arrow/cdata/cdata_test.go`, plus small helpers in
    `cdata_test_framework.go`. The test acts as a C producer: it calls the
    handler's `on_schema` and then `release`, as the spec requires after a
    failure, for both failure paths:
    
    - a producer whose device type is CUDA
    - a CPU producer whose schema has the format `~bogus`, which
    `ImportCArrowSchema` rejects
    
    It checks that the consumer gets the error, that `on_schema` returns
    `EINVAL`, and that `release` marks the handler as released.
    
    - Without the fix, both subtests crash with `panic: runtime/cgo: misuse
    of an invalid Handle` in `asyncStreamRelease`, matching the trace in the
    issue.
    - With the fix, `go test -tags test,assert -short ./arrow/cdata/...`
    passes, and so does `go test -race -tags test -count=5 -run TestAsync
    ./arrow/cdata/`. golangci-lint (staticcheck, repo config) reports
    nothing new on the touched files. I ran these on Linux amd64 with Go
    1.26.11.
    
    I didn't run the full module test suite or the `noasm` pass.
    
    ### Are there any user-facing changes?
    
    No API changes. A handler whose `on_schema` failed can now be released
    without crashing the process.
    
    Signed-off-by: Ahmed Laban <[email protected]>
---
 arrow/cdata/cdata_test.go           | 44 +++++++++++++++++++++++++++++++++++++
 arrow/cdata/cdata_test_framework.go | 37 +++++++++++++++++++++++++++++++
 arrow/cdata/exports.go              | 11 ++++++++++
 3 files changed, 92 insertions(+)

diff --git a/arrow/cdata/cdata_test.go b/arrow/cdata/cdata_test.go
index f4464386..2bd10d4b 100644
--- a/arrow/cdata/cdata_test.go
+++ b/arrow/cdata/cdata_test.go
@@ -1617,6 +1617,50 @@ func TestAsyncSchemaError(t *testing.T) {
        <-wait
 }
 
+// After on_schema fails, a producer calls release on the handler instead of
+// on_error, and that release must not touch the state on_schema freed.
+func TestAsyncReleaseAfterOnSchemaFailure(t *testing.T) {
+       tests := []struct {
+               name   string
+               format string
+               cpu    bool
+               errMsg string
+       }{
+               {"unsupported device", "i", false, "unsupported device type"},
+               {"invalid schema", "~bogus", true, "unimplemented type"},
+       }
+
+       for _, tt := range tests {
+               t.Run(tt.name, func(t *testing.T) {
+                       handler := testAsyncHandler()
+                       defer freeAsyncHandler(handler)
+
+                       ch := 
CreateAsyncDeviceStreamHandler(context.Background(), 1, handler)
+                       schema := testPrimitive(tt.format)
+
+                       type result struct {
+                               status   int
+                               released bool
+                       }
+                       done := make(chan result, 1)
+                       go func() {
+                               status, released := 
asyncOnSchemaThenRelease(handler, &schema, tt.cpu)
+                               done <- result{status, released}
+                       }()
+
+                       asyncStream := <-ch
+                       assert.ErrorContains(t, asyncStream.Err, tt.errMsg)
+
+                       res := <-done
+                       assert.Equal(t, 22, res.status)
+                       assert.True(t, res.released)
+                       if !schemaIsReleased(&schema) {
+                               releaseSchema(&schema)
+                       }
+               })
+       }
+}
+
 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 1726dc0f..ea180468 100644
--- a/arrow/cdata/cdata_test_framework.go
+++ b/arrow/cdata/cdata_test_framework.go
@@ -44,6 +44,22 @@ package cdata
 //     return handler;
 // }
 //
+// static struct ArrowAsyncProducer* get_test_async_producer(ArrowDeviceType 
device_type) {
+//     struct ArrowAsyncProducer* producer =
+//             (struct ArrowAsyncProducer*)malloc(sizeof(struct 
ArrowAsyncProducer));
+//     memset(producer, 0, sizeof(*producer));
+//     producer->device_type = device_type;
+//     return producer;
+// }
+//
+// static int call_async_on_schema(struct ArrowAsyncDeviceStreamHandler* 
handler, struct ArrowSchema* schema) {
+//     return handler->on_schema(handler, schema);
+// }
+//
+// static void call_async_release(struct ArrowAsyncDeviceStreamHandler* 
handler) {
+//     handler->release(handler);
+// }
+//
 // void release_test_arr(struct ArrowArray* arr);
 //
 // static int32_t* get_data() {
@@ -176,6 +192,27 @@ func freeAsyncHandler(h *CArrowAsyncDeviceStreamHandler) {
        C.free(unsafe.Pointer(h))
 }
 
+// asyncOnSchemaThenRelease acts as a producer whose device is CPU (or CUDA
+// when cpu is false): it calls the on_schema callback of handler with schema
+// and then, as a producer must once on_schema returned an error, its release
+// callback. It returns the status on_schema returned and whether release
+// marked handler as released.
+func asyncOnSchemaThenRelease(handler *CArrowAsyncDeviceStreamHandler, schema 
*CArrowSchema, cpu bool) (status int, released bool) {
+       deviceType := C.ArrowDeviceType(C.ARROW_DEVICE_CPU)
+       if !cpu {
+               deviceType = C.ArrowDeviceType(C.ARROW_DEVICE_CUDA)
+       }
+       producer := C.get_test_async_producer(deviceType)
+       defer C.free(unsafe.Pointer(producer))
+
+       handler.producer = producer
+       status = int(C.call_async_on_schema(handler, schema))
+       if status != 0 {
+               C.call_async_release(handler)
+       }
+       return status, handler.release == nil
+}
+
 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 1dd615dd..03dc8ace 100644
--- a/arrow/cdata/exports.go
+++ b/arrow/cdata/exports.go
@@ -217,6 +217,11 @@ func asyncStreamOnSchema(self 
*CArrowAsyncDeviceStreamHandler, schema *CArrowSch
        h := getHandle(self.private_data)
        defer C.free(self.private_data)
        defer h.Delete()
+       // the deferred calls above free this state on every path. Clear it so
+       // that release, which a producer calls instead of on_error once
+       // on_schema has failed, does not use it again. On success it is
+       // replaced below.
+       self.private_data = nil
 
        handler := h.Value().(cAsyncState)
        defer close(handler.ch)
@@ -278,6 +283,12 @@ func asyncStreamOnError(self 
*CArrowAsyncDeviceStreamHandler, code C.int, messag
 
 //export asyncStreamRelease
 func asyncStreamRelease(self *CArrowAsyncDeviceStreamHandler) {
+       if self.private_data == nil {
+               // on_schema failed and has already freed the handler's state
+               self.release = nil
+               return
+       }
+
        h := getHandle(self.private_data)
        if handler, ok := h.Value().(*cAsyncStreamHandler); ok {
                handler.release()

Reply via email to