Skip to content

Commit 867b4ce

Browse files
vuanhphungIsaac
andcommitted
fix: render Thrift complex values in linear time
Render nested Thrift ARRAY, MAP and STRUCT values into a shared byte buffer instead of repeatedly copying growing strings, making wide results linear while preserving their existing text representation. Fixes #596 Signed-off-by: Vu Anh Phung <vu.phung@databricks.com> Co-authored-by: Isaac <no-reply@databricks.com>
1 parent 319b145 commit 867b4ce

6 files changed

Lines changed: 721 additions & 110 deletions

File tree

‎.github/workflows/nightly-e2e.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ jobs:
9090
DATABRICKS_PECOTESTING_TOKEN_PERSONAL: ${{ secrets.DATABRICKS_PECOTESTING_TOKEN_PERSONAL }}
9191
run: |
9292
go test -tags e2e -count=1 -v -timeout 15m \
93-
-run 'TestE2EArrow(SchemaBeforeFetching|BatchesSurviveQueryContextCancellation)|TestE2ECloudFetchExactRowCount|TestE2ECloudFetchNonPositiveMaxDownloadThreads|TestE2EDecimalMetadata|TestE2EVariantTypeName|TestE2EGeospatialTypeNames|^TestE2ETime(Results|ArrowResults)$|TestE2ERejectedRequestClosesResponse' .
93+
-run 'TestE2EArrow(SchemaBeforeFetching|BatchesSurviveQueryContextCancellation)|TestE2ECloudFetchExactRowCount|TestE2ECloudFetchNonPositiveMaxDownloadThreads|TestE2EDecimalMetadata|TestE2EComplexRendering|TestE2EVariantTypeName|TestE2EGeospatialTypeNames|^TestE2ETime(Results|ArrowResults)$|TestE2ERejectedRequestClosesResponse' .
9494
9595
kernel-e2e:
9696
name: E2E (kernel backend)

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
### Driver changes
66

7+
- Render Thrift ARRAY, MAP and STRUCT values in linear time (databricks/databricks-sql-go#596).
78
- **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).
89
- **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).
910
- Evict kernel connections when SEA reports a missing or invalid session, and reject later requests locally without replaying the failed statement.

‎driver_e2e_test.go‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,37 @@ import (
3737
"github.com/stretchr/testify/require"
3838
)
3939

40+
func TestE2EComplexRendering(t *testing.T) {
41+
host, httpPath, token := pecoTestingCreds(t)
42+
connector, err := NewConnector(WithServerHostname(host), WithHTTPPath(httpPath), WithAccessToken(token))
43+
require.NoError(t, err)
44+
db := sql.OpenDB(connector)
45+
t.Cleanup(func() { require.NoError(t, db.Close()) })
46+
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
47+
defer cancel()
48+
result, err := db.QueryContext(ctx, `SELECT
49+
transform(sequence(0, 1535), x -> CAST(x AS DOUBLE) / 7 - 0.5D),
50+
map(1, array(1.25D, NULL), 2, array()),
51+
named_struct('items', array(named_struct('id', 1, 'text', 'a"<>&')),
52+
'lookup', map('key', array(1, NULL, 3)))`)
53+
require.NoError(t, err)
54+
defer func() { require.NoError(t, result.Close()) }()
55+
require.True(t, result.Next(), "%v", result.Err())
56+
var wide, mapping, nested string
57+
require.NoError(t, result.Scan(&wide, &mapping, &nested))
58+
values := make([]float64, 1536)
59+
for index := range values {
60+
values[index] = float64(index)/7 - 0.5
61+
}
62+
expected, err := json.Marshal(values)
63+
require.NoError(t, err)
64+
require.Equal(t, string(expected), wide)
65+
require.Equal(t, `{"1":[1.25,null],"2":[]}`, mapping)
66+
require.Equal(t, `{"items":[{"id":1,"text":"a\"\u003c\u003e\u0026"}],"lookup":{"key":[1,null,3]}}`, nested)
67+
require.False(t, result.Next())
68+
require.NoError(t, result.Err())
69+
}
70+
4071
func TestE2EDecimalMetadata(t *testing.T) {
4172
host, httpPath, token := pecoTestingCreds(t)
4273
for _, native := range []bool{false, true} {

‎internal/rows/arrowbased/columnValues.go‎

Lines changed: 113 additions & 109 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package arrowbased
22

33
import (
4-
"strings"
54
"time"
65

76
"github.com/apache/arrow-go/v18/arrow"
@@ -202,6 +201,7 @@ func (cv *columnValuesTyped[X, T]) SetValueArray(colData arrow.ArrayData) error
202201
var _ columnValues = (*columnValuesTyped[*array.Int16, int16])(nil)
203202

204203
type listValueContainer struct {
204+
scratch []byte
205205
listArray array.ListLike
206206
values columnValues
207207
complexValue bool
@@ -210,50 +210,67 @@ type listValueContainer struct {
210210

211211
var _ columnValues = (*listValueContainer)(nil)
212212

213+
type complexValueAppender interface {
214+
appendValue([]byte, int) ([]byte, error)
215+
}
216+
217+
// maxRetainedScratch bounds the render buffer a container keeps between values.
218+
const maxRetainedScratch = 64 << 10
219+
220+
func renderComplexValue(container complexValueAppender, scratch *[]byte, row int) (any, error) {
221+
value, err := container.appendValue((*scratch)[:0], row)
222+
if err != nil {
223+
return nil, err
224+
}
225+
if cap(value) <= maxRetainedScratch {
226+
*scratch = value
227+
}
228+
return string(value), nil
229+
}
230+
231+
func appendColumnValue(dst []byte, holder columnValues, complex bool, row int) ([]byte, error) {
232+
if holder.IsNull(row) {
233+
return append(dst, "null"...), nil
234+
}
235+
if complex {
236+
return holder.(complexValueAppender).appendValue(dst, row)
237+
}
238+
value, err := holder.Value(row)
239+
if err != nil {
240+
return nil, err
241+
}
242+
return marshalScalar(dst, holder, row, value)
243+
}
244+
213245
func (lvc *listValueContainer) Value(i int) (any, error) {
214246
if i < lvc.listArray.Len() {
215-
var scratch [64]byte
216-
r := "["
217-
s, e := lvc.listArray.ValueOffsets(i)
218-
len := int(e - s)
219-
220-
for i := 0; i < len; i++ {
221-
if lvc.values.IsNull(i + int(s)) {
222-
r = r + "null"
223-
} else {
224-
225-
val, err := lvc.values.Value(i + int(s))
226-
if err != nil {
227-
return nil, err
228-
}
229-
230-
if !lvc.complexValue {
231-
vb, err := marshalScalar(scratch[:0], lvc.values, i+int(s), val)
232-
if err != nil {
233-
return nil, err
234-
}
235-
r = r + string(vb)
236-
} else {
237-
r = r + val.(string)
238-
}
239-
}
247+
return renderComplexValue(lvc, &lvc.scratch, i)
248+
}
249+
return nil, nil
250+
}
240251

241-
if i < len-1 {
242-
r = r + ","
243-
}
252+
func (lvc *listValueContainer) appendValue(dst []byte, row int) ([]byte, error) {
253+
dst = append(dst, '[')
254+
start, end := lvc.listArray.ValueOffsets(row)
255+
for index := start; index < end; index++ {
256+
if index > start {
257+
dst = append(dst, ',')
258+
}
259+
var err error
260+
dst, err = appendColumnValue(dst, lvc.values, lvc.complexValue, int(index))
261+
if err != nil {
262+
return nil, err
244263
}
245-
246-
r = r + "]"
247-
return r, nil
248264
}
249-
return nil, nil
265+
return append(dst, ']'), nil
250266
}
251267

252268
func (lvc *listValueContainer) IsNull(i int) bool {
253269
return lvc.listArray.IsNull(i)
254270
}
255271

256272
func (lvc *listValueContainer) Release() {
273+
lvc.scratch = nil
257274
if lvc.listArray != nil {
258275
lvc.listArray.Release()
259276
}
@@ -264,6 +281,7 @@ func (lvc *listValueContainer) Release() {
264281
}
265282

266283
func (lvc *listValueContainer) SetValueArray(colData arrow.ArrayData) error {
284+
lvc.scratch = nil
267285
lvc.listArray = array.NewListData(colData)
268286
lvs := lvc.listArray.ListValues()
269287
err := lvc.values.SetValueArray(lvs.Data())
@@ -272,9 +290,11 @@ func (lvc *listValueContainer) SetValueArray(colData arrow.ArrayData) error {
272290
}
273291

274292
type mapValueContainer struct {
293+
scratch []byte
275294
mapArray *array.Map
276295
keys columnValues
277296
values columnValues
297+
complexKey bool
278298
complexValue bool
279299
mapArrayType *arrow.MapType
280300
}
@@ -283,62 +303,62 @@ var _ columnValues = (*mapValueContainer)(nil)
283303

284304
func (mvc *mapValueContainer) Value(i int) (any, error) {
285305
if i < mvc.mapArray.Len() {
286-
s, e := mvc.mapArray.ValueOffsets(i)
287-
len := e - s
288-
var keyScratch, scratch [64]byte
289-
r := "{"
290-
for i := int64(0); i < len; i++ {
291-
k, err := mvc.keys.Value(int(i + s))
292-
if err != nil {
306+
return renderComplexValue(mvc, &mvc.scratch, i)
307+
}
308+
return nil, nil
309+
}
310+
311+
func (mvc *mapValueContainer) appendValue(dst []byte, row int) ([]byte, error) {
312+
dst = append(dst, '{')
313+
start, end := mvc.mapArray.ValueOffsets(row)
314+
var keyScratch [64]byte
315+
for index := start; index < end; index++ {
316+
if index > start {
317+
dst = append(dst, ',')
318+
}
319+
var err error
320+
if mvc.complexKey {
321+
// Render the key in place, then quote it as marshalScalar quotes a string.
322+
mark := len(dst)
323+
if dst, err = mvc.keys.(complexValueAppender).appendValue(dst, int(index)); err != nil {
293324
return nil, err
294325
}
295-
296-
key, err := marshalScalar(keyScratch[:0], mvc.keys, int(i+s), k)
297-
if err != nil {
326+
if dst, err = jsonfmt.Append(dst[:mark], string(dst[mark:])); err != nil {
298327
return nil, err
299328
}
300-
301-
v, err := mvc.values.Value(int(i + s))
302-
if err != nil {
329+
} else {
330+
var value any
331+
if value, err = mvc.keys.Value(int(index)); err != nil {
303332
return nil, err
304333
}
305-
306-
var b string
307-
if mvc.values.IsNull(int(i + s)) {
308-
b = "null"
309-
} else if mvc.complexValue {
310-
b = v.(string)
311-
} else {
312-
vb, err := marshalScalar(scratch[:0], mvc.values, int(i+s), v)
313-
if err != nil {
314-
return nil, err
315-
}
316-
b = string(vb)
334+
var key []byte
335+
if key, err = marshalScalar(keyScratch[:0], mvc.keys, int(index), value); err != nil {
336+
return nil, err
317337
}
318-
319-
if !strings.HasPrefix(string(key), "\"") {
320-
r = r + "\"" + string(key) + "\":"
321-
} else {
322-
r = r + string(key) + ":"
338+
quoted := len(key) > 0 && key[0] == '"'
339+
if !quoted {
340+
dst = append(dst, '"')
323341
}
324-
325-
r = r + b
326-
if i < len-1 {
327-
r = r + ","
342+
dst = append(dst, key...)
343+
if !quoted {
344+
dst = append(dst, '"')
328345
}
329346
}
330-
r = r + "}"
331-
332-
return r, nil
347+
dst = append(dst, ':')
348+
dst, err = appendColumnValue(dst, mvc.values, mvc.complexValue, int(index))
349+
if err != nil {
350+
return nil, err
351+
}
333352
}
334-
return nil, nil
353+
return append(dst, '}'), nil
335354
}
336355

337356
func (mvc *mapValueContainer) IsNull(i int) bool {
338357
return mvc.mapArray.IsNull(i)
339358
}
340359

341360
func (mvc *mapValueContainer) Release() {
361+
mvc.scratch = nil
342362
if mvc.mapArray != nil {
343363
mvc.mapArray.Release()
344364
}
@@ -353,6 +373,8 @@ func (mvc *mapValueContainer) Release() {
353373
}
354374

355375
func (mvc *mapValueContainer) SetValueArray(colData arrow.ArrayData) error {
376+
mvc.scratch = nil
377+
_, mvc.complexKey = mvc.keys.(complexValueAppender)
356378
mvc.mapArray = array.NewMapData(colData)
357379
err := mvc.values.SetValueArray(mvc.mapArray.Items().Data())
358380
if err != nil {
@@ -364,6 +386,7 @@ func (mvc *mapValueContainer) SetValueArray(colData arrow.ArrayData) error {
364386
}
365387

366388
type structValueContainer struct {
389+
scratch []byte
367390
structArray *array.Struct
368391
fieldKeys []string // precomputed JSON-escaped `"name":` prefixes, one per field
369392
complexValue []bool
@@ -378,53 +401,33 @@ var _ columnValues = (*structValueContainer)(nil)
378401
// byte-identically — internal/rows/arrowbased/arrowscan_parity_test.go guards it.
379402
func (svc *structValueContainer) Value(i int) (any, error) {
380403
if i < svc.structArray.Len() {
381-
var scratch [64]byte
382-
r := "{"
383-
for j := range svc.fieldValues {
384-
// fieldKeys[j] is the precomputed JSON-escaped `"name":` prefix (built
385-
// once at construction). Escaping matters — a raw `"` + name + `"` concat
386-
// produces invalid JSON for a name with a quote/backslash/control char
387-
// (`a"b` → `{"a"b":...}`) — but doing it per row would re-marshal the same
388-
// constant strings N_rows × N_fields times on this hot path.
389-
r = r + svc.fieldKeys[j]
390-
391-
if svc.fieldValues[j].IsNull(int(i)) {
392-
r = r + "null"
393-
} else {
394-
v, err := svc.fieldValues[j].Value(int(i))
395-
if err != nil {
396-
return nil, err
397-
}
398-
399-
var b string
400-
if svc.complexValue[j] {
401-
b = v.(string)
402-
} else {
403-
vb, err := marshalScalar(scratch[:0], svc.fieldValues[j], int(i), v)
404-
if err != nil {
405-
return nil, err
406-
}
407-
b = string(vb)
408-
}
409-
410-
r = r + b
411-
}
412-
if j < len(svc.fieldValues)-1 {
413-
r = r + ","
414-
}
415-
}
416-
r = r + "}"
417-
418-
return r, nil
404+
return renderComplexValue(svc, &svc.scratch, i)
419405
}
420406
return nil, nil
421407
}
422408

409+
func (svc *structValueContainer) appendValue(dst []byte, row int) ([]byte, error) {
410+
dst = append(dst, '{')
411+
for index, holder := range svc.fieldValues {
412+
if index > 0 {
413+
dst = append(dst, ',')
414+
}
415+
dst = append(dst, svc.fieldKeys[index]...)
416+
var err error
417+
dst, err = appendColumnValue(dst, holder, svc.complexValue[index], row)
418+
if err != nil {
419+
return nil, err
420+
}
421+
}
422+
return append(dst, '}'), nil
423+
}
424+
423425
func (svc *structValueContainer) IsNull(i int) bool {
424426
return svc.structArray.IsNull(i)
425427
}
426428

427429
func (svc *structValueContainer) Release() {
430+
svc.scratch = nil
428431
if svc.structArray != nil {
429432
svc.structArray.Release()
430433
}
@@ -437,6 +440,7 @@ func (svc *structValueContainer) Release() {
437440
}
438441

439442
func (svc *structValueContainer) SetValueArray(colData arrow.ArrayData) error {
443+
svc.scratch = nil
440444
svc.structArray = array.NewStructData(colData)
441445
for i := range svc.fieldValues {
442446
err := svc.fieldValues[i].SetValueArray(svc.structArray.Field(i).Data())

0 commit comments

Comments
 (0)