From 9ad92ab9fd0a6259603988777c4d68e2c10886be Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 27 Nov 2026 05:48:37 +0000 Subject: [PATCH 1/4] Bind typed kernel cell readers once per batch Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- CHANGELOG.md | 1 + internal/arrowscan/bind.go | 79 +++++++++ internal/arrowscan/bind_test.go | 185 +++++++++++++++++++++ internal/backend/kernel/rows.go | 38 +++-- internal/backend/kernel/rows_bench_test.go | 98 +++++++++++ internal/backend/kernel/rows_bound_test.go | 100 +++++++++++ 6 files changed, 491 insertions(+), 10 deletions(-) create mode 100644 internal/arrowscan/bind.go create mode 100644 internal/arrowscan/bind_test.go create mode 100644 internal/backend/kernel/rows_bench_test.go create mode 100644 internal/backend/kernel/rows_bound_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f17e4c9..6ad4832f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### Driver changes +- Reduce per-cell CPU in kernel row iteration by binding typed column readers once per batch; result values and types are unchanged. - **Behavior change:** Bound each whole-transfer Thrift CloudFetch download attempt, including `WithTransport`, by the existing 900s `ClientTimeout`, and omit the link's presigned query string from download errors (databricks/databricks-sql-go#475). - **Behavior change:** Without direct results, `ArrowIPCStreamIterator.SchemaBytes()` and `ArrowBatchIterator.Schema()` now retrieve result metadata without fetching data and return the result schema, including for empty results, and can return request or schema-conversion errors. Schemas inferred from Thrift metadata may differ from CloudFetch file schemas when server ArrowSchema is absent (databricks/databricks-sql-go#312). - Evict kernel connections when SEA reports a missing or invalid session, and reject later requests locally without replaying the failed statement. diff --git a/internal/arrowscan/bind.go b/internal/arrowscan/bind.go new file mode 100644 index 00000000..d64d5024 --- /dev/null +++ b/internal/arrowscan/bind.go @@ -0,0 +1,79 @@ +package arrowscan + +import ( + "database/sql/driver" + "strings" + "time" + + "github.com/apache/arrow-go/v18/arrow" + "github.com/apache/arrow-go/v18/arrow/array" + "github.com/apache/arrow-go/v18/arrow/bitutil" +) + +// CellScanner reads a cell while its caller-owned Arrow array is alive. +type CellScanner func(row int) (driver.Value, error) + +// BindCellScanner resolves a column's scalar reader and null bitmap once per +// batch. Like ScanCellCachedWithOptions, loc is authoritative for timestamps. +func BindCellScanner(col arrow.Array, loc *time.Location, keys *StructKeyCache, options ScanOptions) CellScanner { + generic := func(row int) (driver.Value, error) { + return scanCell(col, row, loc, keys, options) + } + if options.GeospatialBinary || options.DecimalAsFloat { + return generic + } + var read CellScanner + switch column := col.(type) { + case *array.Boolean: + var values []byte + if buffer := column.Data().Buffers()[1]; buffer != nil { + values = buffer.Bytes() + } + offset := column.Data().Offset() + read = func(row int) (driver.Value, error) { return bitutil.BitIsSet(values, offset+row), nil } + case *array.Int8: + read = bindValues(column.Values()) + case *array.Int16: + read = bindValues(column.Values()) + case *array.Int32: + read = bindValues(column.Values()) + case *array.Int64: + read = bindValues(column.Values()) + case *array.Float32: + read = bindValues(column.Values()) + case *array.Float64: + read = bindValues(column.Values()) + case *array.Date32: + values := column.Values() + read = func(row int) (driver.Value, error) { return inLocation(values[row].ToTime(), loc), nil } + case *array.Date64: + values := column.Values() + read = func(row int) (driver.Value, error) { return inLocation(values[row].ToTime(), loc), nil } + case *array.Timestamp: + values := column.Values() + unit := column.DataType().(*arrow.TimestampType).Unit + read = func(row int) (driver.Value, error) { + return inLocation(timestampToTime(int64(values[row]), unit), loc), nil + } + case *array.String: + read = func(row int) (driver.Value, error) { return strings.Clone(column.Value(row)), nil } + case *array.Binary: + read = func(row int) (driver.Value, error) { return column.Value(row), nil } + default: + return generic + } + if col.NullN() == 0 { + return read + } + bitmap, offset := col.NullBitmapBytes(), col.Data().Offset() + return func(row int) (driver.Value, error) { + if !bitutil.BitIsSet(bitmap, offset+row) { + return nil, nil + } + return read(row) + } +} + +func bindValues[Value any](values []Value) CellScanner { + return func(row int) (driver.Value, error) { return values[row], nil } +} diff --git a/internal/arrowscan/bind_test.go b/internal/arrowscan/bind_test.go new file mode 100644 index 00000000..4b0804e4 --- /dev/null +++ b/internal/arrowscan/bind_test.go @@ -0,0 +1,185 @@ +package arrowscan + +import ( + "fmt" + "math" + "reflect" + "strings" + "testing" + "time" + + "github.com/apache/arrow-go/v18/arrow" + "github.com/apache/arrow-go/v18/arrow/array" + "github.com/apache/arrow-go/v18/arrow/memory" +) + +func TestBoundCellParity(t *testing.T) { + fixtures := []struct { + dataType arrow.DataType + values []string + }{ + {arrow.FixedWidthTypes.Boolean, []string{"true", "false"}}, + {arrow.PrimitiveTypes.Int8, []string{"-128", "127", "0"}}, + {arrow.PrimitiveTypes.Int16, []string{"-32768", "32767", "0"}}, + {arrow.PrimitiveTypes.Int32, []string{"-2147483648", "2147483647", "12345"}}, + {arrow.PrimitiveTypes.Int64, []string{"-9223372036854775808", "9223372036854775807", "12345"}}, + {arrow.PrimitiveTypes.Uint8, []string{"0", "255"}}, + {arrow.PrimitiveTypes.Uint16, []string{"0", "65535"}}, + {arrow.PrimitiveTypes.Uint32, []string{"0", "4294967295"}}, + {arrow.PrimitiveTypes.Uint64, []string{"0", "18446744073709551615"}}, + {arrow.PrimitiveTypes.Float32, []string{"0.1", "-0.0", `"NaN"`, `"+Inf"`, `"-Inf"`}}, + {arrow.PrimitiveTypes.Float64, []string{"0.1", "-0.0", `"NaN"`, `"+Inf"`, `"-Inf"`}}, + {arrow.BinaryTypes.String, []string{`""`, `"héllo\u0000世界"`, `"not a short string"`}}, + {arrow.BinaryTypes.LargeString, []string{`""`, `"héllo\u0000世界"`}}, + {arrow.BinaryTypes.Binary, []string{`""`, `"AAEC/w=="`}}, + {arrow.FixedWidthTypes.Date32, []string{`"0001-01-01"`, `"1970-01-01"`, `"9999-12-31"`}}, + {arrow.FixedWidthTypes.Date64, []string{`"0001-01-01"`, `"1970-01-01"`, `"9999-12-31"`}}, + {arrow.Null, []string{"null"}}, + {&arrow.Decimal128Type{Precision: 38, Scale: 2}, []string{`"-12345.67"`, `"999999999999999999999999999999999999.99"`}}, + {&arrow.Decimal128Type{Precision: 10, Scale: -2}, []string{`"12300"`, `"-45600"`}}, + {&arrow.Time32Type{Unit: arrow.Second}, []string{`"00:00:00"`, `"23:59:59"`}}, + {&arrow.Time64Type{Unit: arrow.Nanosecond}, []string{`"00:00:00"`, `"23:59:59.123456789"`}}, + {&arrow.DurationType{Unit: arrow.Microsecond}, []string{"-90061500000", "90061500000"}}, + {arrow.FixedWidthTypes.MonthInterval, []string{`{"months":-25}`, `{"months":25}`}}, + {arrow.FixedWidthTypes.DayTimeInterval, []string{`{"days":-1,"milliseconds":-1234}`, `{"days":2,"milliseconds":1234}`}}, + {arrow.ListOf(arrow.PrimitiveTypes.Int32), []string{"[1,null,3]", "[]"}}, + {arrow.LargeListOf(arrow.BinaryTypes.String), []string{`["x",null]`, "[]"}}, + {arrow.FixedSizeListOf(2, arrow.PrimitiveTypes.Int32), []string{"[1,null]", "[2,3]"}}, + {arrow.MapOf(arrow.BinaryTypes.String, arrow.PrimitiveTypes.Int32), []string{`[{"key":"x","value":1},{"key":"y","value":null}]`, "[]"}}, + {arrow.StructOf(arrow.Field{Name: "a", Type: arrow.PrimitiveTypes.Float32, Nullable: true}), []string{`{"a":0.1}`, `{"a":null}`}}, + {&arrow.FixedSizeBinaryType{ByteWidth: 1}, []string{`"AA=="`, `"AQ=="`}}, + } + for _, unit := range []arrow.TimeUnit{arrow.Second, arrow.Millisecond, arrow.Microsecond, arrow.Nanosecond} { + for _, zone := range []string{"", "UTC", "America/Los_Angeles"} { + fixtures = append(fixtures, struct { + dataType arrow.DataType + values []string + }{&arrow.TimestampType{Unit: unit, TimeZone: zone}, []string{"-123456789", "0", "123456789"}}) + } + } + for _, fixture := range fixtures { + t.Run(fixture.dataType.String(), func(t *testing.T) { + for _, nullMode := range []string{"none", "some", "all"} { + t.Run(nullMode, func(t *testing.T) { + values := make([]string, 40) + for row := range values { + values[row] = fixture.values[row%len(fixture.values)] + if nullMode == "all" || nullMode == "some" && row%7 == 0 { + values[row] = "null" + } + } + column, _, err := array.FromJSON(memory.DefaultAllocator, fixture.dataType, strings.NewReader("["+strings.Join(values, ",")+"]")) + if err != nil { + t.Fatal(err) + } + defer column.Release() + if nullMode == "none" && column.NullN() == 0 && len(column.Data().Buffers()) > 0 { + data := column.Data() + buffers := append([]*memory.Buffer(nil), data.Buffers()...) + buffers[0] = nil + withoutBitmap := array.NewData(data.DataType(), data.Len(), buffers, data.Children(), 0, data.Offset()) + noNulls := array.MakeFromData(withoutBitmap) + withoutBitmap.Release() + checkBoundParity(t, noNulls) + noNulls.Release() + } + for _, offset := range []int64{0, 1, 7, 9, 40} { + sliced := array.NewSlice(column, offset, 40) + checkBoundParity(t, sliced) + sliced.Release() + } + }) + } + }) + } +} + +func TestBoundGeospatialParity(t *testing.T) { + dataType := arrow.StructOf( + arrow.Field{Name: "srid", Type: arrow.PrimitiveTypes.Int32, Nullable: true}, + arrow.Field{Name: "wkb", Type: arrow.BinaryTypes.Binary, Nullable: true}, + ) + builder := array.NewStructBuilder(memory.DefaultAllocator, dataType) + defer builder.Release() + for _, srid := range []int32{4326, 3857} { + builder.Append(true) + builder.FieldBuilder(0).(*array.Int32Builder).Append(srid) + builder.FieldBuilder(1).(*array.BinaryBuilder).Append([]byte{1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 240, 63, 0, 0, 0, 0, 0, 0, 0, 64}) + } + builder.AppendNull() + column := builder.NewArray() + defer column.Release() + checkBoundParity(t, column) +} + +func checkBoundParity(t *testing.T, column arrow.Array) { + t.Helper() + for _, location := range []*time.Location{nil, time.UTC, time.FixedZone("session", -7*3600)} { + for _, options := range []ScanOptions{{}, {DecimalAsFloat: true}, {GeospatialBinary: true}, {DecimalAsFloat: true, GeospatialBinary: true}} { + keys := NewStructKeyCache() + read := BindCellScanner(column, location, keys, options) + for row := 0; row < column.Len(); row++ { + want, wantErr := ScanCellCachedWithOptions(column, row, location, keys, options) + got, gotErr := read(row) + if fmt.Sprint(gotErr) != fmt.Sprint(wantErr) { + t.Fatalf("row %d options %+v: error %v, want %v", row, options, gotErr, wantErr) + } + equal := reflect.DeepEqual(got, want) + switch value := want.(type) { + case float32: + actual, ok := got.(float32) + equal = ok && math.Float32bits(actual) == math.Float32bits(value) + case float64: + actual, ok := got.(float64) + equal = ok && math.Float64bits(actual) == math.Float64bits(value) + } + if !equal { + t.Fatalf("row %d options %+v: %T(%#v), want %T(%#v)", row, options, got, got, want, want) + } + } + } + } +} + +func TestBoundStringOutlivesArray(t *testing.T) { + const text = "a string retained after the Rust-owned Arrow batch is released" + pool := overwriteOnFreeAllocator{memory.NewGoAllocator()} + for _, nulls := range []bool{false, true} { + builder := array.NewStringBuilder(pool) + builder.Append(text) + if nulls { + builder.AppendNull() + } + column := builder.NewArray() + builder.Release() + read := BindCellScanner(column, nil, nil, ScanOptions{}) + got, err := read(0) + column.Release() + if err != nil || got != text { + t.Fatalf("got %q, %v after releasing batch", got, err) + } + } +} + +func TestBoundTimestampExtremes(t *testing.T) { + for _, unit := range []arrow.TimeUnit{arrow.Second, arrow.Millisecond, arrow.Microsecond} { + builder := array.NewTimestampBuilder(memory.DefaultAllocator, &arrow.TimestampType{Unit: unit, TimeZone: "UTC"}) + for _, instant := range []time.Time{ + time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC), + time.Date(9999, 12, 31, 23, 59, 59, 0, time.UTC), + } { + value := instant.Unix() + if unit == arrow.Millisecond { + value = instant.UnixMilli() + } + if unit == arrow.Microsecond { + value = instant.UnixMicro() + } + builder.Append(arrow.Timestamp(value)) + } + column := builder.NewArray() + builder.Release() + checkBoundParity(t, column) + column.Release() + } +} diff --git a/internal/backend/kernel/rows.go b/internal/backend/kernel/rows.go index de328427..954c88cf 100644 --- a/internal/backend/kernel/rows.go +++ b/internal/backend/kernel/rows.go @@ -81,7 +81,9 @@ type kernelRows struct { // keyCache memoizes struct field-name JSON keys for this result set so // per-row rendering doesn't re-marshal constant names. Scoped to this Rows // (freed with it) — not a process-global, which would leak. - keyCache *arrowscan.StructKeyCache + keyCache *arrowscan.StructKeyCache + cells []arrowscan.CellScanner + cellsBound bool } // newKernelRows fetches the schema up front (for Columns()) and returns the row @@ -209,6 +211,8 @@ func (r *kernelRows) Close() error { return nil } r.closed = true + r.cells = nil + r.cellsBound = false closeStart := time.Now() // Release the detached results context so an aborted Close doesn't leak it. if r.cancel != nil { @@ -261,16 +265,11 @@ func (r *kernelRows) next(dest []driver.Value) error { return err } } - rec := r.cur + if !r.cellsBound { + r.bindCells() + } for c := 0; c < len(dest); c++ { - location := r.op.location - if r.ntz[c] { - location = time.UTC - } - v, err := arrowscan.ScanCellCachedWithOptions(rec.Column(c), r.rowInCur, location, r.keyCache, arrowscan.ScanOptions{ - DecimalAsFloat: r.op.decimalAsFloat, - GeospatialBinary: r.geoBinary[c], - }) + v, err := r.cells[c](r.rowInCur) if err != nil { return fmt.Errorf("kernel: scan col %d (%s): %w", c, r.cols[c], err) } @@ -280,9 +279,28 @@ func (r *kernelRows) next(dest []driver.Value) error { return nil } +func (r *kernelRows) bindCells() { + if len(r.cells) != int(r.cur.NumCols()) { + r.cells = make([]arrowscan.CellScanner, r.cur.NumCols()) + } + for column := range r.cells { + location := r.op.location + if r.ntz[column] { + location = time.UTC + } + r.cells[column] = arrowscan.BindCellScanner(r.cur.Column(column), location, r.keyCache, arrowscan.ScanOptions{ + DecimalAsFloat: r.op.decimalAsFloat, + GeospatialBinary: r.geoBinary[column], + }) + } + r.cellsBound = true +} + // nextBatch pulls the next Arrow batch. A released array (release==NULL) is the // kernel's end-of-stream sentinel. func (r *kernelRows) nextBatch() error { + clear(r.cells) + r.cellsBound = false // Stop pulling once Close cancels r.ctx; r.ctx is detached from the caller's // deadline, so this fires on abort, not on a submit-gating timeout. It does NOT // interrupt an in-flight C fetch (the kernel exposes no per-download timeout). diff --git a/internal/backend/kernel/rows_bench_test.go b/internal/backend/kernel/rows_bench_test.go new file mode 100644 index 00000000..297ea3bb --- /dev/null +++ b/internal/backend/kernel/rows_bench_test.go @@ -0,0 +1,98 @@ +//go:build cgo && databricks_kernel + +package kernel + +import ( + "database/sql/driver" + "fmt" + "strings" + "testing" + "time" + + "github.com/apache/arrow-go/v18/arrow" + "github.com/apache/arrow-go/v18/arrow/array" + "github.com/apache/arrow-go/v18/arrow/memory" + "github.com/databricks/databricks-sql-go/v2/internal/arrowscan" +) + +func benchmarkRecord(b *testing.B, types []arrow.DataType, count int, nulls bool) arrow.RecordBatch { + b.Helper() + fields := make([]arrow.Field, len(types)) + columns := make([]arrow.Array, len(types)) + for column, dataType := range types { + fields[column] = arrow.Field{Name: fmt.Sprint(column), Type: dataType, Nullable: true} + values := make([]string, count) + for row := range values { + value := "12345" + switch dataType.ID() { + case arrow.BOOL: + value = "true" + case arrow.FLOAT32, arrow.FLOAT64: + value = "123.456" + case arrow.STRING: + value = `"catalog-sales-value"` + case arrow.DECIMAL128: + value = `"12345.67"` + } + if nulls && row%20 == 0 { + value = "null" + } + values[row] = value + } + columnArray, _, err := array.FromJSON(memory.DefaultAllocator, dataType, strings.NewReader("["+strings.Join(values, ",")+"]")) + if err != nil { + b.Fatal(err) + } + columns[column] = columnArray + defer columnArray.Release() + } + return array.NewRecordBatch(arrow.NewSchema(fields, nil), columns, int64(count)) +} + +func BenchmarkKernelRows(b *testing.B) { + decimalType := &arrow.Decimal128Type{Precision: 18, Scale: 2} + catalog := make([]arrow.DataType, 0, 34) + for column := 0; column < 18; column++ { + catalog = append(catalog, arrow.PrimitiveTypes.Int32) + } + catalog = append(catalog, arrow.PrimitiveTypes.Int64) + withoutDecimals := append([]arrow.DataType(nil), catalog...) + for column := 0; column < 15; column++ { + catalog = append(catalog, decimalType) + } + scenarios := []struct { + name string + types []arrow.DataType + }{ + {"catalog", catalog}, + {"catalog-no-decimals", withoutDecimals}, + {"boolean", []arrow.DataType{arrow.FixedWidthTypes.Boolean}}, + {"int32", []arrow.DataType{arrow.PrimitiveTypes.Int32}}, + {"float32", []arrow.DataType{arrow.PrimitiveTypes.Float32}}, + {"float64", []arrow.DataType{arrow.PrimitiveTypes.Float64}}, + {"string", []arrow.DataType{arrow.BinaryTypes.String}}, + } + for _, scenario := range scenarios { + for _, nulls := range []bool{false, true} { + b.Run(fmt.Sprintf("%s/nulls=%t", scenario.name, nulls), func(b *testing.B) { + record := benchmarkRecord(b, scenario.types, 4096, nulls) + defer record.Release() + destination := make([]driver.Value, len(scenario.types)) + ntz := make([]bool, len(scenario.types)) + geoBinary := make([]bool, len(scenario.types)) + operation := &kernelOp{location: time.UTC} + keys := arrowscan.NewStructKeyCache() + b.ReportAllocs() + b.ResetTimer() + for b.Loop() { + rows := kernelRows{cur: record, op: operation, ntz: ntz, geoBinary: geoBinary, keyCache: keys} + for row := 0; row < 4096; row++ { + if err := rows.next(destination); err != nil { + b.Fatal(err) + } + } + } + }) + } + } +} diff --git a/internal/backend/kernel/rows_bound_test.go b/internal/backend/kernel/rows_bound_test.go new file mode 100644 index 00000000..db1cbeee --- /dev/null +++ b/internal/backend/kernel/rows_bound_test.go @@ -0,0 +1,100 @@ +//go:build cgo && databricks_kernel + +package kernel + +import ( + "context" + "database/sql/driver" + "io" + "testing" + "time" + + "github.com/apache/arrow-go/v18/arrow" + "github.com/apache/arrow-go/v18/arrow/array" + "github.com/apache/arrow-go/v18/arrow/memory" + "github.com/databricks/databricks-sql-go/v2/internal/arrowscan" + "github.com/stretchr/testify/require" +) + +func TestBoundRowsBatchLifecycle(t *testing.T) { + pool := memory.NewCheckedAllocator(memory.DefaultAllocator) + defer pool.AssertSize(t, 0) + builder := array.NewInt32Builder(pool) + builder.AppendValues([]int32{300, 400}, nil) + first := builder.NewArray() + builder.AppendValues([]int32{0, -700}, []bool{false, true}) + second := builder.NewArray() + builder.Release() + schema := arrow.NewSchema([]arrow.Field{{Name: "value", Type: arrow.PrimitiveTypes.Int32}}, nil) + ctx, cancel := context.WithCancel(context.Background()) + rows := &kernelRows{ctx: ctx, cancel: cancel, op: &kernelOp{location: time.UTC}, + cols: []string{"value"}, ntz: []bool{false}, geoBinary: []bool{false}, + cur: array.NewRecordBatch(schema, []arrow.Array{first}, 2), keyCache: arrowscan.NewStructKeyCache()} + first.Release() + require.Nil(t, rows.cells) + destination := make([]driver.Value, 1) + require.NoError(t, rows.Next(destination)) + require.Equal(t, int32(300), destination[0]) + require.True(t, rows.cellsBound) + reader := rows.cells[0] + readerCalls := 0 + rows.cells[0] = func(row int) (driver.Value, error) { + readerCalls++ + return reader(row) + } + require.NoError(t, rows.Next(destination)) + require.Equal(t, int32(400), destination[0]) + require.Equal(t, 1, readerCalls) + cancel() + require.ErrorIs(t, rows.nextBatch(), context.Canceled) + require.False(t, rows.cellsBound) + require.Nil(t, rows.cells[0]) + rows.cur.Release() + rows.cur = array.NewRecordBatch(schema, []arrow.Array{second}, 2) + second.Release() + rows.rowInCur = 0 + require.NoError(t, rows.Next(destination)) + require.Nil(t, destination[0]) + require.NoError(t, rows.Next(destination)) + require.Equal(t, int32(-700), destination[0]) + rows.op = nil + require.NoError(t, rows.Close()) + require.Nil(t, rows.cells) + require.False(t, rows.cellsBound) + require.NoError(t, rows.Close()) + require.ErrorIs(t, rows.Next(destination), io.EOF) +} + +func TestBoundRowsLazyClose(t *testing.T) { + builder := array.NewBooleanBuilder(memory.DefaultAllocator) + builder.Append(true) + column := builder.NewArray() + builder.Release() + defer column.Release() + schema := arrow.NewSchema([]arrow.Field{{Name: "value", Type: arrow.FixedWidthTypes.Boolean}}, nil) + rows := &kernelRows{cur: array.NewRecordBatch(schema, []arrow.Array{column}, 1)} + require.Nil(t, rows.cells) + require.NoError(t, rows.Close()) + require.Nil(t, rows.cells) +} + +func TestBoundRowsFallbackError(t *testing.T) { + builder := array.NewFixedSizeBinaryBuilder(memory.DefaultAllocator, &arrow.FixedSizeBinaryType{ByteWidth: 1}) + builder.AppendNull() + builder.Append([]byte{42}) + column := builder.NewArray() + builder.Release() + defer column.Release() + schema := arrow.NewSchema([]arrow.Field{{Name: "unsupported", Type: column.DataType()}}, nil) + record := array.NewRecordBatch(schema, []arrow.Array{column}, 2) + defer record.Release() + rows := &kernelRows{cur: record, op: &kernelOp{}, cols: []string{"unsupported"}, ntz: []bool{false}, geoBinary: []bool{false}} + destination := make([]driver.Value, 1) + require.NoError(t, rows.Next(destination)) + require.Nil(t, destination[0]) + _, scanError := arrowscan.ScanCell(column, 1, nil) + err := rows.Next(destination) + require.EqualError(t, err, "kernel: scan col 0 (unsupported): "+scanError.Error()) + require.Same(t, err, rows.iterationErr) + require.Equal(t, 1, rows.rowInCur) +} From 01807137fb91db8a8433777d0eaa84a90afab7eb Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 27 Nov 2026 06:06:04 +0000 Subject: [PATCH 2/4] Keep scalar readers fast with decimal conversion enabled Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- internal/arrowscan/bind.go | 2 +- internal/arrowscan/bind_test.go | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/internal/arrowscan/bind.go b/internal/arrowscan/bind.go index d64d5024..ec7f0127 100644 --- a/internal/arrowscan/bind.go +++ b/internal/arrowscan/bind.go @@ -19,7 +19,7 @@ func BindCellScanner(col arrow.Array, loc *time.Location, keys *StructKeyCache, generic := func(row int) (driver.Value, error) { return scanCell(col, row, loc, keys, options) } - if options.GeospatialBinary || options.DecimalAsFloat { + if options.GeospatialBinary { return generic } var read CellScanner diff --git a/internal/arrowscan/bind_test.go b/internal/arrowscan/bind_test.go index 4b0804e4..38dae27f 100644 --- a/internal/arrowscan/bind_test.go +++ b/internal/arrowscan/bind_test.go @@ -183,3 +183,20 @@ func TestBoundTimestampExtremes(t *testing.T) { column.Release() } } + +func TestBoundEmptyColumns(t *testing.T) { + for _, dataType := range []arrow.DataType{ + arrow.FixedWidthTypes.Boolean, arrow.PrimitiveTypes.Int8, + arrow.PrimitiveTypes.Int16, arrow.PrimitiveTypes.Int32, + arrow.PrimitiveTypes.Int64, arrow.PrimitiveTypes.Float32, + arrow.PrimitiveTypes.Float64, arrow.BinaryTypes.String, arrow.BinaryTypes.Binary, + arrow.FixedWidthTypes.Date32, arrow.FixedWidthTypes.Date64, + &arrow.TimestampType{Unit: arrow.Microsecond}, + } { + builder := array.NewBuilder(memory.DefaultAllocator, dataType) + column := builder.NewArray() + builder.Release() + checkBoundParity(t, column) + column.Release() + } +} From f77dbee656d548c82ec666584fba25a092b4d8bd Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 27 Nov 2026 06:19:29 +0000 Subject: [PATCH 3/4] Test decimal options through bound kernel rows Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- internal/backend/kernel/rows_bound_test.go | 27 ++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/internal/backend/kernel/rows_bound_test.go b/internal/backend/kernel/rows_bound_test.go index db1cbeee..5a2e742d 100644 --- a/internal/backend/kernel/rows_bound_test.go +++ b/internal/backend/kernel/rows_bound_test.go @@ -6,6 +6,7 @@ import ( "context" "database/sql/driver" "io" + "strings" "testing" "time" @@ -78,6 +79,32 @@ func TestBoundRowsLazyClose(t *testing.T) { require.Nil(t, rows.cells) } +func TestBoundRowsDecimalOption(t *testing.T) { + decimalType := &arrow.Decimal128Type{Precision: 5, Scale: 2} + decimal, _, err := array.FromJSON(memory.DefaultAllocator, decimalType, strings.NewReader(`["12.50",null]`)) + require.NoError(t, err) + defer decimal.Release() + integer, _, err := array.FromJSON(memory.DefaultAllocator, arrow.PrimitiveTypes.Int32, strings.NewReader(`[12345,null]`)) + require.NoError(t, err) + defer integer.Release() + schema := arrow.NewSchema([]arrow.Field{{Name: "decimal", Type: decimalType}, {Name: "integer", Type: arrow.PrimitiveTypes.Int32}}, nil) + record := array.NewRecordBatch(schema, []arrow.Array{decimal, integer}, 2) + defer record.Release() + for _, asFloat := range []bool{false, true} { + rows := &kernelRows{cur: record, op: &kernelOp{decimalAsFloat: asFloat}, + cols: []string{"decimal", "integer"}, ntz: []bool{false, false}, geoBinary: []bool{false, false}} + destination := make([]driver.Value, 2) + require.NoError(t, rows.Next(destination)) + var want driver.Value = "12.50" + if asFloat { + want = float64(12.5) + } + require.Equal(t, []driver.Value{want, int32(12345)}, destination) + require.NoError(t, rows.Next(destination)) + require.Equal(t, []driver.Value{nil, nil}, destination) + } +} + func TestBoundRowsFallbackError(t *testing.T) { builder := array.NewFixedSizeBinaryBuilder(memory.DefaultAllocator, &arrow.FixedSizeBinaryType{ByteWidth: 1}) builder.AppendNull() From cf3e9f98df58b3ecf197c812216e9bff555b374b Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 27 Nov 2026 07:22:40 +0000 Subject: [PATCH 4/4] Address typed-reader review guards and C Data coverage Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- internal/arrowscan/arrowscan.go | 9 +- internal/arrowscan/bind.go | 13 +-- internal/arrowscan/bind_cdata_test.go | 96 ++++++++++++++++++++++ internal/arrowscan/bind_test.go | 20 +++++ internal/backend/kernel/rows.go | 4 +- internal/backend/kernel/rows_bench_test.go | 6 +- internal/backend/kernel/rows_bound_test.go | 20 +++++ 7 files changed, 155 insertions(+), 13 deletions(-) create mode 100644 internal/arrowscan/bind_cdata_test.go diff --git a/internal/arrowscan/arrowscan.go b/internal/arrowscan/arrowscan.go index 52a9f20d..d6beda14 100644 --- a/internal/arrowscan/arrowscan.go +++ b/internal/arrowscan/arrowscan.go @@ -121,8 +121,8 @@ func ScanCellCached(col arrow.Array, row int, loc *time.Location, keys *StructKe // fieldlessLocation applies IsTimestampNTZField's zone-less fallback for the // entry points that receive only an array, not its schema Field: a top-level // timestamp with an empty TimeZone is treated as TIMESTAMP_NTZ and scanned in -// UTC. Callers that know the Field (the kernel rows via -// ScanCellCachedWithOptions) decide NTZ from its metadata and pass loc directly. +// UTC. Callers that know the Field (the kernel rows via BindCellScanner) decide +// NTZ from its metadata and pass loc directly. func fieldlessLocation(col arrow.Array, loc *time.Location) *time.Location { if IsTimestampNTZField(arrow.Field{Type: col.DataType()}) { return time.UTC @@ -146,8 +146,8 @@ type ScanOptions struct { GeospatialBinary bool } -// ScanCellCachedWithOptions is the full scanner entry point used by the kernel -// rows implementation. Callers that do not need result-specific adaptations +// ScanCellCachedWithOptions is the one-shot counterpart to BindCellScanner, +// which the kernel rows implementation uses. Callers without result adaptations // should continue to use ScanCellCached. Unlike the field-less entry points, loc // is authoritative here: the caller decides TIMESTAMP_NTZ from the schema Field // (IsTimestampNTZField) and passes time.UTC for an NTZ column. @@ -165,6 +165,7 @@ func scanCell(col arrow.Array, row int, loc *time.Location, keys *StructKeyCache switch c := col.(type) { case *array.Null: return nil, nil + // Keep scalar results in sync with the bound readers in bind.go. case *array.Boolean: return c.Value(row), nil case *array.Int8: diff --git a/internal/arrowscan/bind.go b/internal/arrowscan/bind.go index ec7f0127..93603596 100644 --- a/internal/arrowscan/bind.go +++ b/internal/arrowscan/bind.go @@ -16,11 +16,10 @@ type CellScanner func(row int) (driver.Value, error) // BindCellScanner resolves a column's scalar reader and null bitmap once per // batch. Like ScanCellCachedWithOptions, loc is authoritative for timestamps. func BindCellScanner(col arrow.Array, loc *time.Location, keys *StructKeyCache, options ScanOptions) CellScanner { - generic := func(row int) (driver.Value, error) { - return scanCell(col, row, loc, keys, options) - } if options.GeospatialBinary { - return generic + return func(row int) (driver.Value, error) { + return scanCell(col, row, loc, keys, options) + } } var read CellScanner switch column := col.(type) { @@ -60,9 +59,11 @@ func BindCellScanner(col arrow.Array, loc *time.Location, keys *StructKeyCache, case *array.Binary: read = func(row int) (driver.Value, error) { return column.Value(row), nil } default: - return generic + return func(row int) (driver.Value, error) { + return scanCell(col, row, loc, keys, options) + } } - if col.NullN() == 0 { + if col.NullN() == 0 || len(col.NullBitmapBytes()) == 0 { return read } bitmap, offset := col.NullBitmapBytes(), col.Data().Offset() diff --git a/internal/arrowscan/bind_cdata_test.go b/internal/arrowscan/bind_cdata_test.go new file mode 100644 index 00000000..24e9e0c5 --- /dev/null +++ b/internal/arrowscan/bind_cdata_test.go @@ -0,0 +1,96 @@ +//go:build cgo + +package arrowscan + +import ( + "strings" + "testing" + + "github.com/apache/arrow-go/v18/arrow" + "github.com/apache/arrow-go/v18/arrow/array" + "github.com/apache/arrow-go/v18/arrow/cdata" + "github.com/apache/arrow-go/v18/arrow/memory" + "github.com/apache/arrow-go/v18/arrow/memory/mallocator" +) + +func TestBoundCellCDataParity(t *testing.T) { + fixtures := []struct { + name string + dataType arrow.DataType + values []string + }{ + {"bool", arrow.FixedWidthTypes.Boolean, []string{"true", "false"}}, + {"int8", arrow.PrimitiveTypes.Int8, []string{"-128", "127"}}, + {"int16", arrow.PrimitiveTypes.Int16, []string{"-32768", "32767"}}, + {"int32", arrow.PrimitiveTypes.Int32, []string{"-12345", "67890"}}, + {"int64", arrow.PrimitiveTypes.Int64, []string{"-9223372036854775808", "9223372036854775807"}}, + {"float32", arrow.PrimitiveTypes.Float32, []string{"0.1", "-0.0"}}, + {"float64", arrow.PrimitiveTypes.Float64, []string{"0.1", "-0.0"}}, + {"date32", arrow.FixedWidthTypes.Date32, []string{`"0001-01-01"`, `"9999-12-31"`}}, + {"date64", arrow.FixedWidthTypes.Date64, []string{`"0001-01-01"`, `"9999-12-31"`}}, + {"timestamp", &arrow.TimestampType{Unit: arrow.Microsecond, TimeZone: "UTC"}, []string{"-123456789", "123456789"}}, + {"string", arrow.BinaryTypes.String, []string{`""`, `"héllo\u0000世界"`}}, + {"binary", arrow.BinaryTypes.Binary, []string{`""`, `"AAEC/w=="`}}, + {"decimal", &arrow.Decimal128Type{Precision: 10, Scale: 2}, []string{`"-123.45"`, `"678.90"`}}, + {"list", arrow.ListOf(arrow.PrimitiveTypes.Int32), []string{"[1,null,3]", "[]"}}, + } + for _, mode := range []string{"nullable", "no-bitmap"} { + t.Run(mode, func(t *testing.T) { + pool := memory.NewCheckedAllocator(mallocator.NewMallocator()) + defer pool.AssertSize(t, 0) + fields := make([]arrow.Field, len(fixtures)) + columns := make([]arrow.Array, len(fixtures)) + for index, fixture := range fixtures { + values := make([]string, 40) + for row := range values { + values[row] = fixture.values[row%len(fixture.values)] + if mode == "nullable" && row%5 == 0 { + values[row] = "null" + } + } + column, _, err := array.FromJSON(pool, fixture.dataType, strings.NewReader("["+strings.Join(values, ",")+"]")) + if err != nil { + t.Fatal(err) + } + if mode == "no-bitmap" { + data := column.Data() + buffers := append([]*memory.Buffer(nil), data.Buffers()...) + buffers[0] = nil + withoutBitmap := array.NewData(data.DataType(), data.Len(), buffers, data.Children(), 0, data.Offset()) + column.Release() + column = array.MakeFromData(withoutBitmap) + withoutBitmap.Release() + } + defer column.Release() + fields[index] = arrow.Field{Name: fixture.name, Type: fixture.dataType, Nullable: true} + columns[index] = column + } + record := array.NewRecordBatch(arrow.NewSchema(fields, nil), columns, 40) + defer record.Release() + sliced := record.NewSlice(7, 31) + defer sliced.Release() + var exportedArray cdata.CArrowArray + var exportedSchema cdata.CArrowSchema + cdata.ExportArrowRecordBatch(sliced, &exportedArray, &exportedSchema) + defer cdata.ReleaseCArrowArray(&exportedArray) + defer cdata.ReleaseCArrowSchema(&exportedSchema) + imported, err := cdata.ImportCRecordBatch(&exportedArray, &exportedSchema) + if err != nil { + t.Fatal(err) + } + defer imported.Release() + if imported.NumRows() != sliced.NumRows() || imported.NumCols() != sliced.NumCols() { + t.Fatal("C Data round-trip changed the record shape") + } + for _, column := range imported.Columns() { + if column.Data().Offset() != 7 { + t.Fatalf("C Data round-trip lost the slice offset: %d", column.Data().Offset()) + } + if mode == "no-bitmap" && len(column.NullBitmapBytes()) != 0 { + t.Fatal("C Data round-trip introduced a validity bitmap") + } + checkBoundParity(t, column) + } + }) + } +} diff --git a/internal/arrowscan/bind_test.go b/internal/arrowscan/bind_test.go index 38dae27f..1d0b01ec 100644 --- a/internal/arrowscan/bind_test.go +++ b/internal/arrowscan/bind_test.go @@ -94,6 +94,26 @@ func TestBoundCellParity(t *testing.T) { } } +func TestBoundCellNoValidityBitmap(t *testing.T) { + builder := array.NewInt32Builder(memory.DefaultAllocator) + builder.AppendValues([]int32{12345, -67890}, nil) + column := builder.NewArray() + builder.Release() + defer column.Release() + + data := column.Data() + buffers := append([]*memory.Buffer(nil), data.Buffers()...) + buffers[0] = nil + withoutBitmap := array.NewData(data.DataType(), data.Len(), buffers, data.Children(), 1, data.Offset()) + defer withoutBitmap.Release() + noBitmap := array.MakeFromData(withoutBitmap) + defer noBitmap.Release() + if noBitmap.NullN() != 1 || len(noBitmap.NullBitmapBytes()) != 0 { + t.Fatal("expected a nonzero null count without a validity bitmap") + } + checkBoundParity(t, noBitmap) +} + func TestBoundGeospatialParity(t *testing.T) { dataType := arrow.StructOf( arrow.Field{Name: "srid", Type: arrow.PrimitiveTypes.Int32, Nullable: true}, diff --git a/internal/backend/kernel/rows.go b/internal/backend/kernel/rows.go index 954c88cf..0b9f87ce 100644 --- a/internal/backend/kernel/rows.go +++ b/internal/backend/kernel/rows.go @@ -280,8 +280,8 @@ func (r *kernelRows) next(dest []driver.Value) error { } func (r *kernelRows) bindCells() { - if len(r.cells) != int(r.cur.NumCols()) { - r.cells = make([]arrowscan.CellScanner, r.cur.NumCols()) + if len(r.cells) != len(r.cols) { + r.cells = make([]arrowscan.CellScanner, len(r.cols)) } for column := range r.cells { location := r.op.location diff --git a/internal/backend/kernel/rows_bench_test.go b/internal/backend/kernel/rows_bench_test.go index 297ea3bb..bf0dd8e9 100644 --- a/internal/backend/kernel/rows_bench_test.go +++ b/internal/backend/kernel/rows_bench_test.go @@ -78,6 +78,10 @@ func BenchmarkKernelRows(b *testing.B) { record := benchmarkRecord(b, scenario.types, 4096, nulls) defer record.Release() destination := make([]driver.Value, len(scenario.types)) + columns := make([]string, len(scenario.types)) + for column := range columns { + columns[column] = record.ColumnName(column) + } ntz := make([]bool, len(scenario.types)) geoBinary := make([]bool, len(scenario.types)) operation := &kernelOp{location: time.UTC} @@ -85,7 +89,7 @@ func BenchmarkKernelRows(b *testing.B) { b.ReportAllocs() b.ResetTimer() for b.Loop() { - rows := kernelRows{cur: record, op: operation, ntz: ntz, geoBinary: geoBinary, keyCache: keys} + rows := kernelRows{cur: record, op: operation, cols: columns, ntz: ntz, geoBinary: geoBinary, keyCache: keys} for row := 0; row < 4096; row++ { if err := rows.next(destination); err != nil { b.Fatal(err) diff --git a/internal/backend/kernel/rows_bound_test.go b/internal/backend/kernel/rows_bound_test.go index 5a2e742d..bb4edaa2 100644 --- a/internal/backend/kernel/rows_bound_test.go +++ b/internal/backend/kernel/rows_bound_test.go @@ -105,6 +105,26 @@ func TestBoundRowsDecimalOption(t *testing.T) { } } +func TestBoundRowsSchemaColumns(t *testing.T) { + builder := array.NewInt32Builder(memory.DefaultAllocator) + builder.Append(12345) + column := builder.NewArray() + builder.Release() + defer column.Release() + schema := arrow.NewSchema([]arrow.Field{ + {Name: "value", Type: arrow.PrimitiveTypes.Int32}, + {Name: "extra", Type: arrow.PrimitiveTypes.Int32}, + }, nil) + record := array.NewRecordBatch(schema, []arrow.Array{column, column}, 1) + defer record.Release() + rows := &kernelRows{cur: record, op: &kernelOp{}, + cols: []string{"value"}, ntz: []bool{false}, geoBinary: []bool{false}} + destination := make([]driver.Value, 1) + require.NoError(t, rows.Next(destination)) + require.Equal(t, []driver.Value{int32(12345)}, destination) + require.Len(t, rows.cells, 1) +} + func TestBoundRowsFallbackError(t *testing.T) { builder := array.NewFixedSizeBinaryBuilder(memory.DefaultAllocator, &arrow.FixedSizeBinaryType{ByteWidth: 1}) builder.AppendNull()