From a7879e48188e3ffd3132a2eef0ef9a7b244468fa Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 27 Nov 2026 06:24:42 +0000 Subject: [PATCH 01/11] Bind Thrift scalar readers once per Arrow batch Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- CHANGELOG.md | 1 + internal/rows/arrowbased/arrowRows.go | 40 +--- internal/rows/arrowbased/arrowRows_test.go | 6 +- internal/rows/arrowbased/cellReaders.go | 94 ++++++++ internal/rows/arrowbased/cellReaders_test.go | 221 +++++++++++++++++++ internal/rows/arrowbased/columnValues.go | 4 +- 6 files changed, 331 insertions(+), 35 deletions(-) create mode 100644 internal/rows/arrowbased/cellReaders.go create mode 100644 internal/rows/arrowbased/cellReaders_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f17e4c9..ef56cd33 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### Driver changes +- Reduce Thrift row-scan CPU by binding scalar readers and null/type handling once per Arrow batch, without changing returned values. - **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/rows/arrowbased/arrowRows.go b/internal/rows/arrowbased/arrowRows.go index fae38538..097d86b6 100644 --- a/internal/rows/arrowbased/arrowRows.go +++ b/internal/rows/arrowbased/arrowRows.go @@ -64,7 +64,7 @@ type arrowRowScanner struct { currentBatch SparkArrowBatch // Currently loaded field values for a set of rows - rowValues RowValues + rowValues *rowValues // function to convert arrow timestamp when using native arrow format toTimestampFn timeStampFn @@ -207,6 +207,7 @@ func (ars *arrowRowScanner) ScanRow( if ars.location == nil { ars.location = time.UTC } + rowIndex := int(rowNumber - ars.rowValues.Start()) // loop over the destination slice filling in values for i := range destination { @@ -215,37 +216,15 @@ func (ars *arrowRowScanner) ScanRow( // if there is a corresponding column and the value for the specified row // is not null we put the value in the destination - if !ars.rowValues.IsNull(i, rowNumber) { - - col := ars.colInfo[i] - dbType := col.dbType - - if isIntervalType(dbType) && ars.UseArrowNativeIntervalTypes { - // not yet fully supported - ars.Error().Msg(errArrowRowsUnsupportedNativeType(dbType.String())) - return dbsqlerrint.NewDriverError(ars.ctx, errArrowRowsUnsupportedNativeType(dbType.String()), nil) - } - - // A top-level native-arrow DECIMAL column is returned as a lossless, - // scale-applied string so precision beyond float64 is preserved. - // Gated on the requested config (not merely the holder type) so that - // disabling native decimal keeps the prior float64 behavior even if - // the server-provided arrow schema carries a decimal128. Decimals - // nested in complex types take a different path: the complex - // container renders them losslessly via marshalScalar during JSON - // serialization, independent of this config gate. - // See databricks/databricks-sql-go#274 and #253. - if dbType == cli_service.TTypeId_DECIMAL_TYPE && ars.UseArrowNativeDecimal { - if s, ok := ars.rowValues.DecimalStringValue(i, rowNumber); ok { - destination[i] = s - continue - } - } - - // get the value from the column values holder + if i < len(ars.rowValues.readers) { var err1 error - destination[i], err1 = ars.rowValues.Value(i, rowNumber) + destination[i], err1 = ars.rowValues.readers[i](rowIndex) if err1 != nil { + col := ars.colInfo[i] + if err1 == errNativeInterval { + ars.Error().Msg(errArrowRowsUnsupportedNativeType(col.dbType.String())) + return dbsqlerrint.NewDriverError(ars.ctx, errArrowRowsUnsupportedNativeType(col.dbType.String()), nil) + } err = dbsqlerrint.NewDriverError(ars.ctx, errArrowRowsColumnValue(col.name), err1) } } @@ -331,6 +310,7 @@ func (ars *arrowRowScanner) loadBatchFor(rowNumber int64) dbsqlerr.DBError { // Update the delimiter in rowValues to reflect the currently loaded set of rows ars.rowValues.SetDelimiter(rowscanner.NewDelimiter(sar.Start(), sar.Count())) + ars.rowValues.bindReaders(ars.colInfo, ars.ArrowConfig, sar.Columns()) return nil } diff --git a/internal/rows/arrowbased/arrowRows_test.go b/internal/rows/arrowbased/arrowRows_test.go index 82aba722..8df169b4 100644 --- a/internal/rows/arrowbased/arrowRows_test.go +++ b/internal/rows/arrowbased/arrowRows_test.go @@ -249,8 +249,7 @@ func TestArrowRowScanner(t *testing.T) { var ok bool - rowValues, ok := ars.rowValues.(*rowValues) - assert.True(t, ok) + rowValues := ars.rowValues _, ok = rowValues.columnValueHolders[0].(*columnValuesTyped[*array.Boolean, bool]) assert.True(t, ok) @@ -325,8 +324,7 @@ func TestArrowRowScanner(t *testing.T) { var ok bool - rowValues, ok := ars.rowValues.(*rowValues) - assert.True(t, ok) + rowValues := ars.rowValues // timestamp _, ok = rowValues.columnValueHolders[8].(*timestampValueContainer) diff --git a/internal/rows/arrowbased/cellReaders.go b/internal/rows/arrowbased/cellReaders.go new file mode 100644 index 00000000..2748719c --- /dev/null +++ b/internal/rows/arrowbased/cellReaders.go @@ -0,0 +1,94 @@ +package arrowbased + +import ( + "errors" + + "github.com/apache/arrow-go/v18/arrow" + "github.com/apache/arrow-go/v18/arrow/array" + "github.com/apache/arrow-go/v18/arrow/bitutil" + "github.com/databricks/databricks-sql-go/v2/internal/cli_service" + "github.com/databricks/databricks-sql-go/v2/internal/config" +) + +type columnReader func(int) (any, error) + +var errNativeInterval = errors.New("unsupported native interval") + +func (rv *rowValues) bindReaders(columns []colInfo, cfg config.ArrowConfig, arrays []arrow.Array) { + if len(rv.readers) != len(rv.columnValueHolders) { + rv.readers = make([]columnReader, len(rv.columnValueHolders)) + } + for column, holder := range rv.columnValueHolders { + if holder == nil { + continue + } + read := columnReader(holder.Value) + var values arrow.Array + if column < len(arrays) { + read = scalarColumnReader(holder) + values = arrays[column] + } + if cfg.UseArrowNativeDecimal && columns[column].dbType == cli_service.TTypeId_DECIMAL_TYPE { + if decimal, ok := holder.(*decimal128Container); ok { + read = func(row int) (any, error) { return decimal.ValueString(row), nil } + } + } + if cfg.UseArrowNativeIntervalTypes && isIntervalType(columns[column].dbType) { + read = func(int) (any, error) { return nil, errNativeInterval } + } + if values != nil && values.NullN() == 0 { + rv.readers[column] = read + continue + } + if values != nil && len(values.NullBitmapBytes()) > 0 { + bitmap, offset := values.NullBitmapBytes(), values.Data().Offset() + rv.readers[column] = func(row int) (any, error) { + if bitutil.BitIsNotSet(bitmap, offset+row) { + return nil, nil + } + return read(row) + } + } else { + rv.readers[column] = func(row int) (any, error) { + if holder.IsNull(row) { + return nil, nil + } + return read(row) + } + } + } +} + +func scalarColumnReader(holder columnValues) columnReader { + switch column := holder.(type) { + case *columnValuesTyped[*array.Boolean, bool]: + values := column.holder + return func(row int) (any, error) { return values.Value(row), nil } + case *columnValuesTyped[*array.Int8, int8]: + values := column.holder + return func(row int) (any, error) { return values.Value(row), nil } + case *columnValuesTyped[*array.Int16, int16]: + values := column.holder + return func(row int) (any, error) { return values.Value(row), nil } + case *columnValuesTyped[*array.Int32, int32]: + values := column.holder + return func(row int) (any, error) { return values.Value(row), nil } + case *columnValuesTyped[*array.Int64, int64]: + values := column.holder + return func(row int) (any, error) { return values.Value(row), nil } + case *columnValuesTyped[*array.Float32, float32]: + values := column.holder + return func(row int) (any, error) { return values.Value(row), nil } + case *columnValuesTyped[*array.Float64, float64]: + values := column.holder + return func(row int) (any, error) { return values.Value(row), nil } + case *columnValuesTyped[*array.String, string]: + values := column.holder + return func(row int) (any, error) { return values.Value(row), nil } + case *columnValuesTyped[*array.Binary, []byte]: + values := column.holder + return func(row int) (any, error) { return values.Value(row), nil } + default: + return holder.Value + } +} diff --git a/internal/rows/arrowbased/cellReaders_test.go b/internal/rows/arrowbased/cellReaders_test.go new file mode 100644 index 00000000..9ae98b0c --- /dev/null +++ b/internal/rows/arrowbased/cellReaders_test.go @@ -0,0 +1,221 @@ +package arrowbased + +import ( + "context" + "database/sql/driver" + "fmt" + "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/stretchr/testify/require" + + "github.com/databricks/databricks-sql-go/v2/internal/arrowscan" + "github.com/databricks/databricks-sql-go/v2/internal/cli_service" + "github.com/databricks/databricks-sql-go/v2/internal/config" + "github.com/databricks/databricks-sql-go/v2/internal/rows/rowscanner" + dbsqllog "github.com/databricks/databricks-sql-go/v2/logger" +) + +func readerTestScanner(fields []arrow.Field, types []cli_service.TTypeId, cfg config.ArrowConfig, location *time.Location, batches ...[]arrow.Array) *arrowRowScanner { + schema := arrow.NewSchema(fields, nil) + iterator := &fakeBatchIterator{index: -1} + start := int64(41) + for _, columns := range batches { + count := int64(columns[0].Len()) + delimiter := rowscanner.NewDelimiter(start, count) + iterator.batches = append(iterator.batches, &sparkArrowBatch{ + Delimiter: delimiter, + arrowRecords: []SparkArrowRecord{&sparkArrowRecord{ + Delimiter: delimiter, RecordBatch: array.NewRecordBatch(schema, columns, count), + }}, + }) + start += count + } + infos := make([]colInfo, len(fields)) + for column := range fields { + infos[column] = colInfo{name: fields[column].Name, arrowType: fields[column].Type, dbType: types[column]} + } + return &arrowRowScanner{ + Delimiter: rowscanner.NewDelimiter(41, start-41), valueContainerMaker: &arrowValueContainerMaker{}, + ArrowConfig: cfg, arrowSchema: schema, colInfo: infos, location: location, + DBSQLLogger: dbsqllog.Logger, ctx: context.Background(), batchIterator: iterator, + toTimestampFn: func(value arrow.Timestamp) time.Time { return value.ToTime(arrow.Microsecond) }, + } +} + +func TestBoundColumnReaders(t *testing.T) { + for _, test := range []struct { + name string + dataType arrow.DataType + dbType cli_service.TTypeId + input string + expected any + }{ + {"bool", arrow.FixedWidthTypes.Boolean, cli_service.TTypeId_BOOLEAN_TYPE, "true", true}, + {"int8", arrow.PrimitiveTypes.Int8, cli_service.TTypeId_TINYINT_TYPE, "-97", int8(-97)}, + {"int16", arrow.PrimitiveTypes.Int16, cli_service.TTypeId_SMALLINT_TYPE, "-30258", int16(-30258)}, + {"int32", arrow.PrimitiveTypes.Int32, cli_service.TTypeId_INT_TYPE, "1234567890", int32(1234567890)}, + {"int64", arrow.PrimitiveTypes.Int64, cli_service.TTypeId_BIGINT_TYPE, "9223372036854775807", int64(9223372036854775807)}, + {"float32", arrow.PrimitiveTypes.Float32, cli_service.TTypeId_FLOAT_TYPE, "0.1", float32(0.1)}, + {"float64", arrow.PrimitiveTypes.Float64, cli_service.TTypeId_DOUBLE_TYPE, "0.1", float64(0.1)}, + {"string", arrow.BinaryTypes.String, cli_service.TTypeId_STRING_TYPE, "a\x00é🌎", "a\x00é🌎"}, + {"binary", arrow.BinaryTypes.Binary, cli_service.TTypeId_BINARY_TYPE, "AP+A", []byte{0, 255, 128}}, + {"decimal-string", arrow.BinaryTypes.String, cli_service.TTypeId_DECIMAL_TYPE, "1234567890123456789.9900", "1234567890123456789.9900"}, + {"date", arrow.FixedWidthTypes.Date32, cli_service.TTypeId_DATE_TYPE, "2026-11-27", time.Date(2026, 11, 27, 0, 0, 0, 0, time.UTC)}, + {"time32s", arrow.FixedWidthTypes.Time32s, cli_service.TTypeId_STRING_TYPE, "09:15:00", time.Date(1, 1, 1, 9, 15, 0, 0, time.UTC)}, + {"time32ms", arrow.FixedWidthTypes.Time32ms, cli_service.TTypeId_STRING_TYPE, "09:15:00.123", time.Date(1, 1, 1, 9, 15, 0, 123000000, time.UTC)}, + {"time64us", arrow.FixedWidthTypes.Time64us, cli_service.TTypeId_STRING_TYPE, "09:15:00.123456", time.Date(1, 1, 1, 9, 15, 0, 123456000, time.UTC)}, + {"time64ns", arrow.FixedWidthTypes.Time64ns, cli_service.TTypeId_STRING_TYPE, "09:15:00.123456789", time.Date(1, 1, 1, 9, 15, 0, 123456789, time.UTC)}, + {"timestamp", &arrow.TimestampType{Unit: arrow.Microsecond, TimeZone: "UTC"}, cli_service.TTypeId_TIMESTAMP_TYPE, "2026-11-27 09:15:00.123456Z", time.Date(2026, 11, 27, 9, 15, 0, 123456000, time.UTC)}, + {"timestamp-string", arrow.BinaryTypes.String, cli_service.TTypeId_TIMESTAMP_TYPE, "2026-11-27 09:15:00.123456", time.Date(2026, 11, 27, 9, 15, 0, 123456000, time.UTC)}, + {"interval-string", arrow.BinaryTypes.String, cli_service.TTypeId_INTERVAL_DAY_TIME_TYPE, "-8 00:00:00.000000000", "-8 00:00:00.000000000"}, + } { + for _, pattern := range []string{"no-nulls", "mixed", "all-null"} { + t.Run(test.name+"/"+pattern, func(t *testing.T) { + pool := memory.NewCheckedAllocator(memory.DefaultAllocator) + defer pool.AssertSize(t, 0) + builder := array.NewBuilder(pool, test.dataType) + defer builder.Release() + builder.AppendNull() + for row := 0; row < 3; row++ { + if pattern == "all-null" || pattern == "mixed" && row == 1 { + builder.AppendNull() + } else { + require.NoError(t, builder.AppendValueFromString(test.input)) + } + } + full := builder.NewArray() + defer full.Release() + values := array.NewSlice(full, 1, 4) + defer values.Release() + scanner := readerTestScanner([]arrow.Field{{Name: test.name, Type: test.dataType, Nullable: true}}, []cli_service.TTypeId{test.dbType}, config.ArrowConfig{UseArrowNativeDecimal: true}, time.UTC, []arrow.Array{values}) + defer scanner.Close() + destination := []driver.Value{"stale", "extra"} + for row := int64(0); row < 3; row++ { + require.NoError(t, scanner.ScanRow(destination, 41+row)) + require.Nil(t, destination[1]) + if values.IsNull(int(row)) { + require.Nil(t, destination[0]) + } else { + require.IsType(t, test.expected, destination[0]) + require.Equal(t, test.expected, destination[0]) + if test.dbType != cli_service.TTypeId_TIMESTAMP_TYPE { + parity, err := arrowscan.ScanCell(values, int(row), time.UTC) + require.NoError(t, err) + require.Equal(t, parity, destination[0]) + } + } + } + }) + } + } +} + +func TestBoundReadersRebindAndRelease(t *testing.T) { + pool := memory.NewCheckedAllocator(memory.DefaultAllocator) + defer pool.AssertSize(t, 0) + builder := array.NewInt32Builder(pool) + defer builder.Release() + var batches [][]arrow.Array + for batch := 0; batch < 3; batch++ { + builder.Append(int32(300 + batch)) + if batch == 1 { + builder.AppendNull() + } else { + builder.Append(int32(400 + batch)) + } + values := builder.NewArray() + defer values.Release() + batches = append(batches, []arrow.Array{values}) + } + scanner := readerTestScanner([]arrow.Field{{Name: "number", Type: arrow.PrimitiveTypes.Int32, Nullable: true}}, []cli_service.TTypeId{cli_service.TTypeId_INT_TYPE}, config.ArrowConfig{}, time.UTC, batches...) + destination := make([]driver.Value, 1) + for row, expected := range []any{int32(300), int32(400), int32(301), nil, int32(302), int32(402)} { + require.NoError(t, scanner.ScanRow(destination, 41+int64(row))) + require.Equal(t, expected, destination[0]) + } + scanner.Close() + require.Nil(t, scanner.rowValues.readers) + require.Equal(t, int32(402), destination[0]) +} + +func TestBoundNativeIntervalNullAndError(t *testing.T) { + for _, dbType := range []cli_service.TTypeId{cli_service.TTypeId_INTERVAL_DAY_TIME_TYPE, cli_service.TTypeId_INTERVAL_YEAR_MONTH_TYPE} { + t.Run(dbType.String(), func(t *testing.T) { + builder := array.NewStringBuilder(memory.DefaultAllocator) + defer builder.Release() + builder.AppendNull() + builder.Append("1") + values := builder.NewArray() + defer values.Release() + scanner := readerTestScanner([]arrow.Field{{Name: "interval", Type: arrow.BinaryTypes.String, Nullable: true}}, []cli_service.TTypeId{dbType}, config.ArrowConfig{UseArrowNativeIntervalTypes: true}, time.UTC, []arrow.Array{values}) + defer scanner.Close() + destination := []driver.Value{"stale"} + require.NoError(t, scanner.ScanRow(destination, 41)) + require.Nil(t, destination[0]) + err := scanner.ScanRow(destination, 42) + require.EqualError(t, err, "databricks: driver error: "+errArrowRowsUnsupportedNativeType(dbType.String())) + require.Nil(t, destination[0]) + }) + } +} + +func TestBoundDecimalConfig(t *testing.T) { + dataType := &arrow.Decimal128Type{Precision: 38, Scale: 2} + for _, native := range []bool{false, true} { + t.Run(fmt.Sprint(native), func(t *testing.T) { + builder := array.NewDecimal128Builder(memory.DefaultAllocator, dataType) + defer builder.Release() + require.NoError(t, builder.AppendValueFromString("1234567890123456789.99")) + builder.AppendNull() + values := builder.NewArray() + defer values.Release() + scanner := readerTestScanner([]arrow.Field{{Name: "decimal", Type: dataType, Nullable: true}}, []cli_service.TTypeId{cli_service.TTypeId_DECIMAL_TYPE}, config.ArrowConfig{UseArrowNativeDecimal: native}, time.UTC, []arrow.Array{values}) + defer scanner.Close() + destination := make([]driver.Value, 1) + require.NoError(t, scanner.ScanRow(destination, 41)) + if native { + require.Equal(t, "1234567890123456789.99", destination[0]) + } else { + require.Equal(t, values.(*array.Decimal128).Value(0).ToFloat64(2), destination[0]) + } + require.NoError(t, scanner.ScanRow(destination, 42)) + require.Nil(t, destination[0]) + }) + } +} + +func TestBoundTimestampLocation(t *testing.T) { + location := time.FixedZone("east", 9*3600) + wall := time.Date(2026, 11, 27, 9, 15, 0, 123456000, time.UTC) + for _, test := range []struct { + name string + zone string + metadata arrow.Metadata + expected time.Time + }{ + {"zoned", "UTC", arrow.Metadata{}, wall.In(location)}, + {"ntz", "", arrow.Metadata{}, wall}, + {"metadata-ntz", "UTC", arrow.MetadataFrom(map[string]string{"databricks.type_name": "TIMESTAMP_NTZ"}), wall}, + } { + t.Run(test.name, func(t *testing.T) { + dataType := &arrow.TimestampType{Unit: arrow.Microsecond, TimeZone: test.zone} + builder := array.NewTimestampBuilder(memory.DefaultAllocator, dataType) + defer builder.Release() + builder.Append(arrow.Timestamp(wall.UnixMicro())) + builder.AppendNull() + values := builder.NewArray() + defer values.Release() + scanner := readerTestScanner([]arrow.Field{{Name: "timestamp", Type: dataType, Nullable: true, Metadata: test.metadata}}, []cli_service.TTypeId{cli_service.TTypeId_TIMESTAMP_TYPE}, config.ArrowConfig{}, location, []arrow.Array{values}) + defer scanner.Close() + destination := make([]driver.Value, 1) + require.NoError(t, scanner.ScanRow(destination, 41)) + require.Equal(t, test.expected, destination[0]) + require.NoError(t, scanner.ScanRow(destination, 42)) + require.Nil(t, destination[0]) + }) + } +} diff --git a/internal/rows/arrowbased/columnValues.go b/internal/rows/arrowbased/columnValues.go index 25640030..63d2c5ea 100644 --- a/internal/rows/arrowbased/columnValues.go +++ b/internal/rows/arrowbased/columnValues.go @@ -31,18 +31,20 @@ type RowValues interface { SetDelimiter(d rowscanner.Delimiter) } -func NewRowValues(d rowscanner.Delimiter, holders []columnValues) RowValues { +func NewRowValues(d rowscanner.Delimiter, holders []columnValues) *rowValues { return &rowValues{Delimiter: d, columnValueHolders: holders} } type rowValues struct { rowscanner.Delimiter columnValueHolders []columnValues + readers []columnReader } var _ RowValues = (*rowValues)(nil) func (rv *rowValues) Close() { + rv.readers = nil // release any retained arrow arrays for i := range rv.columnValueHolders { if rv.columnValueHolders[i] != nil { From 361dafa6413124899dbfd28d07e24b1dd93ce037 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 27 Nov 2026 06:47:22 +0000 Subject: [PATCH 02/11] Validate bound readers and avoid redundant closures Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- internal/rows/arrowbased/cellReaders.go | 3 +- .../rows/arrowbased/cellReaders_bench_test.go | 89 +++++++++++++++++++ internal/rows/arrowbased/cellReaders_test.go | 51 +++++++++++ 3 files changed, 141 insertions(+), 2 deletions(-) create mode 100644 internal/rows/arrowbased/cellReaders_bench_test.go diff --git a/internal/rows/arrowbased/cellReaders.go b/internal/rows/arrowbased/cellReaders.go index 2748719c..9065c0c4 100644 --- a/internal/rows/arrowbased/cellReaders.go +++ b/internal/rows/arrowbased/cellReaders.go @@ -22,10 +22,9 @@ func (rv *rowValues) bindReaders(columns []colInfo, cfg config.ArrowConfig, arra if holder == nil { continue } - read := columnReader(holder.Value) + read := scalarColumnReader(holder) var values arrow.Array if column < len(arrays) { - read = scalarColumnReader(holder) values = arrays[column] } if cfg.UseArrowNativeDecimal && columns[column].dbType == cli_service.TTypeId_DECIMAL_TYPE { diff --git a/internal/rows/arrowbased/cellReaders_bench_test.go b/internal/rows/arrowbased/cellReaders_bench_test.go new file mode 100644 index 00000000..b099c18f --- /dev/null +++ b/internal/rows/arrowbased/cellReaders_bench_test.go @@ -0,0 +1,89 @@ +package arrowbased + +import ( + "context" + "database/sql/driver" + "fmt" + "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/cli_service" + "github.com/databricks/databricks-sql-go/v2/internal/rows/rowscanner" + dbsqllog "github.com/databricks/databricks-sql-go/v2/logger" +) + +func BenchmarkFactoryCells(benchmark *testing.B) { + for _, shape := range []string{"catalog", "int32", "string", "bool", "float32", "float64"} { + for _, nullPercent := range []int{0, 5} { + benchmark.Run(fmt.Sprintf("%s/null%d", shape, nullPercent), func(benchmark *testing.B) { + const rowCount = 2900 + columnCount := 1 + if shape == "catalog" { + columnCount = 34 + } + fields := make([]arrow.Field, columnCount) + columns := make([]arrow.Array, columnCount) + infos := make([]colInfo, columnCount) + for column := range columns { + dataType := arrow.DataType(arrow.PrimitiveTypes.Int32) + dbType := cli_service.TTypeId_INT_TYPE + value := "1234567" + switch { + case shape == "string" || shape == "catalog" && column >= 20: + dataType, dbType, value = arrow.BinaryTypes.String, cli_service.TTypeId_DECIMAL_TYPE, "12345.67" + case shape == "catalog" && column >= 18: + dataType, dbType = arrow.PrimitiveTypes.Int64, cli_service.TTypeId_BIGINT_TYPE + case shape == "bool": + dataType, dbType, value = arrow.FixedWidthTypes.Boolean, cli_service.TTypeId_BOOLEAN_TYPE, "true" + case shape == "float32": + dataType, dbType, value = arrow.PrimitiveTypes.Float32, cli_service.TTypeId_FLOAT_TYPE, "123.25" + case shape == "float64": + dataType, dbType, value = arrow.PrimitiveTypes.Float64, cli_service.TTypeId_DOUBLE_TYPE, "123.25" + } + builder := array.NewBuilder(memory.DefaultAllocator, dataType) + for row := 0; row < rowCount; row++ { + if nullPercent > 0 && (row*17+column*31)%100 < nullPercent { + builder.AppendNull() + } else if err := builder.AppendValueFromString(value); err != nil { + benchmark.Fatal(err) + } + } + columns[column] = builder.NewArray() + builder.Release() + defer columns[column].Release() + fields[column] = arrow.Field{Name: fmt.Sprint(column), Type: dataType, Nullable: true} + infos[column] = colInfo{name: fields[column].Name, arrowType: dataType, dbType: dbType} + } + schema := arrow.NewSchema(fields, nil) + delimiter := rowscanner.NewDelimiter(0, rowCount) + record := &sparkArrowRecord{Delimiter: delimiter, RecordBatch: array.NewRecordBatch(schema, columns, rowCount)} + scanner := &arrowRowScanner{ + Delimiter: delimiter, valueContainerMaker: &arrowValueContainerMaker{}, + arrowSchema: schema, colInfo: infos, location: time.UTC, + DBSQLLogger: dbsqllog.Logger, ctx: context.Background(), + batchIterator: &fakeBatchIterator{index: -1, batches: []SparkArrowBatch{ + &sparkArrowBatch{Delimiter: delimiter, arrowRecords: []SparkArrowRecord{record}}, + }}, + } + defer scanner.Close() + destination := make([]driver.Value, columnCount) + if err := scanner.ScanRow(destination, 0); err != nil { + benchmark.Fatal(err) + } + benchmark.ReportAllocs() + benchmark.ResetTimer() + for iteration := 0; iteration < benchmark.N; iteration++ { + for row := int64(0); row < rowCount; row++ { + if err := scanner.ScanRow(destination, row); err != nil { + benchmark.Fatal(err) + } + } + } + benchmark.ReportMetric(float64(benchmark.Elapsed().Nanoseconds())/float64(benchmark.N*rowCount*columnCount), "ns/cell") + }) + } + } +} diff --git a/internal/rows/arrowbased/cellReaders_test.go b/internal/rows/arrowbased/cellReaders_test.go index 9ae98b0c..51a9d034 100644 --- a/internal/rows/arrowbased/cellReaders_test.go +++ b/internal/rows/arrowbased/cellReaders_test.go @@ -219,3 +219,54 @@ func TestBoundTimestampLocation(t *testing.T) { }) } } + +func TestBoundDecimalRequiresDecimalColumn(t *testing.T) { + dataType := &arrow.Decimal128Type{Precision: 10, Scale: 2} + builder := array.NewDecimal128Builder(memory.DefaultAllocator, dataType) + defer builder.Release() + require.NoError(t, builder.AppendValueFromString("12.34")) + values := builder.NewArray() + defer values.Release() + scanner := readerTestScanner([]arrow.Field{{Name: "number", Type: dataType}}, []cli_service.TTypeId{cli_service.TTypeId_DOUBLE_TYPE}, config.ArrowConfig{UseArrowNativeDecimal: true}, time.UTC, []arrow.Array{values}) + defer scanner.Close() + destination := make([]driver.Value, 1) + require.NoError(t, scanner.ScanRow(destination, 41)) + require.Equal(t, values.(*array.Decimal128).Value(0).ToFloat64(2), destination[0]) +} + +func TestBoundNullType(t *testing.T) { + values := array.NewNull(2) + defer values.Release() + scanner := readerTestScanner([]arrow.Field{{Name: "null", Type: arrow.Null, Nullable: true}}, []cli_service.TTypeId{cli_service.TTypeId_NULL_TYPE}, config.ArrowConfig{}, time.UTC, []arrow.Array{values}) + defer scanner.Close() + destination := []driver.Value{"stale"} + for row := int64(41); row < 43; row++ { + require.NoError(t, scanner.ScanRow(destination, row)) + require.Nil(t, destination[0]) + } +} + +type bitmapReadCounter struct { + arrow.Array + reads int +} + +func (counter *bitmapReadCounter) NullBitmapBytes() []byte { + counter.reads++ + return counter.Array.NullBitmapBytes() +} + +func TestBoundNullFreeSkipsBitmap(t *testing.T) { + builder := array.NewInt32Builder(memory.DefaultAllocator) + defer builder.Release() + builder.Append(1234567) + values := builder.NewArray() + defer values.Release() + counter := &bitmapReadCounter{Array: values} + scanner := readerTestScanner([]arrow.Field{{Name: "number", Type: arrow.PrimitiveTypes.Int32}}, []cli_service.TTypeId{cli_service.TTypeId_INT_TYPE}, config.ArrowConfig{}, time.UTC, []arrow.Array{counter}) + defer scanner.Close() + destination := make([]driver.Value, 1) + require.NoError(t, scanner.ScanRow(destination, 41)) + require.Equal(t, int32(1234567), destination[0]) + require.Zero(t, counter.reads) +} From 9b059038bd329fb7c24d410cddec4c9ec90deb59 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 27 Nov 2026 07:00:32 +0000 Subject: [PATCH 03/11] Remove obsolete row dispatch helpers and guard record ownership Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- internal/rows/arrowbased/arrowRows_test.go | 31 ++---------- .../rows/arrowbased/arrowscan_parity_test.go | 6 +-- internal/rows/arrowbased/cellReaders_test.go | 18 +++++++ internal/rows/arrowbased/columnValues.go | 47 ------------------- 4 files changed, 25 insertions(+), 77 deletions(-) diff --git a/internal/rows/arrowbased/arrowRows_test.go b/internal/rows/arrowbased/arrowRows_test.go index 8df169b4..7edf1e1b 100644 --- a/internal/rows/arrowbased/arrowRows_test.go +++ b/internal/rows/arrowbased/arrowRows_test.go @@ -516,25 +516,25 @@ func TestArrowRowScanner(t *testing.T) { err := ars.loadBatchFor(0) assert.Nil(t, err) - assert.Equal(t, len(metadataResp.Schema.Columns), ars.rowValues.NColumns()) + assert.Len(t, ars.rowValues.columnValueHolders, len(metadataResp.Schema.Columns)) assert.Equal(t, 1, callCount) assert.Equal(t, 1, fbi.callCount) err = ars.loadBatchFor(1) assert.Nil(t, err) - assert.Equal(t, len(metadataResp.Schema.Columns), ars.rowValues.NColumns()) + assert.Len(t, ars.rowValues.columnValueHolders, len(metadataResp.Schema.Columns)) assert.Equal(t, 1, callCount) assert.Equal(t, 1, fbi.callCount) err = ars.loadBatchFor(2) assert.Nil(t, err) - assert.Equal(t, len(metadataResp.Schema.Columns), ars.rowValues.NColumns()) + assert.Len(t, ars.rowValues.columnValueHolders, len(metadataResp.Schema.Columns)) assert.Equal(t, 1, callCount) assert.Equal(t, 1, fbi.callCount) err = ars.loadBatchFor(5) assert.Nil(t, err) - assert.Equal(t, len(metadataResp.Schema.Columns), ars.rowValues.NColumns()) + assert.Len(t, ars.rowValues.columnValueHolders, len(metadataResp.Schema.Columns)) assert.Equal(t, 1, callCount) assert.Equal(t, 2, fbi.callCount) @@ -2137,29 +2137,6 @@ func TestDecimal128ContainerNativeDecimal(t *testing.T) { assert.Equal(t, float64(5.15), v) }) - t.Run("rowValues.DecimalStringValue returns lossless string for a decimal holder", func(t *testing.T) { - c := newDecimal128Container(t, 10, 2, []string{"5.15", ""}) - rv := NewRowValues(rowscanner.NewDelimiter(0, 2), []columnValues{c}) - - assert.False(t, rv.IsNull(0, 0)) - s, ok := rv.DecimalStringValue(0, 0) - assert.True(t, ok) - assert.Equal(t, "5.15", s) - - // Value still returns the legacy float64 (used for nested rendering). - v, err := rv.Value(0, 0) - assert.NoError(t, err) - assert.Equal(t, float64(5.15), v) - - assert.True(t, rv.IsNull(0, 1)) - }) - - t.Run("rowValues.DecimalStringValue reports ok=false for non-decimal holders", func(t *testing.T) { - rv := NewRowValues(rowscanner.NewDelimiter(0, 1), []columnValues{&columnValuesTyped[*array.String, string]{}}) - s, ok := rv.DecimalStringValue(0, 0) - assert.False(t, ok) - assert.Equal(t, "", s) - }) } // TestScanRowNativeDecimal drives the full ScanRow path with a real diff --git a/internal/rows/arrowbased/arrowscan_parity_test.go b/internal/rows/arrowbased/arrowscan_parity_test.go index a30668e1..6170773a 100644 --- a/internal/rows/arrowbased/arrowscan_parity_test.go +++ b/internal/rows/arrowbased/arrowscan_parity_test.go @@ -550,7 +550,7 @@ func TestArrowbasedKernelVariantGeometryParity(t *testing.T) { // - The Thrift *container* (decimal128Container.Value) converts a decimal128 to // a lossy float64 — but that path is only reached when UseArrowNativeDecimal // is on AND the value is read as a nested leaf. For a top-level column the -// scan uses DecimalStringValue (exact string) when the flag is on. +// scan uses ValueString (exact string) when the flag is on. // - In the DEFAULT config the flag is off, so the server sends DECIMAL as a // string column (DecimalAsArrow=false) — no decimal128 arrives at all, and the // user gets the exact string. @@ -582,14 +582,14 @@ func TestTopLevelDecimalRendering(t *testing.T) { } // Thrift container Value() is the lossy-float64 path (reached only with native - // decimal + nested read); DecimalStringValue is the exact top-level scan path. + // decimal + nested read); ValueString is the exact top-level scan path. // Assert both so a change to either is caught. holder := &decimal128Container{scale: dt.Scale} if err := holder.SetValueArray(arr.Data()); err != nil { t.Fatal(err) } if s := holder.ValueString(0); s != "1234567890123456.7890" { - t.Errorf("Thrift DecimalStringValue = %q, want exact string", s) + t.Errorf("Thrift ValueString = %q, want exact string", s) } // Value() is the lossy path: it returns a float64, and a 20-digit decimal // cannot survive it — assert the actual rounded value, not just the type. diff --git a/internal/rows/arrowbased/cellReaders_test.go b/internal/rows/arrowbased/cellReaders_test.go index 51a9d034..b94e1f1a 100644 --- a/internal/rows/arrowbased/cellReaders_test.go +++ b/internal/rows/arrowbased/cellReaders_test.go @@ -142,6 +142,24 @@ func TestBoundReadersRebindAndRelease(t *testing.T) { require.Equal(t, int32(402), destination[0]) } +func TestBoundReadersSurviveRecordRelease(t *testing.T) { + pool := memory.NewCheckedAllocator(memory.DefaultAllocator) + defer pool.AssertSize(t, 0) + builder := array.NewInt32Builder(pool) + defer builder.Release() + builder.AppendNull() + builder.Append(1234567) + values := builder.NewArray() + scanner := readerTestScanner([]arrow.Field{{Name: "number", Type: arrow.PrimitiveTypes.Int32, Nullable: true}}, []cli_service.TTypeId{cli_service.TTypeId_INT_TYPE}, config.ArrowConfig{}, time.UTC, []arrow.Array{values}) + values.Release() + defer scanner.Close() + destination := []driver.Value{"stale"} + require.NoError(t, scanner.ScanRow(destination, 41)) + require.Nil(t, destination[0]) + require.NoError(t, scanner.ScanRow(destination, 42)) + require.Equal(t, int32(1234567), destination[0]) +} + func TestBoundNativeIntervalNullAndError(t *testing.T) { for _, dbType := range []cli_service.TTypeId{cli_service.TTypeId_INTERVAL_DAY_TIME_TYPE, cli_service.TTypeId_INTERVAL_YEAR_MONTH_TYPE} { t.Run(dbType.String(), func(t *testing.T) { diff --git a/internal/rows/arrowbased/columnValues.go b/internal/rows/arrowbased/columnValues.go index 63d2c5ea..f875f237 100644 --- a/internal/rows/arrowbased/columnValues.go +++ b/internal/rows/arrowbased/columnValues.go @@ -14,23 +14,6 @@ import ( "github.com/pkg/errors" ) -// Abstraction for holding the values for a set of rows -type RowValues interface { - rowscanner.Delimiter - Close() - NColumns() int - SetColumnValues(columnIndex int, values arrow.ArrayData) error - IsNull(columnIndex int, rowNumber int64) bool - Value(columnIndex int, rowNumber int64) (any, error) - // DecimalStringValue returns a native-Arrow DECIMAL column value as a - // lossless, scale-applied string. ok is false when the column is not backed - // by a decimal128 holder, in which case the caller should fall back to - // Value. Used only for top-level DECIMAL columns when native decimal is - // enabled; see databricks/databricks-sql-go#274. - DecimalStringValue(columnIndex int, rowNumber int64) (value string, ok bool) - SetDelimiter(d rowscanner.Delimiter) -} - func NewRowValues(d rowscanner.Delimiter, holders []columnValues) *rowValues { return &rowValues{Delimiter: d, columnValueHolders: holders} } @@ -41,8 +24,6 @@ type rowValues struct { readers []columnReader } -var _ RowValues = (*rowValues)(nil) - func (rv *rowValues) Close() { rv.readers = nil // release any retained arrow arrays @@ -62,34 +43,6 @@ func (rv *rowValues) SetColumnValues(columnIndex int, values arrow.ArrayData) er return err } -func (rv *rowValues) IsNull(columnIndex int, rowNumber int64) bool { - b := true - if columnIndex < len(rv.columnValueHolders) { - b = rv.columnValueHolders[columnIndex].IsNull(int(rowNumber - rv.Start())) - } - return b -} - -func (rv *rowValues) Value(columnIndex int, rowNumber int64) (any, error) { - var err error - var value any - if columnIndex < len(rv.columnValueHolders) { - value, err = rv.columnValueHolders[columnIndex].Value(int(rowNumber - rv.Start())) - } - return value, err -} - -func (rv *rowValues) DecimalStringValue(columnIndex int, rowNumber int64) (string, bool) { - if columnIndex < len(rv.columnValueHolders) { - if d, ok := rv.columnValueHolders[columnIndex].(*decimal128Container); ok { - return d.ValueString(int(rowNumber - rv.Start())), true - } - } - return "", false -} - -func (rv *rowValues) NColumns() int { return len(rv.columnValueHolders) } - func (rv *rowValues) SetDelimiter(d rowscanner.Delimiter) { rv.Delimiter = d } type valueContainerMaker interface { From 9e1dc50d5e80b0391d7e7fe8a259ec54b09242a0 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Fri, 27 Nov 2026 07:47:32 +0000 Subject: [PATCH 04/11] Preserve Thrift cell reader edge-case behavior Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- internal/rows/arrowbased/arrowRows.go | 1 + internal/rows/arrowbased/cellReaders.go | 6 +- internal/rows/arrowbased/cellReaders_test.go | 85 ++++++++++++++++++++ 3 files changed, 91 insertions(+), 1 deletion(-) diff --git a/internal/rows/arrowbased/arrowRows.go b/internal/rows/arrowbased/arrowRows.go index 097d86b6..61c0bf90 100644 --- a/internal/rows/arrowbased/arrowRows.go +++ b/internal/rows/arrowbased/arrowRows.go @@ -158,6 +158,7 @@ func NewArrowRowScanner(resultSetMetadata *cli_service.TGetResultSetMetadataResp func (ars *arrowRowScanner) Close() { if ars.rowValues != nil { ars.rowValues.Close() + ars.rowValues.SetDelimiter(rowscanner.NewDelimiter(0, 0)) } if ars.batchIterator != nil { diff --git a/internal/rows/arrowbased/cellReaders.go b/internal/rows/arrowbased/cellReaders.go index 9065c0c4..9a5a3ced 100644 --- a/internal/rows/arrowbased/cellReaders.go +++ b/internal/rows/arrowbased/cellReaders.go @@ -35,11 +35,15 @@ func (rv *rowValues) bindReaders(columns []colInfo, cfg config.ArrowConfig, arra if cfg.UseArrowNativeIntervalTypes && isIntervalType(columns[column].dbType) { read = func(int) (any, error) { return nil, errNativeInterval } } - if values != nil && values.NullN() == 0 { + if values != nil && values.Data().NullN() == 0 { rv.readers[column] = read continue } if values != nil && len(values.NullBitmapBytes()) > 0 { + if values.NullN() == 0 { + rv.readers[column] = read + continue + } bitmap, offset := values.NullBitmapBytes(), values.Data().Offset() rv.readers[column] = func(row int) (any, error) { if bitutil.BitIsNotSet(bitmap, offset+row) { diff --git a/internal/rows/arrowbased/cellReaders_test.go b/internal/rows/arrowbased/cellReaders_test.go index b94e1f1a..59a977f8 100644 --- a/internal/rows/arrowbased/cellReaders_test.go +++ b/internal/rows/arrowbased/cellReaders_test.go @@ -288,3 +288,88 @@ func TestBoundNullFreeSkipsBitmap(t *testing.T) { require.Equal(t, int32(1234567), destination[0]) require.Zero(t, counter.reads) } + +func TestBoundUnknownNullCountWithoutBitmap(t *testing.T) { + pool := memory.NewCheckedAllocator(memory.DefaultAllocator) + defer pool.AssertSize(t, 0) + builder := array.NewInt32Builder(pool) + defer builder.Release() + for row := 0; row < 64; row++ { + builder.Append(int32(row)) + } + full := builder.NewArray() + defer full.Release() + data := array.NewData(arrow.PrimitiveTypes.Int32, 64, []*memory.Buffer{nil, full.Data().Buffers()[1]}, nil, 5, 0) + defer data.Release() + sliced := array.NewSliceData(data, 7, 39) + defer sliced.Release() + values := array.NewInt32Data(sliced) + defer values.Release() + require.Equal(t, array.UnknownNullCount, values.Data().NullN()) + require.Empty(t, values.NullBitmapBytes()) + scanner := readerTestScanner([]arrow.Field{{Name: "number", Type: arrow.PrimitiveTypes.Int32, Nullable: true}}, []cli_service.TTypeId{cli_service.TTypeId_INT_TYPE}, config.ArrowConfig{}, time.UTC, []arrow.Array{values}) + defer scanner.Close() + destination := make([]driver.Value, 1) + for row := int32(0); row < 32; row++ { + require.NotPanics(t, func() { + require.NoError(t, scanner.ScanRow(destination, 41+int64(row))) + }) + require.Equal(t, 7+row, destination[0]) + } +} + +func TestBoundUnknownNullCountWithBitmap(t *testing.T) { + builder := array.NewInt32Builder(memory.DefaultAllocator) + defer builder.Release() + builder.AppendNull() + builder.Append(1234567) + full := builder.NewArray() + defer full.Release() + values := array.NewSlice(full, 1, 2) + defer values.Release() + require.Equal(t, array.UnknownNullCount, values.Data().NullN()) + counter := &bitmapReadCounter{Array: values} + scanner := readerTestScanner([]arrow.Field{{Name: "number", Type: arrow.PrimitiveTypes.Int32}}, []cli_service.TTypeId{cli_service.TTypeId_INT_TYPE}, config.ArrowConfig{}, time.UTC, []arrow.Array{counter}) + defer scanner.Close() + destination := make([]driver.Value, 1) + require.NoError(t, scanner.ScanRow(destination, 41)) + require.Equal(t, int32(1234567), destination[0]) + require.Equal(t, 1, counter.reads) +} + +type missingBitmapArray struct { + arrow.Array +} + +func (values *missingBitmapArray) NullBitmapBytes() []byte { return nil } + +func TestBoundMissingBitmapUsesHolderNulls(t *testing.T) { + builder := array.NewInt32Builder(memory.DefaultAllocator) + defer builder.Release() + builder.Append(1234567) + builder.AppendNull() + builder.Append(7654321) + values := builder.NewArray() + defer values.Release() + scanner := readerTestScanner([]arrow.Field{{Name: "number", Type: arrow.PrimitiveTypes.Int32, Nullable: true}}, []cli_service.TTypeId{cli_service.TTypeId_INT_TYPE}, config.ArrowConfig{}, time.UTC, []arrow.Array{&missingBitmapArray{Array: values}}) + defer scanner.Close() + destination := []driver.Value{"stale"} + for row, expected := range []any{int32(1234567), nil, int32(7654321)} { + require.NoError(t, scanner.ScanRow(destination, 41+int64(row))) + require.Equal(t, expected, destination[0]) + } +} + +func TestBoundScanRowAfterCloseFails(t *testing.T) { + builder := array.NewInt32Builder(memory.DefaultAllocator) + defer builder.Release() + builder.Append(1234567) + builder.Append(7654321) + values := builder.NewArray() + defer values.Release() + scanner := readerTestScanner([]arrow.Field{{Name: "number", Type: arrow.PrimitiveTypes.Int32}}, []cli_service.TTypeId{cli_service.TTypeId_INT_TYPE}, config.ArrowConfig{}, time.UTC, []arrow.Array{values}) + destination := make([]driver.Value, 1) + require.NoError(t, scanner.ScanRow(destination, 41)) + scanner.Close() + require.Error(t, scanner.ScanRow(destination, 42)) +} From 5badad6f9feced7a181570f8151dd270a998dfab Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Mon, 30 Nov 2026 21:59:08 +0000 Subject: [PATCH 05/11] fix(thrift): validate bound row readers and closed scanners Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- CHANGELOG.md | 1 + internal/rows/arrowbased/arrowRows.go | 56 ++++++-------- internal/rows/arrowbased/arrowRows_test.go | 8 +- internal/rows/arrowbased/cellReaders.go | 53 +++++++------ internal/rows/arrowbased/cellReaders_test.go | 81 +++++++++++++++++++- internal/rows/arrowbased/columnValues.go | 17 +++- 6 files changed, 147 insertions(+), 69 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f184f7e..64f433f6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Driver changes - Reduce Thrift row-scan CPU by binding scalar readers and null/type handling once per Arrow batch, without changing returned values. +- **Behavior change:** Scanning a closed Thrift Arrow row scanner now returns "row scanner closed" instead of stale values, without logging an ERROR. - Render Thrift ARRAY, MAP and STRUCT values in linear time (databricks/databricks-sql-go#596). - **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). diff --git a/internal/rows/arrowbased/arrowRows.go b/internal/rows/arrowbased/arrowRows.go index 61c0bf90..ea931b4c 100644 --- a/internal/rows/arrowbased/arrowRows.go +++ b/internal/rows/arrowbased/arrowRows.go @@ -77,6 +77,7 @@ type arrowRowScanner struct { ctx context.Context batchIterator BatchIterator + closed bool } // Make sure arrowRowScanner fulfills the RowScanner interface @@ -156,9 +157,9 @@ func NewArrowRowScanner(resultSetMetadata *cli_service.TGetResultSetMetadataResp // Close is called when the Rows instance is closed. func (ars *arrowRowScanner) Close() { + ars.closed = true if ars.rowValues != nil { ars.rowValues.Close() - ars.rowValues.SetDelimiter(rowscanner.NewDelimiter(0, 0)) } if ars.batchIterator != nil { @@ -198,11 +199,18 @@ func (ars *arrowRowScanner) ScanRow( destination []driver.Value, rowNumber int64) dbsqlerr.DBError { - // load the error batch for the specified row, if necessary + if ars != nil && ars.closed { + return dbsqlerrint.NewDriverError(ars.ctx, "row scanner closed", nil) + } + + // load the Arrow batch for the specified row, if necessary err := ars.loadBatchFor(rowNumber) if err != nil { return err } + if len(ars.rowValues.readers) != len(ars.rowValues.columnValueHolders) || len(destination) != len(ars.rowValues.columnValueHolders) { + return dbsqlerrint.NewDriverError(ars.ctx, "row scanner column readers and holders do not match destination", nil) + } // if no location is provided default to UTC if ars.location == nil { @@ -215,19 +223,16 @@ func (ars *arrowRowScanner) ScanRow( // clear the destination destination[i] = nil - // if there is a corresponding column and the value for the specified row - // is not null we put the value in the destination - if i < len(ars.rowValues.readers) { - var err1 error - destination[i], err1 = ars.rowValues.readers[i](rowIndex) - if err1 != nil { - col := ars.colInfo[i] - if err1 == errNativeInterval { - ars.Error().Msg(errArrowRowsUnsupportedNativeType(col.dbType.String())) - return dbsqlerrint.NewDriverError(ars.ctx, errArrowRowsUnsupportedNativeType(col.dbType.String()), nil) - } - err = dbsqlerrint.NewDriverError(ars.ctx, errArrowRowsColumnValue(col.name), err1) + // Bound readers handle both NULLs and column-specific conversions. + var err1 error + destination[i], err1 = ars.rowValues.readers[i](rowIndex) + if err1 != nil { + col := ars.colInfo[i] + if errors.Is(err1, errNativeInterval) { + ars.Error().Msg(errArrowRowsUnsupportedNativeType(col.dbType.String())) + return dbsqlerrint.NewDriverError(ars.ctx, errArrowRowsUnsupportedNativeType(col.dbType.String()), nil) } + err = dbsqlerrint.NewDriverError(ars.ctx, errArrowRowsColumnValue(col.name), err1) } } @@ -292,26 +297,9 @@ func (ars *arrowRowScanner) loadBatchFor(rowNumber int64) dbsqlerr.DBError { } } - // for each column we want to create an arrow array specific to the data type - for i, col := range sar.Columns() { - func() { - col.Retain() - defer col.Release() - - colData := col.Data() - colData.Retain() - defer colData.Release() - - err := ars.rowValues.SetColumnValues(i, colData) - if err != nil { - ars.Error().Msg(err.Error()) - } - }() + if err := ars.rowValues.setRecord(sar, ars.colInfo, ars.ArrowConfig); err != nil { + return dbsqlerrint.NewDriverError(ars.ctx, errArrowRowsMakeColumnValueContainers, err) } - - // Update the delimiter in rowValues to reflect the currently loaded set of rows - ars.rowValues.SetDelimiter(rowscanner.NewDelimiter(sar.Start(), sar.Count())) - ars.rowValues.bindReaders(ars.colInfo, ars.ArrowConfig, sar.Columns()) return nil } @@ -602,7 +590,7 @@ func (vcm *arrowValueContainerMaker) makeColumnValuesContainers(ars *arrowRowSca columnValueHolders[i] = holder } - ars.rowValues = NewRowValues(d, columnValueHolders) + ars.rowValues = newRowValues(d, columnValueHolders) } return nil diff --git a/internal/rows/arrowbased/arrowRows_test.go b/internal/rows/arrowbased/arrowRows_test.go index 7edf1e1b..64e9c662 100644 --- a/internal/rows/arrowbased/arrowRows_test.go +++ b/internal/rows/arrowbased/arrowRows_test.go @@ -452,7 +452,7 @@ func TestArrowRowScanner(t *testing.T) { ars := d.(*arrowRowScanner) var releaseCount int fc := &fakeColumnValues{fnRelease: func() { releaseCount++ }} - ars.rowValues = NewRowValues(rowscanner.NewDelimiter(0, 1), []columnValues{fc, fc, fc}) + ars.rowValues = newRowValues(rowscanner.NewDelimiter(0, 1), []columnValues{fc, fc, fc}) d.Close() assert.Equal(t, 3, releaseCount) }) @@ -510,7 +510,7 @@ func TestArrowRowScanner(t *testing.T) { for i := range ars.arrowSchema.Fields() { columnValueHolders[i] = &fakeColumnValues{} } - ars.rowValues = NewRowValues(rowscanner.NewDelimiter(0, 0), make([]columnValues, len(ars.arrowSchema.Fields()))) + ars.rowValues = newRowValues(rowscanner.NewDelimiter(0, 0), columnValueHolders) return nil }} @@ -880,7 +880,7 @@ func TestArrowRowScanner(t *testing.T) { for i := range ars.arrowSchema.Fields() { columnValueHolders[i] = &fakeColumnValues{} } - ars.rowValues = NewRowValues(rowscanner.NewDelimiter(0, 0), columnValueHolders) + ars.rowValues = newRowValues(rowscanner.NewDelimiter(0, 0), columnValueHolders) return nil }} @@ -2195,7 +2195,7 @@ func TestScanRowNativeDecimal(t *testing.T) { // Install a real decimal128Container holding the high-precision value. ars.valueContainerMaker = &fakeValueContainerMaker{fnMakeColumnValuesContainers: func(ars *arrowRowScanner, _ rowscanner.Delimiter) dbsqlerr.DBError { c := newDecimal128Container(t, precision, scale, []string{highPrecision}) - ars.rowValues = NewRowValues(rowscanner.NewDelimiter(0, 1), []columnValues{c}) + ars.rowValues = newRowValues(rowscanner.NewDelimiter(0, 1), []columnValues{c}) return nil }} diff --git a/internal/rows/arrowbased/cellReaders.go b/internal/rows/arrowbased/cellReaders.go index 9a5a3ced..fc4d962d 100644 --- a/internal/rows/arrowbased/cellReaders.go +++ b/internal/rows/arrowbased/cellReaders.go @@ -20,9 +20,10 @@ func (rv *rowValues) bindReaders(columns []colInfo, cfg config.ArrowConfig, arra } for column, holder := range rv.columnValueHolders { if holder == nil { - continue + rv.readers = nil + return } - read := scalarColumnReader(holder) + read, topLevelValidity := scalarColumnReader(holder) var values arrow.Array if column < len(arrays) { values = arrays[column] @@ -35,25 +36,26 @@ func (rv *rowValues) bindReaders(columns []colInfo, cfg config.ArrowConfig, arra if cfg.UseArrowNativeIntervalTypes && isIntervalType(columns[column].dbType) { read = func(int) (any, error) { return nil, errNativeInterval } } - if values != nil && values.Data().NullN() == 0 { - rv.readers[column] = read - continue + var bitmap []byte + if topLevelValidity && values != nil && values.Data().NullN() != 0 { + bitmap = values.NullBitmapBytes() } - if values != nil && len(values.NullBitmapBytes()) > 0 { - if values.NullN() == 0 { - rv.readers[column] = read - continue - } - bitmap, offset := values.NullBitmapBytes(), values.Data().Offset() + // Only concrete scalar holders use the top-level bitmap; other holders own + // their NULL semantics. NullN may infer unknown counts only with a bitmap. + switch { + case !topLevelValidity || values == nil || values.Data().NullN() != 0 && len(bitmap) == 0: rv.readers[column] = func(row int) (any, error) { - if bitutil.BitIsNotSet(bitmap, offset+row) { + if holder.IsNull(row) { return nil, nil } return read(row) } - } else { + case values.Data().NullN() == 0 || values.NullN() == 0: + rv.readers[column] = read + default: + offset := values.Data().Offset() rv.readers[column] = func(row int) (any, error) { - if holder.IsNull(row) { + if bitutil.BitIsNotSet(bitmap, offset+row) { return nil, nil } return read(row) @@ -62,36 +64,37 @@ func (rv *rowValues) bindReaders(columns []colInfo, cfg config.ArrowConfig, arra } } -func scalarColumnReader(holder columnValues) columnReader { +// Concrete reads avoid generic/interface dispatch (catalog benchmark: 24.8 to 14.0 ns/cell). +func scalarColumnReader(holder columnValues) (columnReader, bool) { switch column := holder.(type) { case *columnValuesTyped[*array.Boolean, bool]: values := column.holder - return func(row int) (any, error) { return values.Value(row), nil } + return func(row int) (any, error) { return values.Value(row), nil }, true case *columnValuesTyped[*array.Int8, int8]: values := column.holder - return func(row int) (any, error) { return values.Value(row), nil } + return func(row int) (any, error) { return values.Value(row), nil }, true case *columnValuesTyped[*array.Int16, int16]: values := column.holder - return func(row int) (any, error) { return values.Value(row), nil } + return func(row int) (any, error) { return values.Value(row), nil }, true case *columnValuesTyped[*array.Int32, int32]: values := column.holder - return func(row int) (any, error) { return values.Value(row), nil } + return func(row int) (any, error) { return values.Value(row), nil }, true case *columnValuesTyped[*array.Int64, int64]: values := column.holder - return func(row int) (any, error) { return values.Value(row), nil } + return func(row int) (any, error) { return values.Value(row), nil }, true case *columnValuesTyped[*array.Float32, float32]: values := column.holder - return func(row int) (any, error) { return values.Value(row), nil } + return func(row int) (any, error) { return values.Value(row), nil }, true case *columnValuesTyped[*array.Float64, float64]: values := column.holder - return func(row int) (any, error) { return values.Value(row), nil } + return func(row int) (any, error) { return values.Value(row), nil }, true case *columnValuesTyped[*array.String, string]: values := column.holder - return func(row int) (any, error) { return values.Value(row), nil } + return func(row int) (any, error) { return values.Value(row), nil }, true case *columnValuesTyped[*array.Binary, []byte]: values := column.holder - return func(row int) (any, error) { return values.Value(row), nil } + return func(row int) (any, error) { return values.Value(row), nil }, true default: - return holder.Value + return holder.Value, false } } diff --git a/internal/rows/arrowbased/cellReaders_test.go b/internal/rows/arrowbased/cellReaders_test.go index 59a977f8..fcff67b8 100644 --- a/internal/rows/arrowbased/cellReaders_test.go +++ b/internal/rows/arrowbased/cellReaders_test.go @@ -1,6 +1,7 @@ package arrowbased import ( + "bytes" "context" "database/sql/driver" "fmt" @@ -93,10 +94,9 @@ func TestBoundColumnReaders(t *testing.T) { defer values.Release() scanner := readerTestScanner([]arrow.Field{{Name: test.name, Type: test.dataType, Nullable: true}}, []cli_service.TTypeId{test.dbType}, config.ArrowConfig{UseArrowNativeDecimal: true}, time.UTC, []arrow.Array{values}) defer scanner.Close() - destination := []driver.Value{"stale", "extra"} + destination := []driver.Value{"stale"} for row := int64(0); row < 3; row++ { require.NoError(t, scanner.ScanRow(destination, 41+row)) - require.Nil(t, destination[1]) if values.IsNull(int(row)) { require.Nil(t, destination[0]) } else { @@ -364,12 +364,85 @@ func TestBoundScanRowAfterCloseFails(t *testing.T) { builder := array.NewInt32Builder(memory.DefaultAllocator) defer builder.Release() builder.Append(1234567) - builder.Append(7654321) + builder.AppendNull() values := builder.NewArray() defer values.Release() scanner := readerTestScanner([]arrow.Field{{Name: "number", Type: arrow.PrimitiveTypes.Int32}}, []cli_service.TTypeId{cli_service.TTypeId_INT_TYPE}, config.ArrowConfig{}, time.UTC, []arrow.Array{values}) destination := make([]driver.Value, 1) require.NoError(t, scanner.ScanRow(destination, 41)) scanner.Close() - require.Error(t, scanner.ScanRow(destination, 42)) + var output bytes.Buffer + scanner.DBSQLLogger = &dbsqllog.DBSQLLogger{Logger: dbsqllog.Logger.Output(&output)} + for _, row := range []int64{41, 42} { + require.EqualError(t, scanner.ScanRow(destination, row), "databricks: driver error: row scanner closed") + require.Equal(t, int32(1234567), destination[0]) + } + require.Empty(t, output.String()) + require.Zero(t, scanner.rowValues.Count()) + require.False(t, scanner.rowValues.Contains(41)) +} + +func TestBoundScanRowRequiresHoldersAndReaders(t *testing.T) { + for _, state := range []string{"no-holder", "nil-holder", "not-bound"} { + t.Run(state, func(t *testing.T) { + builder := array.NewInt32Builder(memory.DefaultAllocator) + defer builder.Release() + builder.Append(1234567) + values := builder.NewArray() + defer values.Release() + scanner := readerTestScanner([]arrow.Field{{Name: "number", Type: arrow.PrimitiveTypes.Int32}}, []cli_service.TTypeId{cli_service.TTypeId_INT_TYPE}, config.ArrowConfig{}, time.UTC, []arrow.Array{values}) + defer scanner.Close() + destination := []driver.Value{"stale"} + require.NoError(t, scanner.ScanRow(destination, 41)) + holders := scanner.rowValues.columnValueHolders + defer func() { scanner.rowValues.columnValueHolders = holders }() + switch state { + case "no-holder": + scanner.rowValues.columnValueHolders = nil + scanner.rowValues.readers = nil + case "nil-holder": + scanner.rowValues.columnValueHolders = []columnValues{nil} + scanner.rowValues.bindReaders(scanner.colInfo, scanner.ArrowConfig, []arrow.Array{values}) + case "not-bound": + scanner.rowValues.readers = nil + } + require.NotPanics(t, func() { + require.ErrorContains(t, scanner.ScanRow(destination, 41), "row scanner column readers and holders do not match destination") + }) + require.Equal(t, int32(1234567), destination[0]) + }) + } +} + +func TestBoundUnknownHolderOwnsNullSemantics(t *testing.T) { + builder := array.NewInt32Builder(memory.DefaultAllocator) + defer builder.Release() + builder.Append(1234567) + builder.AppendNull() + values := builder.NewArray() + defer values.Release() + holder := &fakeColumnValues{ + fnIsNull: func(row int) bool { return row == 0 }, + fnValue: func(int) any { return int32(7654321) }, + } + containers := newRowValues(rowscanner.NewDelimiter(41, 2), []columnValues{holder}) + defer containers.Close() + containers.bindReaders([]colInfo{{dbType: cli_service.TTypeId_INT_TYPE}}, config.ArrowConfig{}, []arrow.Array{values}) + for row, expected := range []any{nil, int32(7654321)} { + actual, err := containers.readers[0](row) + require.NoError(t, err) + require.Equal(t, expected, actual) + } +} + +func TestBoundWrappedNativeIntervalError(t *testing.T) { + scanner := &arrowRowScanner{ + rowValues: newRowValues(rowscanner.NewDelimiter(0, 1), []columnValues{&fakeColumnValues{}}), + batchIterator: &fakeBatchIterator{}, DBSQLLogger: dbsqllog.Logger, + colInfo: []colInfo{{dbType: cli_service.TTypeId_INTERVAL_YEAR_MONTH_TYPE}}, + } + scanner.rowValues.readers = []columnReader{func(int) (any, error) { + return nil, fmt.Errorf("wrapped: %w", errNativeInterval) + }} + require.EqualError(t, scanner.ScanRow(make([]driver.Value, 1), 0), "databricks: driver error: "+errArrowRowsUnsupportedNativeType(cli_service.TTypeId_INTERVAL_YEAR_MONTH_TYPE.String())) } diff --git a/internal/rows/arrowbased/columnValues.go b/internal/rows/arrowbased/columnValues.go index fc015720..40a2e824 100644 --- a/internal/rows/arrowbased/columnValues.go +++ b/internal/rows/arrowbased/columnValues.go @@ -6,6 +6,7 @@ import ( "github.com/apache/arrow-go/v18/arrow" "github.com/apache/arrow-go/v18/arrow/array" "github.com/databricks/databricks-sql-go/v2/internal/arrowscan" + "github.com/databricks/databricks-sql-go/v2/internal/config" "github.com/databricks/databricks-sql-go/v2/internal/decimalfmt" "github.com/databricks/databricks-sql-go/v2/internal/jsonfmt" "github.com/databricks/databricks-sql-go/v2/internal/rows/rowscanner" @@ -13,7 +14,7 @@ import ( "github.com/pkg/errors" ) -func NewRowValues(d rowscanner.Delimiter, holders []columnValues) *rowValues { +func newRowValues(d rowscanner.Delimiter, holders []columnValues) *rowValues { return &rowValues{Delimiter: d, columnValueHolders: holders} } @@ -25,6 +26,7 @@ type rowValues struct { func (rv *rowValues) Close() { rv.readers = nil + rv.Delimiter = rowscanner.NewDelimiter(0, 0) // release any retained arrow arrays for i := range rv.columnValueHolders { if rv.columnValueHolders[i] != nil { @@ -42,7 +44,18 @@ func (rv *rowValues) SetColumnValues(columnIndex int, values arrow.ArrayData) er return err } -func (rv *rowValues) SetDelimiter(d rowscanner.Delimiter) { rv.Delimiter = d } +func (rv *rowValues) setRecord(record SparkArrowRecord, columns []colInfo, cfg config.ArrowConfig) error { + rv.Delimiter = rowscanner.NewDelimiter(0, 0) + for column, values := range record.Columns() { + if err := rv.SetColumnValues(column, values.Data()); err != nil { + rv.readers = nil + return err + } + } + rv.bindReaders(columns, cfg, record.Columns()) + rv.Delimiter = rowscanner.NewDelimiter(record.Start(), record.Count()) + return nil +} type valueContainerMaker interface { makeColumnValuesContainers(ars *arrowRowScanner, d rowscanner.Delimiter) error From 7279bc827e1bdb2207de890990c2344276c1df9f Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Mon, 30 Nov 2026 22:07:13 +0000 Subject: [PATCH 06/11] perf(thrift): retain bitmap reads for audited container holders Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- internal/rows/arrowbased/cellReaders.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/internal/rows/arrowbased/cellReaders.go b/internal/rows/arrowbased/cellReaders.go index fc4d962d..56668fe3 100644 --- a/internal/rows/arrowbased/cellReaders.go +++ b/internal/rows/arrowbased/cellReaders.go @@ -40,7 +40,7 @@ func (rv *rowValues) bindReaders(columns []colInfo, cfg config.ArrowConfig, arra if topLevelValidity && values != nil && values.Data().NullN() != 0 { bitmap = values.NullBitmapBytes() } - // Only concrete scalar holders use the top-level bitmap; other holders own + // Only known holders use the top-level bitmap; other holders own // their NULL semantics. NullN may infer unknown counts only with a bitmap. switch { case !topLevelValidity || values == nil || values.Data().NullN() != 0 && len(bitmap) == 0: @@ -94,6 +94,10 @@ func scalarColumnReader(holder columnValues) (columnReader, bool) { case *columnValuesTyped[*array.Binary, []byte]: values := column.holder return func(row int) (any, error) { return values.Value(row), nil }, true + case *listValueContainer, *mapValueContainer, *structValueContainer, + *dateValueContainer, *timeValueContainer, *timestampValueContainer, + *timestampStringValueContainer, *decimal128Container: + return holder.Value, true default: return holder.Value, false } From 74cb90318a54c9c94b0938eb2383223007d0c500 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Mon, 30 Nov 2026 23:02:19 +0000 Subject: [PATCH 07/11] fix(thrift): validate readers once and retain setup errors Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- CHANGELOG.md | 4 +- internal/rows/arrowbased/arrowRows.go | 21 ++++-- internal/rows/arrowbased/arrowRows_test.go | 10 ++- internal/rows/arrowbased/cellReaders.go | 2 + internal/rows/arrowbased/cellReaders_test.go | 77 +++++++++++++++++++- internal/rows/arrowbased/columnValues.go | 4 + internal/rows/arrowbased/errors.go | 3 + 7 files changed, 105 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 64f433f6..e6df0792 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,8 +4,8 @@ ### Driver changes -- Reduce Thrift row-scan CPU by binding scalar readers and null/type handling once per Arrow batch, without changing returned values. -- **Behavior change:** Scanning a closed Thrift Arrow row scanner now returns "row scanner closed" instead of stale values, without logging an ERROR. +- Reduce Thrift row-scan CPU by binding scalar readers and null/type handling once per Arrow record (databricks/databricks-sql-go#602). +- **Behavior change:** Closed Thrift Arrow row scanners return an explicit error without logging an ERROR instead of stale values; destinations with more columns than Arrow holders now error instead of receiving NULL for missing columns (databricks/databricks-sql-go#602). - Render Thrift ARRAY, MAP and STRUCT values in linear time (databricks/databricks-sql-go#596). - **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). diff --git a/internal/rows/arrowbased/arrowRows.go b/internal/rows/arrowbased/arrowRows.go index ea931b4c..46bef323 100644 --- a/internal/rows/arrowbased/arrowRows.go +++ b/internal/rows/arrowbased/arrowRows.go @@ -78,6 +78,7 @@ type arrowRowScanner struct { batchIterator BatchIterator closed bool + scanError dbsqlerr.DBError } // Make sure arrowRowScanner fulfills the RowScanner interface @@ -199,18 +200,15 @@ func (ars *arrowRowScanner) ScanRow( destination []driver.Value, rowNumber int64) dbsqlerr.DBError { - if ars != nil && ars.closed { - return dbsqlerrint.NewDriverError(ars.ctx, "row scanner closed", nil) - } - // load the Arrow batch for the specified row, if necessary err := ars.loadBatchFor(rowNumber) if err != nil { return err } - if len(ars.rowValues.readers) != len(ars.rowValues.columnValueHolders) || len(destination) != len(ars.rowValues.columnValueHolders) { - return dbsqlerrint.NewDriverError(ars.ctx, "row scanner column readers and holders do not match destination", nil) + if len(destination) != len(ars.rowValues.readers) { + return dbsqlerrint.NewDriverError(ars.ctx, errArrowRowsReaderMismatch, nil) } + readers := ars.rowValues.readers[:len(destination)] // if no location is provided default to UTC if ars.location == nil { @@ -225,7 +223,7 @@ func (ars *arrowRowScanner) ScanRow( // Bound readers handle both NULLs and column-specific conversions. var err1 error - destination[i], err1 = ars.rowValues.readers[i](rowIndex) + destination[i], err1 = readers[i](rowIndex) if err1 != nil { col := ars.colInfo[i] if errors.Is(err1, errNativeInterval) { @@ -250,6 +248,9 @@ func (ars *arrowRowScanner) loadBatchFor(rowNumber int64) dbsqlerr.DBError { if ars == nil { return dbsqlerrint.NewDriverError(context.Background(), errArrowRowsNoArrowBatches, nil) } + if ars.closed { + return dbsqlerrint.NewDriverError(ars.ctx, errArrowRowsScannerClosed, nil) + } if ars.batchIterator == nil { return dbsqlerrint.NewDriverError(ars.ctx, errArrowRowsNoArrowBatches, nil) @@ -259,6 +260,9 @@ func (ars *arrowRowScanner) loadBatchFor(rowNumber int64) dbsqlerr.DBError { if ars.rowValues != nil && ars.rowValues.Contains(rowNumber) { return nil } + if ars.scanError != nil { + return ars.scanError + } // check for things like going backwards, rowNumber < 0, etc. err := ars.validateRowNumber(rowNumber) @@ -298,7 +302,8 @@ func (ars *arrowRowScanner) loadBatchFor(rowNumber int64) dbsqlerr.DBError { } if err := ars.rowValues.setRecord(sar, ars.colInfo, ars.ArrowConfig); err != nil { - return dbsqlerrint.NewDriverError(ars.ctx, errArrowRowsMakeColumnValueContainers, err) + ars.scanError = dbsqlerrint.NewDriverError(ars.ctx, errArrowRowsSetColumnValues, err) + return ars.scanError } return nil } diff --git a/internal/rows/arrowbased/arrowRows_test.go b/internal/rows/arrowbased/arrowRows_test.go index 64e9c662..1a13762b 100644 --- a/internal/rows/arrowbased/arrowRows_test.go +++ b/internal/rows/arrowbased/arrowRows_test.go @@ -1613,9 +1613,10 @@ func TestArrowRowScanner(t *testing.T) { } type fakeColumnValues struct { - fnValue func(int) any - fnIsNull func(int) bool - fnRelease func() + fnValue func(int) any + fnIsNull func(int) bool + fnRelease func() + fnSetValueArray func(arrow.ArrayData) error } func (fc *fakeColumnValues) Value(i int) (any, error) { @@ -1639,6 +1640,9 @@ func (fc *fakeColumnValues) Release() { } func (cv *fakeColumnValues) SetValueArray(colData arrow.ArrayData) error { + if cv.fnSetValueArray != nil { + return cv.fnSetValueArray(colData) + } return nil } diff --git a/internal/rows/arrowbased/cellReaders.go b/internal/rows/arrowbased/cellReaders.go index 56668fe3..ff591d54 100644 --- a/internal/rows/arrowbased/cellReaders.go +++ b/internal/rows/arrowbased/cellReaders.go @@ -14,6 +14,8 @@ type columnReader func(int) (any, error) var errNativeInterval = errors.New("unsupported native interval") +// arrays must be the arrays assigned to the holders by setRecord: the bitmap +// shortcut must read validity from the same data as the value reader. func (rv *rowValues) bindReaders(columns []colInfo, cfg config.ArrowConfig, arrays []arrow.Array) { if len(rv.readers) != len(rv.columnValueHolders) { rv.readers = make([]columnReader, len(rv.columnValueHolders)) diff --git a/internal/rows/arrowbased/cellReaders_test.go b/internal/rows/arrowbased/cellReaders_test.go index fcff67b8..bbf4374b 100644 --- a/internal/rows/arrowbased/cellReaders_test.go +++ b/internal/rows/arrowbased/cellReaders_test.go @@ -142,7 +142,7 @@ func TestBoundReadersRebindAndRelease(t *testing.T) { require.Equal(t, int32(402), destination[0]) } -func TestBoundReadersSurviveRecordRelease(t *testing.T) { +func TestBoundReadersPreserveValuesAfterCallerRelease(t *testing.T) { pool := memory.NewCheckedAllocator(memory.DefaultAllocator) defer pool.AssertSize(t, 0) builder := array.NewInt32Builder(pool) @@ -374,7 +374,7 @@ func TestBoundScanRowAfterCloseFails(t *testing.T) { var output bytes.Buffer scanner.DBSQLLogger = &dbsqllog.DBSQLLogger{Logger: dbsqllog.Logger.Output(&output)} for _, row := range []int64{41, 42} { - require.EqualError(t, scanner.ScanRow(destination, row), "databricks: driver error: row scanner closed") + require.EqualError(t, scanner.ScanRow(destination, row), "databricks: driver error: databricks: row scanner closed") require.Equal(t, int32(1234567), destination[0]) } require.Empty(t, output.String()) @@ -407,13 +407,84 @@ func TestBoundScanRowRequiresHoldersAndReaders(t *testing.T) { scanner.rowValues.readers = nil } require.NotPanics(t, func() { - require.ErrorContains(t, scanner.ScanRow(destination, 41), "row scanner column readers and holders do not match destination") + require.ErrorContains(t, scanner.ScanRow(destination, 41), errArrowRowsReaderMismatch) }) require.Equal(t, int32(1234567), destination[0]) }) } } +func TestBoundScanRowRejectsExtraDestinationColumns(t *testing.T) { + builder := array.NewInt32Builder(memory.DefaultAllocator) + defer builder.Release() + builder.Append(7) + values := builder.NewArray() + defer values.Release() + scanner := readerTestScanner([]arrow.Field{{Name: "number", Type: arrow.PrimitiveTypes.Int32}}, []cli_service.TTypeId{cli_service.TTypeId_INT_TYPE}, config.ArrowConfig{}, time.UTC, []arrow.Array{values}) + defer scanner.Close() + destination := []driver.Value{"first", "second"} + require.ErrorContains(t, scanner.ScanRow(destination, 41), errArrowRowsReaderMismatch) + require.Equal(t, []driver.Value{"first", "second"}, destination) +} + +func TestRowValuesSetRecordRequiresReaders(t *testing.T) { + builder := array.NewInt32Builder(memory.DefaultAllocator) + defer builder.Release() + builder.Append(7) + values := builder.NewArray() + defer values.Release() + schema := arrow.NewSchema([]arrow.Field{{Name: "number", Type: arrow.PrimitiveTypes.Int32}}, nil) + record := &sparkArrowRecord{Delimiter: rowscanner.NewDelimiter(41, 1), RecordBatch: array.NewRecordBatch(schema, []arrow.Array{values}, 1)} + defer record.Release() + containers := newRowValues(rowscanner.NewDelimiter(39, 2), []columnValues{nil}) + defer containers.Close() + containers.readers = []columnReader{func(int) (any, error) { return "stale", nil }} + require.ErrorContains(t, containers.setRecord(record, []colInfo{{dbType: cli_service.TTypeId_INT_TYPE}}, config.ArrowConfig{}), errArrowRowsReaderMismatch) + require.Nil(t, containers.readers) + require.Zero(t, containers.Count()) + require.False(t, containers.Contains(39)) + require.False(t, containers.Contains(41)) +} + +func TestBoundScanRowSetRecordFailureIsSticky(t *testing.T) { + builder := array.NewInt32Builder(memory.DefaultAllocator) + defer builder.Release() + builder.Append(7) + builder.AppendNull() + values := builder.NewArray() + defer values.Release() + scanner := readerTestScanner([]arrow.Field{{Name: "number", Type: arrow.PrimitiveTypes.Int32, Nullable: true}}, []cli_service.TTypeId{cli_service.TTypeId_INT_TYPE}, config.ArrowConfig{}, time.UTC, []arrow.Array{values}, []arrow.Array{values}) + defer scanner.Close() + setError := fmt.Errorf("set failed") + setCalls := 0 + scanner.rowValues = newRowValues(rowscanner.NewDelimiter(39, 2), []columnValues{&fakeColumnValues{ + fnValue: func(row int) any { return values.(*array.Int32).Value(row) }, + fnSetValueArray: func(arrow.ArrayData) error { + setCalls++ + if setCalls == 1 { + return setError + } + return nil + }, + }}) + scanner.rowValues.readers = []columnReader{func(int) (any, error) { return "stale", nil }} + destination := []driver.Value{"unchanged"} + first := scanner.ScanRow(destination, 41) + require.EqualError(t, first, "databricks: driver error: databricks: failed setting column values: set failed") + require.ErrorIs(t, first, setError) + require.Nil(t, scanner.rowValues.readers) + require.Zero(t, scanner.rowValues.Count()) + require.False(t, scanner.rowValues.Contains(39)) + for _, row := range []int64{39, 41, 42, 43, 44} { + require.NotPanics(t, func() { + require.Same(t, first, scanner.ScanRow(destination, row)) + }) + require.Equal(t, []driver.Value{"unchanged"}, destination) + } + require.Equal(t, 1, setCalls) + require.Equal(t, 1, scanner.batchIterator.(*fakeBatchIterator).callCount) +} + func TestBoundUnknownHolderOwnsNullSemantics(t *testing.T) { builder := array.NewInt32Builder(memory.DefaultAllocator) defer builder.Release() diff --git a/internal/rows/arrowbased/columnValues.go b/internal/rows/arrowbased/columnValues.go index 40a2e824..d4615987 100644 --- a/internal/rows/arrowbased/columnValues.go +++ b/internal/rows/arrowbased/columnValues.go @@ -53,6 +53,10 @@ func (rv *rowValues) setRecord(record SparkArrowRecord, columns []colInfo, cfg c } } rv.bindReaders(columns, cfg, record.Columns()) + if len(rv.readers) != len(rv.columnValueHolders) { + rv.readers = nil + return errors.New(errArrowRowsReaderMismatch) + } rv.Delimiter = rowscanner.NewDelimiter(record.Start(), record.Count()) return nil } diff --git a/internal/rows/arrowbased/errors.go b/internal/rows/arrowbased/errors.go index 5d3af9bd..53bb6cde 100644 --- a/internal/rows/arrowbased/errors.go +++ b/internal/rows/arrowbased/errors.go @@ -13,6 +13,9 @@ var errArrowRowsConvertSchema = "databricks: arrow row scanner failed to convert var errArrowRowsSerializeSchema = "databricks: arrow row scanner failed to serialize schema" var errArrowRowsToTimestampFn = "databricks: arrow row scanner failed getting toTimestamp function" var errArrowRowsMakeColumnValueContainers = "databricks: failed creating column value container" +var errArrowRowsSetColumnValues = "databricks: failed setting column values" +var errArrowRowsScannerClosed = "databricks: row scanner closed" +var errArrowRowsReaderMismatch = "databricks: row scanner column readers and holders do not match destination" var errArrowRowsNotArrowFormat = "databricks: result set is not in arrow format" const errArrowRowsCloudFetchDownloadFailure = "cloud fetch batch loader failed to download results" From 480919564cd44d9e4157beb572811649dc0c5dda Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Mon, 30 Nov 2026 23:06:26 +0000 Subject: [PATCH 08/11] test(thrift): exercise retry within a partially consumed batch Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- internal/rows/arrowbased/cellReaders_test.go | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/internal/rows/arrowbased/cellReaders_test.go b/internal/rows/arrowbased/cellReaders_test.go index bbf4374b..74b85379 100644 --- a/internal/rows/arrowbased/cellReaders_test.go +++ b/internal/rows/arrowbased/cellReaders_test.go @@ -447,14 +447,22 @@ func TestRowValuesSetRecordRequiresReaders(t *testing.T) { } func TestBoundScanRowSetRecordFailureIsSticky(t *testing.T) { - builder := array.NewInt32Builder(memory.DefaultAllocator) + pool := memory.NewCheckedAllocator(memory.DefaultAllocator) + defer pool.AssertSize(t, 0) + builder := array.NewInt32Builder(pool) defer builder.Release() builder.Append(7) builder.AppendNull() values := builder.NewArray() defer values.Release() - scanner := readerTestScanner([]arrow.Field{{Name: "number", Type: arrow.PrimitiveTypes.Int32, Nullable: true}}, []cli_service.TTypeId{cli_service.TTypeId_INT_TYPE}, config.ArrowConfig{}, time.UTC, []arrow.Array{values}, []arrow.Array{values}) + scanner := readerTestScanner([]arrow.Field{{Name: "number", Type: arrow.PrimitiveTypes.Int32, Nullable: true}}, []cli_service.TTypeId{cli_service.TTypeId_INT_TYPE}, config.ArrowConfig{}, time.UTC, []arrow.Array{values}) defer scanner.Close() + batch := scanner.batchIterator.(*fakeBatchIterator).batches[0].(*sparkArrowBatch) + batch.arrowRecords = append(batch.arrowRecords, &sparkArrowRecord{ + Delimiter: rowscanner.NewDelimiter(43, 2), RecordBatch: array.NewRecordBatch(scanner.arrowSchema, []arrow.Array{values}, 2), + }) + batch.Delimiter = rowscanner.NewDelimiter(41, 4) + scanner.Delimiter = batch.Delimiter setError := fmt.Errorf("set failed") setCalls := 0 scanner.rowValues = newRowValues(rowscanner.NewDelimiter(39, 2), []columnValues{&fakeColumnValues{ From a2159a880328af3f4faf2fccfcbc501c8eb8d57f Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Mon, 30 Nov 2026 23:16:59 +0000 Subject: [PATCH 09/11] perf(thrift): keep closed checks on the scan fast path Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- internal/rows/arrowbased/arrowRows.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/internal/rows/arrowbased/arrowRows.go b/internal/rows/arrowbased/arrowRows.go index 46bef323..65c82d9b 100644 --- a/internal/rows/arrowbased/arrowRows.go +++ b/internal/rows/arrowbased/arrowRows.go @@ -200,6 +200,10 @@ func (ars *arrowRowScanner) ScanRow( destination []driver.Value, rowNumber int64) dbsqlerr.DBError { + if ars != nil && ars.closed { + return dbsqlerrint.NewDriverError(ars.ctx, errArrowRowsScannerClosed, nil) + } + // load the Arrow batch for the specified row, if necessary err := ars.loadBatchFor(rowNumber) if err != nil { @@ -248,10 +252,6 @@ func (ars *arrowRowScanner) loadBatchFor(rowNumber int64) dbsqlerr.DBError { if ars == nil { return dbsqlerrint.NewDriverError(context.Background(), errArrowRowsNoArrowBatches, nil) } - if ars.closed { - return dbsqlerrint.NewDriverError(ars.ctx, errArrowRowsScannerClosed, nil) - } - if ars.batchIterator == nil { return dbsqlerrint.NewDriverError(ars.ctx, errArrowRowsNoArrowBatches, nil) } From 8acc4dbb6f36bf4151130351668639f57e4f2db2 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Tue, 1 Dec 2026 00:21:45 +0000 Subject: [PATCH 10/11] fix(thrift): cover scanner widths and log setup failures once Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- CHANGELOG.md | 2 +- internal/rows/arrowbased/arrowRows.go | 1 + internal/rows/arrowbased/cellReaders.go | 1 + internal/rows/arrowbased/cellReaders_test.go | 30 +++++++++++++++++++- 4 files changed, 32 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e6df0792..d700a7ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ ### Driver changes - Reduce Thrift row-scan CPU by binding scalar readers and null/type handling once per Arrow record (databricks/databricks-sql-go#602). -- **Behavior change:** Closed Thrift Arrow row scanners return an explicit error without logging an ERROR instead of stale values; destinations with more columns than Arrow holders now error instead of receiving NULL for missing columns (databricks/databricks-sql-go#602). +- **Behavior change:** Closed Thrift Arrow row scanners return an explicit error without logging an ERROR instead of stale values; a destination whose column count differs from the Arrow holders now errors instead of filling leading columns or NULL-padding missing columns (databricks/databricks-sql-go#602). - Render Thrift ARRAY, MAP and STRUCT values in linear time (databricks/databricks-sql-go#596). - **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). diff --git a/internal/rows/arrowbased/arrowRows.go b/internal/rows/arrowbased/arrowRows.go index 65c82d9b..2e9e20c0 100644 --- a/internal/rows/arrowbased/arrowRows.go +++ b/internal/rows/arrowbased/arrowRows.go @@ -302,6 +302,7 @@ func (ars *arrowRowScanner) loadBatchFor(rowNumber int64) dbsqlerr.DBError { } if err := ars.rowValues.setRecord(sar, ars.colInfo, ars.ArrowConfig); err != nil { + ars.Err(err).Msg(errArrowRowsSetColumnValues) ars.scanError = dbsqlerrint.NewDriverError(ars.ctx, errArrowRowsSetColumnValues, err) return ars.scanError } diff --git a/internal/rows/arrowbased/cellReaders.go b/internal/rows/arrowbased/cellReaders.go index ff591d54..bc68a87e 100644 --- a/internal/rows/arrowbased/cellReaders.go +++ b/internal/rows/arrowbased/cellReaders.go @@ -16,6 +16,7 @@ var errNativeInterval = errors.New("unsupported native interval") // arrays must be the arrays assigned to the holders by setRecord: the bitmap // shortcut must read validity from the same data as the value reader. +// Known holders trust a zero null count without reading the bitmap. func (rv *rowValues) bindReaders(columns []colInfo, cfg config.ArrowConfig, arrays []arrow.Array) { if len(rv.readers) != len(rv.columnValueHolders) { rv.readers = make([]columnReader, len(rv.columnValueHolders)) diff --git a/internal/rows/arrowbased/cellReaders_test.go b/internal/rows/arrowbased/cellReaders_test.go index 74b85379..31d44415 100644 --- a/internal/rows/arrowbased/cellReaders_test.go +++ b/internal/rows/arrowbased/cellReaders_test.go @@ -10,7 +10,9 @@ import ( "github.com/apache/arrow-go/v18/arrow" "github.com/apache/arrow-go/v18/arrow/array" + "github.com/apache/arrow-go/v18/arrow/bitutil" "github.com/apache/arrow-go/v18/arrow/memory" + "github.com/rs/zerolog" "github.com/stretchr/testify/require" "github.com/databricks/databricks-sql-go/v2/internal/arrowscan" @@ -318,7 +320,7 @@ func TestBoundUnknownNullCountWithoutBitmap(t *testing.T) { } } -func TestBoundUnknownNullCountWithBitmap(t *testing.T) { +func TestBoundUnknownZeroNullCountUsesDirectReader(t *testing.T) { builder := array.NewInt32Builder(memory.DefaultAllocator) defer builder.Release() builder.AppendNull() @@ -335,6 +337,11 @@ func TestBoundUnknownNullCountWithBitmap(t *testing.T) { require.NoError(t, scanner.ScanRow(destination, 41)) require.Equal(t, int32(1234567), destination[0]) require.Equal(t, 1, counter.reads) + require.Zero(t, values.Data().NullN()) + bitutil.ClearBit(values.NullBitmapBytes(), values.Data().Offset()) + require.True(t, values.IsNull(0)) + require.NoError(t, scanner.ScanRow(destination, 41)) + require.Equal(t, int32(1234567), destination[0]) } type missingBitmapArray struct { @@ -427,6 +434,22 @@ func TestBoundScanRowRejectsExtraDestinationColumns(t *testing.T) { require.Equal(t, []driver.Value{"first", "second"}, destination) } +func TestBoundScanRowRejectsNarrowDestination(t *testing.T) { + builder := array.NewInt32Builder(memory.DefaultAllocator) + defer builder.Release() + builder.Append(7) + values := builder.NewArray() + defer values.Release() + scanner := readerTestScanner([]arrow.Field{ + {Name: "first", Type: arrow.PrimitiveTypes.Int32}, + {Name: "second", Type: arrow.PrimitiveTypes.Int32}, + }, []cli_service.TTypeId{cli_service.TTypeId_INT_TYPE, cli_service.TTypeId_INT_TYPE}, config.ArrowConfig{}, time.UTC, []arrow.Array{values, values}) + defer scanner.Close() + destination := []driver.Value{"unchanged"} + require.ErrorContains(t, scanner.ScanRow(destination, 41), errArrowRowsReaderMismatch) + require.Equal(t, []driver.Value{"unchanged"}, destination) +} + func TestRowValuesSetRecordRequiresReaders(t *testing.T) { builder := array.NewInt32Builder(memory.DefaultAllocator) defer builder.Release() @@ -463,6 +486,8 @@ func TestBoundScanRowSetRecordFailureIsSticky(t *testing.T) { }) batch.Delimiter = rowscanner.NewDelimiter(41, 4) scanner.Delimiter = batch.Delimiter + var output bytes.Buffer + scanner.DBSQLLogger = &dbsqllog.DBSQLLogger{Logger: zerolog.New(&output)} setError := fmt.Errorf("set failed") setCalls := 0 scanner.rowValues = newRowValues(rowscanner.NewDelimiter(39, 2), []columnValues{&fakeColumnValues{ @@ -491,6 +516,9 @@ func TestBoundScanRowSetRecordFailureIsSticky(t *testing.T) { } require.Equal(t, 1, setCalls) require.Equal(t, 1, scanner.batchIterator.(*fakeBatchIterator).callCount) + require.Equal(t, 1, bytes.Count(output.Bytes(), []byte(`"level":"error"`))) + require.Contains(t, output.String(), errArrowRowsSetColumnValues) + require.Contains(t, output.String(), setError.Error()) } func TestBoundUnknownHolderOwnsNullSemantics(t *testing.T) { From ce04b64d5dcfd3b35a3724f1ba6986a4fd82c6d2 Mon Sep 17 00:00:00 2001 From: Vu Anh Phung Date: Tue, 1 Dec 2026 00:35:46 +0000 Subject: [PATCH 11/11] docs: describe sticky Arrow column setup failures Signed-off-by: Vu Anh Phung Co-authored-by: Isaac --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bd0f6643..14bb29cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ - Honor `WithPort` and the DSN port on the kernel backend, including after automatic Reyden recovery, instead of rejecting a non-default port. IPv6 hosts need brackets, and a port the kernel rejects returns an error wrapping both `ErrInvalidKernelConfig` and `ErrNotSupportedByKernel`. - Reduce Thrift row-scan CPU by binding scalar readers and null/type handling once per Arrow record (databricks/databricks-sql-go#602). -- **Behavior change:** Closed Thrift Arrow row scanners return an explicit error without logging an ERROR instead of stale values; a destination whose column count differs from the Arrow holders now errors instead of filling leading columns or NULL-padding missing columns (databricks/databricks-sql-go#602). +- **Behavior change:** Closed Thrift Arrow row scanners return an explicit error without logging an ERROR instead of stale values; a destination whose column count differs from the Arrow holders now errors instead of filling leading columns or NULL-padding missing columns. Column-value setup failures now stop scanning and are retained for subsequent scans instead of only being logged and ignored (databricks/databricks-sql-go#602). - Render Thrift ARRAY, MAP and STRUCT values in linear time (databricks/databricks-sql-go#596). - **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).