-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathbatchloader_test.go
More file actions
489 lines (411 loc) · 12.4 KB
/
batchloader_test.go
File metadata and controls
489 lines (411 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
package arrowbased
import (
"bytes"
"context"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
dbsqlerr "github.com/databricks/databricks-sql-go/errors"
"github.com/databricks/databricks-sql-go/internal/cli_service"
"github.com/databricks/databricks-sql-go/internal/config"
"github.com/pkg/errors"
"github.com/apache/arrow/go/v12/arrow"
"github.com/apache/arrow/go/v12/arrow/array"
"github.com/apache/arrow/go/v12/arrow/ipc"
"github.com/apache/arrow/go/v12/arrow/memory"
"github.com/stretchr/testify/assert"
)
func TestCloudFetchIterator(t *testing.T) {
var handler func(w http.ResponseWriter, r *http.Request)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handler(w, r)
}))
defer server.Close()
t.Run("should fetch all the links", func(t *testing.T) {
cloudFetchHeaders := map[string]string{
"foo": "bar",
}
handler = func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
for name, value := range cloudFetchHeaders {
if values, ok := r.Header[name]; ok {
if values[0] != value {
panic(errors.New("Missing auth headers"))
}
}
}
_, err := w.Write(generateMockArrowBytes(generateArrowRecord()))
if err != nil {
panic(err)
}
}
startRowOffset := int64(100)
links := []*cli_service.TSparkArrowResultLink{
{
FileLink: server.URL,
ExpiryTime: time.Now().Add(10 * time.Minute).Unix(),
StartRowOffset: startRowOffset,
RowCount: 1,
HttpHeaders: cloudFetchHeaders,
},
{
FileLink: server.URL,
ExpiryTime: time.Now().Add(10 * time.Minute).Unix(),
StartRowOffset: startRowOffset + 1,
RowCount: 1,
HttpHeaders: cloudFetchHeaders,
},
}
cfg := config.WithDefaults()
cfg.UseLz4Compression = false
cfg.MaxDownloadThreads = 1
bi, err := NewCloudBatchIterator(
context.Background(),
links,
startRowOffset,
nil,
cfg,
)
if err != nil {
panic(err)
}
// Access the internal structure through the wrapper
wrapper, ok := bi.(*batchIterator)
assert.True(t, ok)
cbi, ok := wrapper.ipcIterator.(*cloudIPCStreamIterator)
assert.True(t, ok)
assert.True(t, bi.HasNext())
assert.Equal(t, cbi.pendingLinks.Len(), len(links))
assert.Equal(t, cbi.downloadTasks.Len(), 0)
// get first link - should succeed
sab1, err2 := bi.Next()
if err2 != nil {
panic(err2)
}
assert.Equal(t, cbi.pendingLinks.Len(), len(links)-1)
assert.Equal(t, cbi.downloadTasks.Len(), 0)
assert.Equal(t, sab1.Start(), startRowOffset)
// get second link - should succeed
sab2, err3 := bi.Next()
if err3 != nil {
panic(err3)
}
assert.Equal(t, cbi.pendingLinks.Len(), len(links)-2)
assert.Equal(t, cbi.downloadTasks.Len(), 0)
assert.Equal(t, sab2.Start(), startRowOffset+sab1.Count())
// all links downloaded, should be no more data
assert.False(t, bi.HasNext())
})
t.Run("should fail on expired link", func(t *testing.T) {
handler = func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, err := w.Write(generateMockArrowBytes(generateArrowRecord()))
if err != nil {
panic(err)
}
}
startRowOffset := int64(100)
links := []*cli_service.TSparkArrowResultLink{
{
FileLink: server.URL,
ExpiryTime: time.Now().Add(10 * time.Minute).Unix(),
StartRowOffset: startRowOffset,
RowCount: 1,
},
{
FileLink: server.URL,
ExpiryTime: time.Now().Add(-10 * time.Minute).Unix(), // expired link
StartRowOffset: startRowOffset + 1,
RowCount: 1,
},
}
cfg := config.WithDefaults()
cfg.UseLz4Compression = false
cfg.MaxDownloadThreads = 1
bi, err := NewCloudBatchIterator(
context.Background(),
links,
startRowOffset,
nil,
cfg,
)
if err != nil {
panic(err)
}
// Access the internal structure through the wrapper
wrapper, ok := bi.(*batchIterator)
assert.True(t, ok)
cbi, ok := wrapper.ipcIterator.(*cloudIPCStreamIterator)
assert.True(t, ok)
assert.True(t, bi.HasNext())
assert.Equal(t, cbi.pendingLinks.Len(), len(links))
assert.Equal(t, cbi.downloadTasks.Len(), 0)
// get first link - should succeed
sab1, err2 := bi.Next()
if err2 != nil {
panic(err2)
}
assert.Equal(t, cbi.pendingLinks.Len(), len(links)-1)
assert.Equal(t, cbi.downloadTasks.Len(), 0)
assert.Equal(t, sab1.Start(), startRowOffset)
// get second link - should fail
_, err3 := bi.Next()
assert.NotNil(t, err3)
assert.ErrorContains(t, err3, dbsqlerr.ErrLinkExpired)
})
t.Run("should fail on HTTP errors", func(t *testing.T) {
startRowOffset := int64(100)
links := []*cli_service.TSparkArrowResultLink{
{
FileLink: server.URL,
ExpiryTime: time.Now().Add(10 * time.Minute).Unix(),
StartRowOffset: startRowOffset,
RowCount: 1,
},
{
FileLink: server.URL,
ExpiryTime: time.Now().Add(10 * time.Minute).Unix(),
StartRowOffset: startRowOffset + 1,
RowCount: 1,
},
}
cfg := config.WithDefaults()
cfg.UseLz4Compression = false
cfg.MaxDownloadThreads = 1
bi, err := NewCloudBatchIterator(
context.Background(),
links,
startRowOffset,
nil,
cfg,
)
if err != nil {
panic(err)
}
// Access the internal structure through the wrapper
wrapper, ok := bi.(*batchIterator)
assert.True(t, ok)
cbi, ok := wrapper.ipcIterator.(*cloudIPCStreamIterator)
assert.True(t, ok)
assert.True(t, bi.HasNext())
assert.Equal(t, cbi.pendingLinks.Len(), len(links))
assert.Equal(t, cbi.downloadTasks.Len(), 0)
// set handler for the first link, which returns some data
handler = func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, err := w.Write(generateMockArrowBytes(generateArrowRecord()))
if err != nil {
panic(err)
}
}
// get first link - should succeed
sab1, err2 := bi.Next()
if err2 != nil {
panic(err2)
}
assert.Equal(t, cbi.pendingLinks.Len(), len(links)-1)
assert.Equal(t, cbi.downloadTasks.Len(), 0)
assert.Equal(t, sab1.Start(), startRowOffset)
// set handler for the first link, which fails with some non-retryable HTTP error
handler = func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
}
// get second link - should fail
_, err3 := bi.Next()
assert.NotNil(t, err3)
assert.ErrorContains(t, err3, fmt.Sprintf("%s %d", "HTTP error", http.StatusNotFound))
})
t.Run("should use custom HTTPClient when provided", func(t *testing.T) {
handler = func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, err := w.Write(generateMockArrowBytes(generateArrowRecord()))
if err != nil {
panic(err)
}
}
startRowOffset := int64(100)
customHTTPClient := &http.Client{
Transport: &http.Transport{MaxIdleConns: 10},
}
cfg := config.WithDefaults()
cfg.UseLz4Compression = false
cfg.MaxDownloadThreads = 1
cfg.UserConfig.CloudFetchConfig.HTTPClient = customHTTPClient
bi, err := NewCloudBatchIterator(
context.Background(),
[]*cli_service.TSparkArrowResultLink{{
FileLink: server.URL,
ExpiryTime: time.Now().Add(10 * time.Minute).Unix(),
StartRowOffset: startRowOffset,
RowCount: 1,
}},
startRowOffset,
nil,
cfg,
)
assert.Nil(t, err)
cbi := bi.(*batchIterator).ipcIterator.(*cloudIPCStreamIterator)
assert.Equal(t, customHTTPClient, cbi.httpClient)
// Verify fetch works
sab, nextErr := bi.Next()
assert.Nil(t, nextErr)
assert.NotNil(t, sab)
})
t.Run("should fallback to http.DefaultClient when HTTPClient is nil", func(t *testing.T) {
handler = func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, err := w.Write(generateMockArrowBytes(generateArrowRecord()))
if err != nil {
panic(err)
}
}
startRowOffset := int64(100)
cfg := config.WithDefaults()
cfg.UseLz4Compression = false
cfg.MaxDownloadThreads = 1
// Explicitly set HTTPClient to nil to verify fallback behavior
cfg.UserConfig.CloudFetchConfig.HTTPClient = nil
bi, err := NewCloudBatchIterator(
context.Background(),
[]*cli_service.TSparkArrowResultLink{{
FileLink: server.URL,
ExpiryTime: time.Now().Add(10 * time.Minute).Unix(),
StartRowOffset: startRowOffset,
RowCount: 1,
}},
startRowOffset,
nil,
cfg,
)
assert.Nil(t, err)
cbi := bi.(*batchIterator).ipcIterator.(*cloudIPCStreamIterator)
assert.Equal(t, http.DefaultClient, cbi.httpClient)
// Verify fetch works with default client
sab, nextErr := bi.Next()
assert.Nil(t, nextErr)
assert.NotNil(t, sab)
})
}
func TestCloudFetchSchemaOverride(t *testing.T) {
// Reproduces ES-1804970: When the server result cache serves Arrow IPC files
// from a prior query, the embedded schema has stale column names. The
// authoritative schema from GetResultSetMetadata must override them.
// IPC data has columns ["id", "name"] (stale, from cached query)
staleRecord := generateArrowRecord()
staleIPCBytes := generateMockArrowBytes(staleRecord)
// Authoritative schema has columns ["x", "y"] (correct, from GetResultSetMetadata)
correctFields := []arrow.Field{
{Name: "x", Type: arrow.PrimitiveTypes.Int32},
{Name: "y", Type: arrow.BinaryTypes.String},
}
correctSchema := arrow.NewSchema(correctFields, nil)
var schemaBuf bytes.Buffer
schemaWriter := ipc.NewWriter(&schemaBuf, ipc.WithSchema(correctSchema))
if err := schemaWriter.Close(); err != nil {
t.Fatal(err)
}
correctSchemaBytes := schemaBuf.Bytes()
// Serve stale IPC data via mock HTTP
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, err := w.Write(staleIPCBytes)
if err != nil {
panic(err)
}
}))
defer server.Close()
t.Run("should override stale column names with authoritative schema", func(t *testing.T) {
links := []*cli_service.TSparkArrowResultLink{
{
FileLink: server.URL,
ExpiryTime: time.Now().Add(10 * time.Minute).Unix(),
StartRowOffset: 0,
RowCount: 3,
},
}
cfg := config.WithDefaults()
cfg.UseLz4Compression = false
cfg.MaxDownloadThreads = 1
bi, err := NewCloudBatchIterator(
context.Background(),
links,
0,
correctSchemaBytes,
cfg,
)
assert.Nil(t, err)
batch, batchErr := bi.Next()
assert.Nil(t, batchErr)
assert.NotNil(t, batch)
rec, recErr := batch.Next()
assert.Nil(t, recErr)
assert.NotNil(t, rec)
// The record schema must use the authoritative names, not the stale ones
assert.Equal(t, "x", rec.Schema().Field(0).Name)
assert.Equal(t, "y", rec.Schema().Field(1).Name)
// Data must be preserved
assert.Equal(t, int64(3), rec.NumRows())
assert.Equal(t, 2, len(rec.Schema().Fields()))
rec.Release()
})
t.Run("should pass through unchanged when no override schema provided", func(t *testing.T) {
links := []*cli_service.TSparkArrowResultLink{
{
FileLink: server.URL,
ExpiryTime: time.Now().Add(10 * time.Minute).Unix(),
StartRowOffset: 0,
RowCount: 3,
},
}
cfg := config.WithDefaults()
cfg.UseLz4Compression = false
cfg.MaxDownloadThreads = 1
bi, err := NewCloudBatchIterator(
context.Background(),
links,
0,
nil,
cfg,
)
assert.Nil(t, err)
batch, batchErr := bi.Next()
assert.Nil(t, batchErr)
rec, recErr := batch.Next()
assert.Nil(t, recErr)
// Without override, the original (stale) column names are preserved
assert.Equal(t, "id", rec.Schema().Field(0).Name)
assert.Equal(t, "name", rec.Schema().Field(1).Name)
rec.Release()
})
}
func generateArrowRecord() arrow.Record {
mem := memory.NewCheckedAllocator(memory.NewGoAllocator())
fields := []arrow.Field{
{Name: "id", Type: arrow.PrimitiveTypes.Int32},
{Name: "name", Type: arrow.BinaryTypes.String},
}
schema := arrow.NewSchema(fields, nil)
builder := array.NewRecordBuilder(mem, schema)
defer builder.Release()
builder.Field(0).(*array.Int32Builder).AppendValues([]int32{1, 2, 3}, nil)
builder.Field(1).(*array.StringBuilder).AppendValues([]string{"one", "two", "three"}, nil)
record := builder.NewRecord()
return record
}
func generateMockArrowBytes(record arrow.Record) []byte {
defer record.Release()
var buf bytes.Buffer
w := ipc.NewWriter(&buf, ipc.WithSchema(record.Schema()))
if err := w.Write(record); err != nil {
return nil
}
if err := w.Write(record); err != nil {
return nil
}
if err := w.Close(); err != nil {
return nil
}
return buf.Bytes()
}