Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Release History

## Unreleased

### Driver changes

- **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).

## v2.0.0 (2026-11-23)

### Breaking changes
Expand Down
56 changes: 56 additions & 0 deletions cloudfetch_benchmark_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package dbsql

import (
"bytes"
"context"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/databricks/databricks-sql-go/v2/internal/cli_service"
"github.com/databricks/databricks-sql-go/v2/internal/rows/arrowbased"
)

func BenchmarkCloudFetchDownload(b *testing.B) {
payload := bytes.Repeat([]byte("cloudfetch"), 512*1024)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write(payload)
}))
defer server.Close()
links := []*cli_service.TSparkArrowResultLink{{FileLink: server.URL, ExpiryTime: time.Now().Add(time.Hour).Unix(), RowCount: 1}}
for _, transport := range []string{"default", "WithTransport"} {
b.Run(transport, func(b *testing.B) {
var options []ConnOption
if transport == "WithTransport" {
options = append(options, WithTransport(http.DefaultTransport))
}
con, err := NewConnector(options...)
if err != nil {
b.Fatal(err)
}
cfg := con.(*connector).cfg
cfg.UseLz4Compression = false
b.ReportAllocs()
b.SetBytes(int64(len(payload)))
b.ResetTimer()
for range b.N {
iterator, err := arrowbased.NewCloudIPCStreamIterator(context.Background(), links, 0, cfg, nil)
if err != nil {
b.Fatal(err)
}
stream, nextErr := iterator.Next()
if nextErr != nil {
iterator.Close()
b.Fatal(nextErr)
}
_, readErr := io.Copy(io.Discard, stream)
iterator.Close()
if readErr != nil {
b.Fatal(readErr)
}
}
})
}
}
10 changes: 4 additions & 6 deletions connector.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,9 @@ func NewConnector(options ...ConnOption) (driver.Connector, error) {
for _, opt := range options {
opt(cfg)
}
if cfg.HTTPClient == nil && cfg.Transport != nil {
cfg.HTTPClient = &http.Client{Transport: cfg.Transport, Timeout: cfg.ClientTimeout}
}
// Covers the DSN path too, which applies ParseDSN's UserConfig as an option.
if cfg.MaxDownloadThreads <= 0 {
logger.Warn().Msgf("databricks: maxDownloadThreads (WithMaxDownloadThreads) value %d is not positive; using the default %d",
Expand Down Expand Up @@ -528,15 +531,10 @@ func WithAuthenticator(authr auth.Authenticator) ConnOption {
}

// WithTransport sets up the transport configuration to be used by the httpclient.
// Thrift CloudFetch downloads also use this transport, with ClientTimeout bounding each attempt.
func WithTransport(t http.RoundTripper) ConnOption {
return func(c *config.Config) {
c.Transport = t

if c.HTTPClient == nil {
c.HTTPClient = &http.Client{
Transport: t,
}
}
}
}

Expand Down
152 changes: 152 additions & 0 deletions connector_cloudfetch_timeout_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
package dbsql

import (
"context"
"database/sql/driver"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"

dbsqlerr "github.com/databricks/databricks-sql-go/v2/errors"
"github.com/databricks/databricks-sql-go/v2/internal/cli_service"
"github.com/databricks/databricks-sql-go/v2/internal/client"
"github.com/databricks/databricks-sql-go/v2/internal/config"
dbsqlerrint "github.com/databricks/databricks-sql-go/v2/internal/errors"
driverrows "github.com/databricks/databricks-sql-go/v2/internal/rows"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

type cloudFetchStallingTransport struct {
cancelled chan<- struct{}
release <-chan struct{}
}

func (transport cloudFetchStallingTransport) RoundTrip(request *http.Request) (*http.Response, error) {
select {
case <-request.Context().Done():
transport.cancelled <- struct{}{}
return nil, request.Context().Err()
case <-transport.release:
return nil, context.Canceled
}
}

func TestCloudFetchClientTimeout(t *testing.T) {
for _, testCase := range []struct {
name string
stallBody bool
withTransport bool
}{
{name: "default/headers"},
{name: "default/body", stallBody: true},
{name: "WithTransport/headers", withTransport: true},
} {
t.Run(testCase.name, func(t *testing.T) {
release := make(chan struct{})
cancelled := make(chan struct{}, 2)
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
if testCase.withTransport {
response.WriteHeader(http.StatusNoContent)
return
}
if testCase.stallBody {
response.Header().Set("Content-Length", "100")
response.WriteHeader(http.StatusOK)
response.(http.Flusher).Flush()
}
select {
case <-request.Context().Done():
cancelled <- struct{}{}
case <-release:
}
}))
defer server.Close()
defer close(release)

options := []ConnOption{func(cfg *config.Config) {
cfg.ClientTimeout = 100 * time.Millisecond
cfg.RetryMax = 0
cfg.UseLz4Compression = false
cfg.MaxDownloadThreads = 2
}}
if testCase.withTransport {
options = append(options, WithTransport(cloudFetchStallingTransport{cancelled: cancelled, release: release}))
}
con, err := NewConnector(options...)
require.NoError(t, err)
cfg := con.(*connector).cfg
fixture, err := os.ReadFile("internal/rows/testdata/directResultsMultipleFetch/ExecuteStatement.json")
require.NoError(t, err)
var execute cli_service.TExecuteStatementResp
require.NoError(t, json.Unmarshal(fixture, &execute))
direct := execute.DirectResults
direct.ResultSet.Results.ArrowBatches = nil
expiry := time.Now().Add(time.Hour).Unix()
direct.ResultSet.Results.ResultLinks = []*cli_service.TSparkArrowResultLink{
{FileLink: server.URL + "/file?sig=SECRET_SIGNATURE", ExpiryTime: expiry, RowCount: 1},
{FileLink: server.URL + "/file?sig=SECRET_SIGNATURE", ExpiryTime: expiry, RowCount: 1, StartRowOffset: 1},
}
format := cli_service.TSparkRowSetType_URL_BASED_SET
direct.ResultSetMetadata.ResultFormat = &format
testClient := &client.TestClient{
FnCloseOperation: func(context.Context, *cli_service.TCloseOperationReq) (*cli_service.TCloseOperationResp, error) {
return &cli_service.TCloseOperationResp{}, nil
},
}
rowSet, err := driverrows.NewRows(context.Background(), nil, testClient, cfg, direct, nil)
require.NoError(t, err)
defer rowSet.Close() //nolint:errcheck

result := make(chan error, 1)
start := time.Now()
go func() { result <- rowSet.Next(make([]driver.Value, len(rowSet.Columns()))) }()
select {
case nextErr := <-result:
require.Error(t, nextErr)
assert.ErrorIs(t, nextErr, dbsqlerr.DriverError)
assert.ErrorIs(t, nextErr, context.DeadlineExceeded)
assert.Equal(t, dbsqlerrint.CategoryChunkDownload, dbsqlerrint.CategoryFromError(nextErr))
assert.NotContains(t, nextErr.Error(), "SECRET_SIGNATURE")
assert.GreaterOrEqual(t, time.Since(start), cfg.ClientTimeout)
case <-time.After(cfg.ClientTimeout + 2*time.Second):
server.CloseClientConnections()
select {
case nextErr := <-result:
assert.Error(t, nextErr)
case <-time.After(2 * time.Second):
t.Fatal("CloudFetch read did not exit after connections closed")
}
t.Fatal("CloudFetch read did not honor ClientTimeout")
}
for range 2 {
select {
case <-cancelled:
case <-time.After(2 * time.Second):
t.Fatal("in-flight CloudFetch request was not cancelled")
}
}
})
}
}

func TestCloudFetchWithTransportClientTimeoutOptionOrder(t *testing.T) {
for _, timeout := range []time.Duration{0, 100 * time.Millisecond, 5 * time.Second} {
for _, order := range []string{"before", "after"} {
t.Run(timeout.String()+"/"+order, func(t *testing.T) {
options := []ConnOption{func(cfg *config.Config) { cfg.ClientTimeout = timeout }, WithTransport(http.DefaultTransport)}
if order == "after" {
options[0], options[1] = options[1], options[0]
}
con, err := NewConnector(options...)
require.NoError(t, err)
require.NotNil(t, con.(*connector).cfg.HTTPClient)
assert.Equal(t, timeout, con.(*connector).cfg.HTTPClient.Timeout)
assert.Same(t, http.DefaultTransport, con.(*connector).cfg.HTTPClient.Transport)
})
}
}
}
2 changes: 1 addition & 1 deletion connector_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ func TestNewConnector(t *testing.T) {
MaxFilesInMemory: 10,
MinTimeToExpiry: 0 * time.Second,
CloudFetchSpeedThresholdMbps: 0.1,
HTTPClient: &http.Client{Transport: roundTripper},
HTTPClient: &http.Client{Transport: roundTripper, Timeout: 900 * time.Second},
}
expectedUserConfig := config.UserConfig{
Host: host,
Expand Down
50 changes: 44 additions & 6 deletions internal/rows/arrowbased/batchloader.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"context"
"fmt"
"io"
"net/url"
"strings"
"time"

Expand Down Expand Up @@ -59,9 +60,13 @@ func NewCloudIPCStreamIterator(
cfg *config.Config,
onFileDownloaded func(downloadMs int64),
) (IPCStreamIterator, dbsqlerr.DBError) {
httpClient := http.DefaultClient
if cfg.HTTPClient != nil {
httpClient = cfg.HTTPClient
httpClient := cfg.HTTPClient
if httpClient == nil {
client := *http.DefaultClient
if cfg.ClientTimeout > 0 && (client.Timeout <= 0 || client.Timeout > cfg.ClientTimeout) {
client.Timeout = cfg.ClientTimeout
}
httpClient = &client
}

bi := &cloudIPCStreamIterator{
Expand Down Expand Up @@ -399,6 +404,37 @@ func logCloudFetchSpeed(fullURL string, contentLength int64, duration time.Durat
}
}

func redactCloudFetchError(err error) error {
urlErr, ok := err.(*url.Error)
if !ok {
return err
}
redacted := *urlErr
redacted.URL, _, _ = strings.Cut(urlErr.URL, "?")
redacted.Err = redactCloudFetchError(urlErr.Err)
return &redacted
}

type redactedCloudFetchError struct {
cause error
rawQuery string
}

func (downloadErr redactedCloudFetchError) Error() string {
if downloadErr.rawQuery == "" {
return downloadErr.cause.Error()
}
return strings.ReplaceAll(downloadErr.cause.Error(), downloadErr.rawQuery, "[REDACTED]")
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
}

func (downloadErr redactedCloudFetchError) Unwrap() error {
Comment thread
vuanhphung marked this conversation as resolved.
Resolved
return downloadErr.cause
}

func (downloadErr redactedCloudFetchError) Cause() error {
return downloadErr.cause
}

// fetchBatchBytes downloads a single CloudFetch result link and returns the
// raw response body, still compressed if the server used LZ4. Connection-time
// failures, retryable HTTP statuses, and mid-stream body read failures are
Expand All @@ -421,6 +457,8 @@ func fetchBatchBytes(
if retryMax < 0 {
retryMax = 0
}
_, rawQuery, _ := strings.Cut(link.FileLink, "?")
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
rawQuery, _, _ = strings.Cut(rawQuery, "#")

var (
lastErr error
Expand Down Expand Up @@ -455,7 +493,7 @@ func fetchBatchBytes(

req, err := http.NewRequestWithContext(ctx, "GET", link.FileLink, nil)
if err != nil {
return nil, err
return nil, redactedCloudFetchError{cause: redactCloudFetchError(err), rawQuery: rawQuery}
}
if link.HttpHeaders != nil {
for key, value := range link.HttpHeaders {
Expand All @@ -471,7 +509,7 @@ func fetchBatchBytes(
if ctx.Err() != nil {
return nil, ctx.Err()
}
lastErr = err
lastErr = redactedCloudFetchError{cause: redactCloudFetchError(err), rawQuery: rawQuery}
lastStatus = 0
lastRetryAfter = ""
continue
Expand All @@ -486,7 +524,7 @@ func fetchBatchBytes(
if ctx.Err() != nil {
return nil, ctx.Err()
}
lastErr = readErr
lastErr = redactedCloudFetchError{cause: redactCloudFetchError(readErr), rawQuery: rawQuery}
lastStatus = 0
lastRetryAfter = ""
continue
Expand Down
5 changes: 3 additions & 2 deletions internal/rows/arrowbased/batchloader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ func TestCloudFetchIterator(t *testing.T) {
assert.NotNil(t, sab)
})

t.Run("should fallback to http.DefaultClient when HTTPClient is nil", func(t *testing.T) {
t.Run("should use a bounded default client 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()))
Expand Down Expand Up @@ -360,7 +360,8 @@ func TestCloudFetchIterator(t *testing.T) {
assert.Nil(t, err)

cbi := bi.(*batchIterator).ipcIterator.(*cloudIPCStreamIterator)
assert.Equal(t, http.DefaultClient, cbi.httpClient)
assert.NotSame(t, http.DefaultClient, cbi.httpClient)
assert.Equal(t, cfg.ClientTimeout, cbi.httpClient.Timeout)

// Verify fetch works with default client
sab, nextErr := bi.Next()
Expand Down
Loading
Loading