Skip to content

Commit 3c548d6

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 3c548d6

6 files changed

Lines changed: 334 additions & 120 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: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package dbsql
33
import (
44
"bytes"
55
"context"
6+
"crypto/sha256"
67
"database/sql"
78
"database/sql/driver"
89
"encoding/json"
@@ -37,6 +38,40 @@ import (
3738
"github.com/stretchr/testify/require"
3839
)
3940

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

‎internal/rows/arrowbased/columnValues.go‎

Lines changed: 95 additions & 119 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"
@@ -210,45 +209,56 @@ type listValueContainer struct {
210209

211210
var _ columnValues = (*listValueContainer)(nil)
212211

212+
type complexValueAppender interface {
213+
appendValue([]byte, int) ([]byte, error)
214+
}
215+
216+
func renderComplexValue(container complexValueAppender, row int) (any, error) {
217+
var buffer [128]byte
218+
value, err := container.appendValue(buffer[:0], row)
219+
if err != nil {
220+
return nil, err
221+
}
222+
return string(value), nil
223+
}
224+
225+
func appendColumnValue(dst []byte, holder columnValues, complex bool, row int) ([]byte, error) {
226+
if holder.IsNull(row) {
227+
return append(dst, "null"...), nil
228+
}
229+
if complex {
230+
return holder.(complexValueAppender).appendValue(dst, row)
231+
}
232+
value, err := holder.Value(row)
233+
if err != nil {
234+
return nil, err
235+
}
236+
return marshalScalar(dst, holder, row, value)
237+
}
238+
213239
func (lvc *listValueContainer) Value(i int) (any, error) {
214240
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-
}
240-
241-
if i < len-1 {
242-
r = r + ","
243-
}
244-
}
245-
246-
r = r + "]"
247-
return r, nil
241+
return renderComplexValue(lvc, i)
248242
}
249243
return nil, nil
250244
}
251245

246+
func (lvc *listValueContainer) appendValue(dst []byte, row int) ([]byte, error) {
247+
dst = append(dst, '[')
248+
start, end := lvc.listArray.ValueOffsets(row)
249+
for index := start; index < end; index++ {
250+
if index > start {
251+
dst = append(dst, ',')
252+
}
253+
var err error
254+
dst, err = appendColumnValue(dst, lvc.values, lvc.complexValue, int(index))
255+
if err != nil {
256+
return nil, err
257+
}
258+
}
259+
return append(dst, ']'), nil
260+
}
261+
252262
func (lvc *listValueContainer) IsNull(i int) bool {
253263
return lvc.listArray.IsNull(i)
254264
}
@@ -283,57 +293,44 @@ var _ columnValues = (*mapValueContainer)(nil)
283293

284294
func (mvc *mapValueContainer) Value(i int) (any, error) {
285295
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 {
293-
return nil, err
294-
}
295-
296-
key, err := marshalScalar(keyScratch[:0], mvc.keys, int(i+s), k)
297-
if err != nil {
298-
return nil, err
299-
}
300-
301-
v, err := mvc.values.Value(int(i + s))
302-
if err != nil {
303-
return nil, err
304-
}
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)
317-
}
318-
319-
if !strings.HasPrefix(string(key), "\"") {
320-
r = r + "\"" + string(key) + "\":"
321-
} else {
322-
r = r + string(key) + ":"
323-
}
324-
325-
r = r + b
326-
if i < len-1 {
327-
r = r + ","
328-
}
329-
}
330-
r = r + "}"
331-
332-
return r, nil
296+
return renderComplexValue(mvc, i)
333297
}
334298
return nil, nil
335299
}
336300

301+
func (mvc *mapValueContainer) appendValue(dst []byte, row int) ([]byte, error) {
302+
dst = append(dst, '{')
303+
start, end := mvc.mapArray.ValueOffsets(row)
304+
var keyScratch [64]byte
305+
for index := start; index < end; index++ {
306+
if index > start {
307+
dst = append(dst, ',')
308+
}
309+
value, err := mvc.keys.Value(int(index))
310+
if err != nil {
311+
return nil, err
312+
}
313+
key, err := marshalScalar(keyScratch[:0], mvc.keys, int(index), value)
314+
if err != nil {
315+
return nil, err
316+
}
317+
quoted := len(key) > 0 && key[0] == '"'
318+
if !quoted {
319+
dst = append(dst, '"')
320+
}
321+
dst = append(dst, key...)
322+
if !quoted {
323+
dst = append(dst, '"')
324+
}
325+
dst = append(dst, ':')
326+
dst, err = appendColumnValue(dst, mvc.values, mvc.complexValue, int(index))
327+
if err != nil {
328+
return nil, err
329+
}
330+
}
331+
return append(dst, '}'), nil
332+
}
333+
337334
func (mvc *mapValueContainer) IsNull(i int) bool {
338335
return mvc.mapArray.IsNull(i)
339336
}
@@ -378,48 +375,27 @@ var _ columnValues = (*structValueContainer)(nil)
378375
// byte-identically — internal/rows/arrowbased/arrowscan_parity_test.go guards it.
379376
func (svc *structValueContainer) Value(i int) (any, error) {
380377
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
378+
return renderComplexValue(svc, i)
419379
}
420380
return nil, nil
421381
}
422382

383+
func (svc *structValueContainer) appendValue(dst []byte, row int) ([]byte, error) {
384+
dst = append(dst, '{')
385+
for index, holder := range svc.fieldValues {
386+
if index > 0 {
387+
dst = append(dst, ',')
388+
}
389+
dst = append(dst, svc.fieldKeys[index]...)
390+
var err error
391+
dst, err = appendColumnValue(dst, holder, svc.complexValue[index], row)
392+
if err != nil {
393+
return nil, err
394+
}
395+
}
396+
return append(dst, '}'), nil
397+
}
398+
423399
func (svc *structValueContainer) IsNull(i int) bool {
424400
return svc.structArray.IsNull(i)
425401
}

‎internal/rows/arrowbased/render_bench_test.go‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,3 +134,74 @@ func BenchmarkRenderNested(b *testing.B) {
134134
arr.Release()
135135
}
136136
}
137+
138+
func BenchmarkRenderWideArray(b *testing.B) {
139+
benchmarkRenderWide(b, "array")
140+
}
141+
142+
func BenchmarkRenderWideMap(b *testing.B) {
143+
benchmarkRenderWide(b, "map")
144+
}
145+
146+
func BenchmarkRenderWideStruct(b *testing.B) {
147+
benchmarkRenderWide(b, "struct")
148+
}
149+
150+
func benchmarkRenderWide(b *testing.B, shape string) {
151+
pool := memory.NewGoAllocator()
152+
for _, width := range []int{5, 50, 500, 1536, 5000} {
153+
var builder array.Builder
154+
switch shape {
155+
case "array":
156+
builder = array.NewListBuilder(pool, arrow.PrimitiveTypes.Float64)
157+
case "map":
158+
builder = array.NewMapBuilder(pool, arrow.PrimitiveTypes.Int64, arrow.PrimitiveTypes.Float64, false)
159+
case "struct":
160+
fields := make([]arrow.Field, width)
161+
for index := range fields {
162+
fields[index] = arrow.Field{Name: "f" + strconv.Itoa(index), Type: arrow.PrimitiveTypes.Float64}
163+
}
164+
builder = array.NewStructBuilder(pool, arrow.StructOf(fields...))
165+
}
166+
switch builder := builder.(type) {
167+
case *array.ListBuilder:
168+
builder.Append(true)
169+
case *array.MapBuilder:
170+
builder.Append(true)
171+
case *array.StructBuilder:
172+
builder.Append(true)
173+
}
174+
for index := 0; index < width; index++ {
175+
value := float64(index)/7 - 0.5
176+
switch builder := builder.(type) {
177+
case *array.ListBuilder:
178+
builder.ValueBuilder().(*array.Float64Builder).Append(value)
179+
case *array.MapBuilder:
180+
builder.KeyBuilder().(*array.Int64Builder).Append(int64(index))
181+
builder.ItemBuilder().(*array.Float64Builder).Append(value)
182+
case *array.StructBuilder:
183+
builder.FieldBuilder(index).(*array.Float64Builder).Append(value)
184+
}
185+
}
186+
values := builder.NewArray()
187+
builder.Release()
188+
b.Run("thrift/"+strconv.Itoa(width), func(b *testing.B) {
189+
holder, err := (&arrowValueContainerMaker{}).makeColumnValueContainer(values.DataType(), time.UTC, nil, nil)
190+
if err != nil {
191+
b.Fatal(err)
192+
}
193+
defer holder.Release()
194+
if err := holder.SetValueArray(values.Data()); err != nil {
195+
b.Fatal(err)
196+
}
197+
b.ReportAllocs()
198+
b.ResetTimer()
199+
for iteration := 0; iteration < b.N; iteration++ {
200+
if _, err := holder.Value(0); err != nil {
201+
b.Fatal(err)
202+
}
203+
}
204+
})
205+
values.Release()
206+
}
207+
}

0 commit comments

Comments
 (0)