diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b736e9a..c266790e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ # Release History +## Unreleased +- Honor `WithCloudFetch(false)` / `useCloudFetch=false` on the kernel backend to fetch complete results without cloud-storage downloads. The option overrides conflicting session configuration and remains effective after automatic backend recovery. Servers without paged inline support return a configuration error; the driver does not fall back to storage downloads. + ## v1.19.0 (2026-11-04) - Upgrade the SQL kernel bindings to v1.4.0. - Upgrade go-oidc to v3.21.0 (go-jose v4.1.6) and x/oauth2 to v0.36.0 to address go-jose/v3 security findings (databricks/databricks-sql-go#526). diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 35a4ad0e..ee0a37b6 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -113,11 +113,11 @@ Notes: - Boolean-valued keys should use the exact strings `"true"` / `"false"` — the kernel does not pre-validate values and forwards them as-is. -- **`CAN_CLOUD_DOWNLOAD` is not a valid SEA session conf**: it may be accepted at - CreateSession and rejected by the first statement with `CONFIG_NOT_AVAILABLE`. - To disable Cloud Fetch on the kernel path, set the client-result conf - `cloudfetch_enabled=false`; `WithCloudFetch(false)` is a Thrift option and is inert - on the kernel path. +- `WithCloudFetch(false)` fetches complete results through the SQL connection + without cloud-storage downloads. On the kernel backend, this option takes + precedence over conflicting session parameters. Servers without paged inline + support return a configuration error at session creation or statement execution; + the driver does not fall back to storage downloads. ### Kernel client-result confs @@ -129,7 +129,7 @@ Thrift options where available. | DSN / session-conf key | Dedicated connector option | Thrift | Kernel | Default | Notes | |---|---|:---:|:---:|---|---| -| `cloudfetch_enabled` | *(none; use `WithSessionParams`)* | ⚠️ | ✅ | `true` | Kernel Cloud Fetch toggle; `false` forces inline results. On Thrift use `WithCloudFetch`. | +| `cloudfetch_enabled` | `WithCloudFetch` | ⚠️ | ✅ | `true` | Set `false` to fetch complete results without cloud-storage downloads. Use `WithCloudFetch` for the standard option on either backend. | | `cloudfetch_link_prefetch_window` | *(none; use `WithSessionParams`)* | ⚠️ | ✅ | `10` | Number of presigned Cloud Fetch links prefetched ahead of the consumer. | | `cloudfetch_max_chunks_in_memory` | `WithKernelMaxChunksInMemory` | ⚠️ | ✅ | `16` | Maximum decompressed Cloud Fetch chunks held in memory. Values above 256 are clamped with a warning, not rejected. | | `inline_max_chunks_in_memory` | *(none; use `WithSessionParams`)* | ⚠️ | ✅ | `4` | Inline-Arrow prefetch window; `1` disables prefetching. | @@ -174,7 +174,7 @@ an internal setting) and non-Arrow values also retain legacy session-location pa | DSN parameter | Connector option | Thrift | Kernel | Default | Notes | |---|---|:---:|:---:|---|---| -| `useCloudFetch` | `WithCloudFetch` | ✅ | ⚠️ | `true` | Enable Cloud Fetch on Thrift. This option is inert on the kernel path; use the `cloudfetch_enabled` client-result conf there. | +| `useCloudFetch` | `WithCloudFetch` | ✅ | ✅ | `true` | Set false to fetch complete results through the SQL connection without direct cloud-storage access. | | `maxDownloadThreads` | `WithMaxDownloadThreads` | ✅ | ⚠️ | `10` | Concurrent download goroutines (Thrift). Inert on the kernel path. | | | `WithKernelMaxChunksInMemory(n)` | ❌ | ✅ | kernel default (16) | Bounds decompressed Cloud Fetch chunks held in memory — trades large-result throughput for peak memory. | diff --git a/KERNEL_REV b/KERNEL_REV index d025be44..de1b52ca 100644 --- a/KERNEL_REV +++ b/KERNEL_REV @@ -1 +1 @@ -6f4b6d607a61bdde61dcda2cf82bc8e80fd32cb9 +0b5d0edfed32c0745d5abc2468fc3070e2eb2a17 diff --git a/README.md b/README.md index c4633c85..fad7bc25 100644 --- a/README.md +++ b/README.md @@ -327,7 +327,7 @@ parallel via cloud storage | DSN parameter | Connector option | Protocol | Default | Description | |---|---|---|---|---| -| `useCloudFetch` | `WithCloudFetch` | Thrift only (inert on kernel) | `true` | Enable Cloud Fetch. On the kernel path Cloud Fetch is always managed internally, so the flag is inert. | +| `useCloudFetch` | `WithCloudFetch` | Both | `true` | Enable Cloud Fetch. Set to false to fetch results through the SQL connection without direct cloud-storage access. | | `maxDownloadThreads` | `WithMaxDownloadThreads` | Thrift only (inert on kernel) | `10` | Concurrent download goroutines (Thrift). Inert on the kernel path. | | | `WithKernelMaxChunksInMemory(n)` | SEA only | kernel default (16) | Bounds decompressed Cloud Fetch chunks held in memory — trades large-result throughput for peak memory. | diff --git a/connector_reyden_test.go b/connector_reyden_test.go index 92cfe1af..858d8ca3 100644 --- a/connector_reyden_test.go +++ b/connector_reyden_test.go @@ -8,6 +8,7 @@ import ( dbsqlerr "github.com/databricks/databricks-sql-go/errors" "github.com/databricks/databricks-sql-go/internal/backend" + "github.com/databricks/databricks-sql-go/internal/backend/kernel" "github.com/databricks/databricks-sql-go/internal/backend/thrift" "github.com/databricks/databricks-sql-go/internal/cli_service" "github.com/databricks/databricks-sql-go/internal/client" @@ -193,10 +194,15 @@ func TestReydenReactiveRecovery(t *testing.T) { return fakeThrift, nil }, func(ctx context.Context, cfg *config.Config) (backend.Backend, error) { + require.False(t, cfg.UseCloudFetch) + kc := buildKernelConfig(cfg, kernel.Auth{Mode: kernel.AuthPAT, Token: "test-token"}) + require.NotNil(t, kc.CloudFetchEnabled) + require.False(t, *kc.CloudFetchEnabled) return kernelBackend, nil }, ) + conn.cfg.UseCloudFetch = false be, _, err := conn.openSessionWithReydenFallback(context.Background()) require.NoError(t, err) diff --git a/internal/backend/kernel/backend.go b/internal/backend/kernel/backend.go index f8e6ebb7..d8e20d08 100644 --- a/internal/backend/kernel/backend.go +++ b/internal/backend/kernel/backend.go @@ -67,6 +67,7 @@ import ( "context" "errors" "fmt" + "strconv" "strings" "sync/atomic" "time" @@ -297,12 +298,29 @@ func (k *KernelBackend) OpenSession(ctx context.Context) error { } } + if k.cfg.CloudFetchEnabled != nil { + key := newCStr("cloudfetch_enabled") + value := newCStr(strconv.FormatBool(*k.cfg.CloudFetchEnabled)) + errSet := call(func() C.KernelStatusCode { + return C.kernel_session_config_set_client_conf(cfg, key.c, value.c) + }) + key.free() + value.free() + if errSet != nil { + return fmt.Errorf("kernel: set_client_conf[cloudfetch_enabled]: %w", toConnError(errSet)) + } + } + // Log the resolved retry policy + CloudFetch chunk cap before connecting, so if a // customer reports a hung connect or a large-result OOM, on-call can see from the // debug log what was actually applied (these are otherwise silent — forwarded to // the kernel with no observable trace). Kept at Debug and cheap to format. - klogCtx(ctx, "OpenSession resolved: retry=%s cloudfetchMaxChunksInMemory=%s", - describeRetry(k.cfg.Retry), k.cfg.SessionConf[kernelMaxChunksInMemoryConfKey]) + cloudFetchOption := "unset" + if k.cfg.CloudFetchEnabled != nil { + cloudFetchOption = strconv.FormatBool(*k.cfg.CloudFetchEnabled) + } + klogCtx(ctx, "OpenSession resolved: retry=%s cloudfetchMaxChunksInMemory=%s cloudFetchOption=%s", + describeRetry(k.cfg.Retry), k.cfg.SessionConf[kernelMaxChunksInMemoryConfKey], cloudFetchOption) // kernel_session_open takes ownership of cfg here. Its documented C-ABI // contract (databricks_kernel.h: "CONSUMES config on both success and failure diff --git a/internal/backend/kernel/config.go b/internal/backend/kernel/config.go index 5a68ce0d..c3f97ed8 100644 --- a/internal/backend/kernel/config.go +++ b/internal/backend/kernel/config.go @@ -44,6 +44,9 @@ type Config struct { // Thrift backend forwards (STATEMENT_TIMEOUT, QUERY_TAGS, TIMEZONE, …). SessionConf map[string]string + // Nil preserves the kernel default and any raw session configuration. + CloudFetchEnabled *bool + // TLSSkipVerify accepts any server cert (maps the driver's // WithSkipTLSHostVerify / TLSConfig.InsecureSkipVerify). crypto/tls's // InsecureSkipVerify disables both chain validation and the hostname check, diff --git a/kernel_cloudfetch_e2e_test.go b/kernel_cloudfetch_e2e_test.go new file mode 100644 index 00000000..09866707 --- /dev/null +++ b/kernel_cloudfetch_e2e_test.go @@ -0,0 +1,96 @@ +//go:build cgo && databricks_kernel + +package dbsql + +import ( + "context" + "crypto/sha256" + "crypto/sha512" + "database/sql" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestE2EKernelCloudFetchDisabledLargeResults(t *testing.T) { + if testing.Short() { + t.Skip("skipping large inline result in -short mode") + } + host, httpPath, token := pecoTestingCreds(t) + _, workspaceHost := parseHostName(host) + workspaceAuthority := net.JoinHostPort(workspaceHost, "443") + var workspaceConnections, blockedConnections atomic.Int64 + proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodConnect || !strings.EqualFold(r.Host, workspaceAuthority) { + blockedConnections.Add(1) + http.Error(w, "Only the SQL workspace is reachable", http.StatusForbidden) + return + } + upstream, err := net.DialTimeout("tcp", r.Host, 10*time.Second) + if err != nil { + http.Error(w, "Workspace connection failed", http.StatusBadGateway) + return + } + defer upstream.Close() //nolint:errcheck + hijacker, ok := w.(http.Hijacker) + if !ok { + http.Error(w, "Proxy tunneling is unavailable", http.StatusInternalServerError) + return + } + client, buffered, err := hijacker.Hijack() + if err != nil { + return + } + defer client.Close() //nolint:errcheck + workspaceConnections.Add(1) + _, _ = buffered.WriteString("HTTP/1.1 200 Connection Established\r\n\r\n") + if err := buffered.Flush(); err != nil { + return + } + go func() { _, _ = io.Copy(upstream, buffered) }() + _, _ = io.Copy(client, upstream) + })) + defer proxy.Close() + connector, err := NewConnector( + WithServerHostname(host), WithHTTPPath(httpPath), WithAccessToken(token), + WithUseKernel(true), WithCloudFetch(false), + WithKernelProxy(KernelProxy{URL: proxy.URL}), + WithRetries(-1, time.Millisecond, time.Millisecond), + ) + require.NoError(t, err) + db := sql.OpenDB(connector) + defer db.Close() //nolint:errcheck + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + defer cancel() + rows, err := db.QueryContext(ctx, "SELECT id, sha2(CAST(id AS STRING), 512) AS payload FROM range(250000) ORDER BY id") + require.NoError(t, err) + defer rows.Close() //nolint:errcheck + var count int64 + var payloadBytes int + digest := sha256.New() + for rows.Next() { + var id int64 + var payload string + require.NoError(t, rows.Scan(&id, &payload)) + require.Equal(t, count, id) + require.Equal(t, fmt.Sprintf("%x", sha512.Sum512([]byte(strconv.FormatInt(id, 10)))), payload) + _, _ = fmt.Fprintf(digest, "%d\t%s\n", id, payload) + payloadBytes += len(payload) + count++ + } + require.NoError(t, rows.Err()) + require.Positive(t, workspaceConnections.Load(), "SQL traffic must use the restricted proxy") + require.Zero(t, blockedConnections.Load(), "no non-workspace connections are allowed") + require.Equal(t, int64(250000), count) + require.Equal(t, 32000000, payloadBytes) + require.Equal(t, "a25ada4c6c476b53e97eb6e8a945e9ce4c14cc432c7ad672dc6fb607d660c86a", fmt.Sprintf("%x", digest.Sum(nil))) +} diff --git a/kernel_cloudfetch_test.go b/kernel_cloudfetch_test.go new file mode 100644 index 00000000..c728b88d --- /dev/null +++ b/kernel_cloudfetch_test.go @@ -0,0 +1,118 @@ +//go:build cgo && databricks_kernel + +package dbsql + +import ( + "context" + "database/sql" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + dbsqlerr "github.com/databricks/databricks-sql-go/errors" + "github.com/databricks/databricks-sql-go/internal/backend" + "github.com/databricks/databricks-sql-go/internal/cli_service" + "github.com/databricks/databricks-sql-go/internal/client" + "github.com/databricks/databricks-sql-go/internal/config" + "github.com/databricks/databricks-sql-go/internal/warehouse_cache" + "github.com/stretchr/testify/require" +) + +func TestKernelCloudFetchDisabledPreservesUnsupportedServerError(t *testing.T) { + for _, automaticRecovery := range []bool{false, true} { + for _, rejectSession := range []bool{false, true} { + t.Run(fmt.Sprintf("recovery=%t/session_rejected=%t", automaticRecovery, rejectSession), func(t *testing.T) { + testKernelCloudFetchDisabledUnsupportedServer(t, automaticRecovery, rejectSession) + }) + } + } +} + +func testKernelCloudFetchDisabledUnsupportedServer(t *testing.T, automaticRecovery, rejectSession bool) { + t.Helper() + defer warehouse_cache.ClearCache() + var sessions atomic.Int64 + var executions atomic.Int64 + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/sessions"): + sessions.Add(1) + var body struct { + SessionConfs map[string]string `json:"session_confs"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body.SessionConfs["can_cloud_download"] != "false" { + http.Error(w, "missing disabled download capability", http.StatusBadRequest) + return + } + for key := range body.SessionConfs { + if strings.EqualFold(key, "cloudfetch_enabled") || (strings.EqualFold(key, "can_cloud_download") && key != "can_cloud_download") { + http.Error(w, "conflicting download parameter", http.StatusBadRequest) + return + } + } + if rejectSession { + w.WriteHeader(http.StatusBadRequest) + _, _ = io.WriteString(w, `{"error_code":"CONFIG_NOT_AVAILABLE","message":"Configuration can_cloud_download is not available. SQLSTATE: 42K0I"}`) + return + } + _, _ = io.WriteString(w, `{"session_id":"test-session"}`) + case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/statements"): + executions.Add(1) + _, _ = io.WriteString(w, `{"statement_id":"unsupported-inline","status":{"state":"FAILED","sql_state":"42K0I","error":{"error_code":"CONFIG_NOT_AVAILABLE","message":"Configuration can_cloud_download is not available"}}}`) + default: + _, _ = io.WriteString(w, `{}`) + } + })) + defer server.Close() + dbConnector, err := NewConnector( + WithServerHostname(server.URL), WithHTTPPath("/sql/1.0/warehouses/test"), + WithAccessToken("test-token"), WithUseKernel(true), WithCloudFetch(false), + WithSessionParams(map[string]string{"CAN_CLOUD_DOWNLOAD": "true"}), + WithSkipTLSHostVerify(), WithRetries(-1, time.Millisecond, time.Millisecond), + ) + require.NoError(t, err) + var thriftAttempts atomic.Int64 + if automaticRecovery { + c := dbConnector.(*connector) + c.cfg.UseKernel = false + c.thriftBackendFactory = func(context.Context, *config.Config, *http.Client) (backend.Backend, error) { + thriftAttempts.Add(1) + sqlState := "KP001" + return &fakeThriftBackend{openSessionErr: client.CheckOpenSessionStatus(&cli_service.TOpenSessionResp{ + Status: &cli_service.TStatus{StatusCode: cli_service.TStatusCode_ERROR_STATUS, SqlState: &sqlState}, + })}, nil + } + } + db := sql.OpenDB(dbConnector) + defer db.Close() //nolint:errcheck + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + connection, err := db.Conn(ctx) + if rejectSession { + require.Error(t, err) + require.Contains(t, err.Error(), "CONFIG_NOT_AVAILABLE") + require.Contains(t, err.Error(), "42K0I") + require.Equal(t, int64(0), executions.Load()) + } else { + require.NoError(t, err) + defer connection.Close() //nolint:errcheck + _, err = connection.ExecContext(ctx, "SELECT 1") + require.Error(t, err) + var executionError dbsqlerr.DBExecutionError + require.ErrorAs(t, err, &executionError) + require.Equal(t, "42K0I", executionError.SqlState()) + require.Contains(t, err.Error(), "CONFIG_NOT_AVAILABLE") + require.Equal(t, int64(1), executions.Load(), "unsupported delivery must not fall back") + } + require.Equal(t, int64(1), sessions.Load(), "unsupported delivery must not reopen the session") + if automaticRecovery { + require.Equal(t, int64(1), thriftAttempts.Load(), "backend recovery must not repeat") + } +} diff --git a/kernel_config.go b/kernel_config.go index 9db5d154..76f70a33 100644 --- a/kernel_config.go +++ b/kernel_config.go @@ -180,6 +180,10 @@ func buildKernelConfig(cfg *config.Config, kauth kernel.Auth) kernel.Config { // An explicit true below opts into native geospatial values. EnableGeoSpatialSupport: false, } + if !cfg.UseCloudFetch { + enabled := false + kc.CloudFetchEnabled = &enabled + } if cfg.ClientQueryTimeout != nil { timeout := *cfg.ClientQueryTimeout kc.ClientQueryTimeout = &timeout diff --git a/kernel_config_test.go b/kernel_config_test.go index d669a023..e7a44b9b 100644 --- a/kernel_config_test.go +++ b/kernel_config_test.go @@ -3,6 +3,7 @@ package dbsql import ( "crypto/tls" "errors" + "fmt" "net/http" "reflect" "testing" @@ -473,9 +474,9 @@ var kernelConfigFieldDisposition = map[string]string{ "EnableGeoSpatialSupportDSN": "inert", // DSN carrier; forwarded to KernelExperimental.EnableGeoSpatialSupport // Fields promoted from the embedded CloudFetchConfig. The kernel does - // CloudFetch internally (below the C ABI), so none is forwarded — but each is + // CloudFetch internally (below the C ABI); each option is // classified individually so a new CloudFetch option can't slip the guard. - "UseCloudFetch": "inert", + "UseCloudFetch": "forwarded", "MaxDownloadThreads": "inert", "MaxFilesInMemory": "inert", "MinTimeToExpiry": "inert", @@ -702,6 +703,26 @@ func TestBuildKernelConfig(t *testing.T) { } }) + for _, enabled := range []bool{false, true} { + t.Run(fmt.Sprintf("CloudFetch enabled=%v", enabled), func(t *testing.T) { + c := baseKernelConfig() + c.UseCloudFetch = enabled + c.SessionParams = map[string]string{"can_cloud_download": "true", "CLOUDFETCH_ENABLED": "true", "TIMEZONE": "UTC"} + original := map[string]string{"can_cloud_download": "true", "CLOUDFETCH_ENABLED": "true", "TIMEZONE": "UTC"} + kc := buildKernelConfig(c, kernel.Auth{Mode: kernel.AuthPAT, Token: "dapi-x"}) + if enabled { + if kc.CloudFetchEnabled != nil { + t.Fatal("enabled mode must keep the kernel default") + } + } else if kc.CloudFetchEnabled == nil || *kc.CloudFetchEnabled { + t.Fatal("disabled mode must forward the client option") + } + if !reflect.DeepEqual(kc.SessionConf, original) || !reflect.DeepEqual(c.SessionParams, original) { + t.Fatal("session parameters must be preserved for the kernel to interpret") + } + }) + } + t.Run("MaxChunksInMemory injected into kernel SessionConf", func(t *testing.T) { c := baseKernelConfig() c.KernelExperimental = &config.KernelExperimentalConfig{MaxChunksInMemory: 4}