diff --git a/CHANGELOG.md b/CHANGELOG.md index 94d6136ac..c9e8608fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ - **Behavior change:** Closed Thrift Arrow row scanners return an explicit error without logging an ERROR instead of stale values; a destination whose column count differs from the Arrow holders now errors instead of filling leading columns or NULL-padding missing columns. Column-value setup failures now stop scanning and are retained for subsequent scans instead of only being logged and ignored (databricks/databricks-sql-go#602). - Support SOCKS proxies on the kernel backend; see [Proxy](CONNECTION_PARAMETERS.md#proxy). - **Behavior change:** On the kernel backend, `NO_PROXY` now also applies to CloudFetch storage and OAuth hosts, with the differences from the Thrift path listed in [Proxy](CONNECTION_PARAMETERS.md#proxy). +- Support Volume PUT, GET and REMOVE on the kernel backend: with the staging context, the kernel transfers the file during execution. Local paths, with symlinks resolved, must be within the staging roots (databricks/databricks-sql-go#560). ## v2.0.0 (2026-11-23) diff --git a/KERNEL_REV b/KERNEL_REV index 418c81d3b..c3e3ca999 100644 --- a/KERNEL_REV +++ b/KERNEL_REV @@ -1 +1 @@ -a29235cbea9532efa5572ebff010045583a19cbe +d18b044bdd8d6a3ef7c7dd763a5f38c1532a213f diff --git a/doc.go b/doc.go index aaf8cb746..2365d8607 100644 --- a/doc.go +++ b/doc.go @@ -229,13 +229,13 @@ RetryWaitMin / RetryWaitMax / RetryMax, including the disable form, forwarded to kernel's HTTP retry config); and the TLS, proxy, and session-conf (query tags, statement timeout, time zone) options. Federated token providers use one token snapshot during setup. Nothing is silently ignored: WithTimeout and token-provider / external / -static authenticators are rejected at connect; staging (PUT/GET/REMOVE on a -Unity Catalog volume) is rejected at execute. WithMaxRows is accepted but inert (the +static authenticators are rejected at connect. WithMaxRows is accepted but inert (the kernel manages fetching below the C ABI). Kernel HTTP requests inherit the driver's ClientTimeout (900s by default). If that value is zero, the kernel uses its own 120s default; zero is neither -unlimited nor an immediate timeout. +unlimited nor an immediate timeout. For a Volume file transfer it is an idle limit +rather than a total deadline; use a context deadline to bound the whole transfer. OAuth U2M is interactive: on a cache miss, connecting launches the system browser and blocks until login completes or the kernel's ~120s callback timeout expires. Because @@ -381,6 +381,13 @@ After doing so, you can execute staging operations using this context using the _, err1 := db.ExecContext(ctx, `PUT 'staging/file.csv' INTO '/Volumes/main/staging_test/e2etests/file.csv' OVERWRITE`) +With the kernel backend, a statement run with the staging context transfers its +file during ExecContext or QueryContext, and ExecContext reports zero rows +affected. Local paths, with symlinks resolved, must be within the staging roots. +Without the staging context, ExecContext fails a PUT, GET or REMOVE and +QueryContext returns its instruction row, as on Thrift. New GET files are created +with mode 0666 before the umask; the Thrift backend uses 0644. + # Errors There are three error types exposed via dbsql/errors diff --git a/examples/kernel/main.go b/examples/kernel/main.go index 2ed079282..5caac5d2e 100644 --- a/examples/kernel/main.go +++ b/examples/kernel/main.go @@ -87,14 +87,4 @@ func main() { log.Fatalf("query: %v", err) } fmt.Printf("server version: %s\n", version) - - // Options the kernel can't honor are rejected with an error wrapping - // ErrNotSupportedByKernel, never silently ignored. Staging (PUT/GET/REMOVE on a - // Unity Catalog volume) is one such feature, rejected at execute. - _, err = db.ExecContext(ctx, "PUT '/tmp/local.csv' INTO '/Volumes/main/default/vol/f.csv' OVERWRITE") - if errors.Is(err, dbsqlerr.ErrNotSupportedByKernel) { - fmt.Println("staging is not supported on the kernel backend (use Thrift for staging)") - } else if err != nil { - fmt.Printf("staging: %v\n", err) - } } diff --git a/internal/backend/kernel/backend.go b/internal/backend/kernel/backend.go index 13b6c4f1e..61c166304 100644 --- a/internal/backend/kernel/backend.go +++ b/internal/backend/kernel/backend.go @@ -72,7 +72,6 @@ import ( "sync/atomic" "time" - dbsqlerr "github.com/databricks/databricks-sql-go/v2/errors" "github.com/databricks/databricks-sql-go/v2/internal/backend" dbsqlerrint "github.com/databricks/databricks-sql-go/v2/internal/errors" ) @@ -925,15 +924,5 @@ func (k *KernelBackend) Execute(ctx context.Context, req backend.ExecRequest) (b // so ErrBadConn can safely retire the connection before this request. return &kernelOp{}, dbsqlerrint.NewBadConnectionError(errors.New("kernel: session is no longer valid")) } - // Staging (Unity Catalog volume PUT/GET/REMOVE) needs a local file transfer the - // kernel path can't perform, and the kernel C ABI surfaces no IsStagingOperation - // signal to drive conn.execStagingOperation. Reject it here rather than let - // IsStaging return false and report success with no file moved (silent data loss). - // (Bound parameters, by contrast, ARE now supported — bound in execute via the - // kernel's raw-param C ABI.) - if isStagingStatement(req.Query) { - return &kernelOp{}, fmt.Errorf("databricks: staging operations (PUT/GET/REMOVE on a volume) are %w; "+ - "use the default (Thrift) backend", dbsqlerr.ErrNotSupportedByKernel) - } return k.execute(ctx, req) } diff --git a/internal/backend/kernel/cgo.go b/internal/backend/kernel/cgo.go index 2ae5943c4..eeded2593 100644 --- a/internal/backend/kernel/cgo.go +++ b/internal/backend/kernel/cgo.go @@ -38,7 +38,9 @@ import "C" import ( "context" "fmt" + "os" "runtime" + "syscall" "unsafe" "github.com/databricks/databricks-sql-go/v2/driverctx" @@ -178,6 +180,11 @@ func lastError(code C.KernelStatusCode) *KernelError { if e.query_id != nil { ke.QueryID = C.GoString(e.query_id) } + ke.ErrorCode = C.GoString(C.kernel_get_last_error_code()) + if code := C.kernel_get_last_error_local_os_error(); code != 0 { + // The C ABI reports a path and errno without a syscall name. + ke.cause = &os.PathError{Op: "file", Path: C.GoString(C.kernel_get_last_error_local_path()), Err: syscall.Errno(code)} + } klog("kernel error: code=%d sqlstate=%q vendor=%d http=%d retryable=%v msg=%q", ke.Code, ke.SQLState, ke.VendorCode, ke.HTTPStatus, ke.Retryable, ke.Message) // Also emit through the driver's logger — no SQL text or PII, just the @@ -188,7 +195,7 @@ func lastError(code C.KernelStatusCode) *KernelError { // User/query faults (bad SQL, bad argument) are routine and log at Debug so they // don't inflate the WARN rate on-call alerts key on; infra codes stay at Warn. msg := "databricks: kernel call failed: code=%d sqlstate=%q vendor=%d http=%d retryable=%v queryId=%q" - if isUserFault(ke.Code) { + if isUserFault(ke.Code, ke.ErrorCode) { logger.Logger.Debug().Msgf(msg, ke.Code, ke.SQLState, ke.VendorCode, ke.HTTPStatus, ke.Retryable, ke.QueryID) } else { logger.Logger.Warn().Msgf(msg, ke.Code, ke.SQLState, ke.VendorCode, ke.HTTPStatus, ke.Retryable, ke.QueryID) diff --git a/internal/backend/kernel/errors_classify.go b/internal/backend/kernel/errors_classify.go index 8eb605bab..2a3d43b6d 100644 --- a/internal/backend/kernel/errors_classify.go +++ b/internal/backend/kernel/errors_classify.go @@ -51,8 +51,12 @@ type KernelError struct { HTTPStatus uint16 Retryable bool QueryID string + ErrorCode string + cause error } +func (e *KernelError) Unwrap() error { return e.cause } + func (e *KernelError) Error() string { // Append the server query id when present — it is the one correlation handle // to server-side query history, and on the execute-error path (no exec handle) @@ -135,6 +139,9 @@ func isBadConnection(code int) bool { // invalid session handles are fatal; other missing resources or invalid // arguments leave the session usable. func isSessionFatal(ke *KernelError) bool { + if ke.ErrorCode == "VOLUME_STORAGE_HTTP_ERROR" || ke.ErrorCode == "VOLUME_STORAGE_NETWORK_ERROR" { + return false + } switch ke.Code { case statusUnauthenticated, statusUnavailable, statusNetworkError: return true @@ -147,20 +154,19 @@ func isSessionFatal(ke *KernelError) bool { } } -// isUserFault reports whether a status code is a user/query fault (a bad SQL -// statement or a bad argument) rather than an infrastructure problem. Used to +// isUserFault reports whether a kernel error is a user fault (bad SQL, a bad +// argument or a local file error) rather than an infrastructure problem. Used to // pick the log level for a kernel-call failure: user faults are routine — a // fat-fingered query should not raise the driver's WARN rate and page on-call — // so they log at Debug, while infra codes (Unavailable / NetworkError / Timeout / // Unauthenticated) stay at Warn. Mirrors the Thrift path, which keeps user SQL // errors out of operational-noise logging. -func isUserFault(code int) bool { +func isUserFault(code int, errorCode string) bool { switch code { case statusSqlError, statusInvalidArgument: return true - default: - return false } + return errorCode == "VOLUME_LOCAL_FILE_ERROR" } // toConnError classifies a kernel error on a SESSION-lifecycle path (open/close/ diff --git a/internal/backend/kernel/errors_classify_test.go b/internal/backend/kernel/errors_classify_test.go index 3c132dff1..8e9e143d3 100644 --- a/internal/backend/kernel/errors_classify_test.go +++ b/internal/backend/kernel/errors_classify_test.go @@ -50,6 +50,14 @@ func TestIsSessionFatal(t *testing.T) { t.Errorf("code %d should not be session-fatal", code) } } + for _, err := range []*KernelError{ + {Code: statusUnauthenticated, ErrorCode: "VOLUME_STORAGE_HTTP_ERROR"}, + {Code: statusNetworkError, ErrorCode: "VOLUME_STORAGE_NETWORK_ERROR"}, + } { + if isSessionFatal(err) { + t.Errorf("storage error %s should not be session-fatal", err.ErrorCode) + } + } } func expiredSessionError() *KernelError { @@ -138,16 +146,22 @@ func TestExpiredSessionDoesNotTriggerReplay(t *testing.T) { func TestIsUserFault(t *testing.T) { faults := []int{statusSqlError, statusInvalidArgument} for _, code := range faults { - if !isUserFault(code) { + if !isUserFault(code, "") { t.Errorf("code %d should be a user fault (log at Debug)", code) } } infra := []int{statusUnavailable, statusNetworkError, statusTimeout, statusUnauthenticated} for _, code := range infra { - if isUserFault(code) { + if isUserFault(code, "") { t.Errorf("code %d is infra-side and should NOT be a user fault (stays Warn)", code) } } + if !isUserFault(statusNotFound, "VOLUME_LOCAL_FILE_ERROR") { + t.Error("a local file error should be a user fault (log at Debug)") + } + if isUserFault(statusNotFound, "VOLUME_STORAGE_HTTP_ERROR") { + t.Error("a storage HTTP error should not be a user fault (stays Warn)") + } } // toConnError (session-lifecycle path) wraps a session-unusable KernelError as diff --git a/internal/backend/kernel/include/databricks_kernel.h b/internal/backend/kernel/include/databricks_kernel.h index effd60572..35fc9c4e2 100644 --- a/internal/backend/kernel/include/databricks_kernel.h +++ b/internal/backend/kernel/include/databricks_kernel.h @@ -191,6 +191,18 @@ typedef struct KernelError { */ bool kernel_get_last_error(KernelError* out); +/* + * Details of the last error recorded on the calling thread. Strings are NULL + * when absent and valid until the next kernel call on that thread. + * - `_code`: string code such as `VOLUME_PATH_NOT_ALLOWED`. + * - `_local_os_error`: OS error number behind a local file error (errno, or + * a Windows error code on Windows), or 0. + * - `_local_path`: local path of a local file error. + */ +const char* kernel_get_last_error_code(void); +int32_t kernel_get_last_error_local_os_error(void); +const char* kernel_get_last_error_local_path(void); + /* ─── Opaque handles ────────────────────────────────────────────────── * * All handles are owned heap allocations on the Rust side; the C side @@ -387,7 +399,9 @@ KernelStatusCode kernel_session_config_set_sea_response_compression_enabled( /* Configure the total timeout for one HTTP request, from connection start * through response-body completion. A separate 30s connection timeout also * applies, so connection establishment is bounded by the shorter limit. - * `request_timeout_ms == 0` keeps the kernel default (120s). */ + * `request_timeout_ms == 0` keeps the kernel default (120s). For Volume file + * transfers it is an idle limit: a transfer fails after this long without + * progress. */ KernelStatusCode kernel_session_config_set_request_timeout(KernelSessionConfig* config, uint64_t request_timeout_ms); @@ -628,10 +642,8 @@ KernelStatusCode kernel_session_config_set_u2m_token_cache_config(KernelSessionC * * Counterpart to kernel_session_config_set_session_conf: that one carries * SERVER session confs (ANSI_MODE, TIMEZONE, ...) to the SEA wire; this one - * sets CLIENT-SIDE knobs that tune how the kernel fetches, buffers, and - * post-processes results and are NEVER sent to the server. The two channels - * are deliberately separate (conflating them is what made a client flag - * masquerade as a rejected server conf). + * configures how the kernel requests, fetches, buffers, and post-processes + * results. These keys are kept out of the server session configuration. * * Key/value (rather than one typed setter per knob) so the signature never * changes as new result knobs are added, and so a host that already has DSN @@ -642,6 +654,9 @@ KernelStatusCode kernel_session_config_set_u2m_token_cache_config(KernelSessionC * Recognised keys (case-insensitive): * - "cloudfetch_enabled" = "true"|"false" — false serves every result * through paged inline delivery without cloud-storage downloads. + * - "lz4_compression_enabled" = "true"|"false", for LZ4 compression + * for Arrow results. Sets the session default; defaults to "true". + * The C ABI has no per-statement compression setter. * - "cloudfetch_link_prefetch_window" = positive integer. * - "cloudfetch_max_chunks_in_memory" = positive integer (bounds peak RSS; * values above the kernel ceiling of 256 are clamped with a warning). @@ -802,6 +817,21 @@ KernelStatusCode kernel_statement_bind_parameter(kernel_statement_t* stmt, KernelStatusCode kernel_statement_set_query_tags(kernel_statement_t* stmt, const char* query_tags); +/* + * Set the Volume transfer options for later executions of `stmt`. With them, + * executing a Volume PUT, GET or REMOVE also runs its file transfer, and the + * execution fails if the transfer does. `allowed_paths_json`: JSON array of + * local directories a transfer may use; the local path, with symlinks + * resolved, must be inside one of them. NULL clears the options, so a Volume + * statement returns its instruction row without transferring. + * `remove_not_found_is_success`: report success when REMOVE targets a missing + * object. The options survive kernel_statement_set_sql. This API takes no upload + * bytes, so `PUT '__input_stream__'` fails. + */ +KernelStatusCode kernel_statement_set_volume_options(kernel_statement_t* stmt, + const char* allowed_paths_json, + bool remove_not_found_is_success); + /* * Wait-for-result execution without an overall client polling deadline. * On success, release `*out` with @@ -959,6 +989,10 @@ KernelStatusCode kernel_executed_statement_get_result_stream(kernel_executed_sta */ int64_t kernel_executed_statement_num_modified_rows(const kernel_executed_statement_t* exec); +/* Whether the server marked the statement as a Volume PUT, GET or REMOVE. */ +KernelStatusCode kernel_executed_statement_is_volume_operation( + const kernel_executed_statement_t* exec, bool* out); + /* * Server statement (query) id of a successfully executed statement, as a * NUL-terminated C string — the success-path counterpart to the query id on @@ -988,10 +1022,18 @@ KernelStatusCode kernel_executed_async_statement_status( * state returns KernelStatusCode_InvalidArgument rather than blocking (v0 * collapses invalid-state into that code). This is single-consumption: * a second successful take is rejected. Close the stream with - * kernel_result_stream_close. */ + * kernel_result_stream_close. For a statement the server marks as a Volume + * PUT, GET or REMOVE, it runs the file transfer before returning. */ KernelStatusCode kernel_executed_async_statement_get_result_stream( kernel_executed_async_statement_t* exec, kernel_result_stream_t** out); +/* Whether the last status poll reported success for a statement the server + * marks as a Volume PUT, GET or REMOVE. False before that poll and once the + * result stream is taken. Returns KernelStatusCode_InvalidStatementHandle + * after the parent statement is re-executed or closed. */ +KernelStatusCode kernel_executed_async_statement_is_volume_operation( + const kernel_executed_async_statement_t* exec, bool* out); + /* Most recently observed DML count, or -1 when unavailable. */ int64_t kernel_executed_async_statement_num_modified_rows( const kernel_executed_async_statement_t* exec); @@ -1068,6 +1110,10 @@ KernelStatusCode kernel_result_stream_canceller_cancel( KernelStatusCode kernel_result_stream_canceller_free( kernel_result_stream_canceller_t* canceller); +/* Whether the server marked this result as a Volume PUT, GET or REMOVE. */ +KernelStatusCode kernel_result_stream_is_volume_operation(const kernel_result_stream_t* stream, + bool* out); + /* ─── Metadata ──────────────────────────────────────────────────────── * * Each returns a self-contained result stream (released via diff --git a/internal/backend/kernel/kernel_test.go b/internal/backend/kernel/kernel_test.go index 5eae14125..fabe32846 100644 --- a/internal/backend/kernel/kernel_test.go +++ b/internal/backend/kernel/kernel_test.go @@ -8,9 +8,11 @@ import ( "encoding/json" "errors" "fmt" + "io/fs" "os" "strings" "sync" + "syscall" "testing" "time" @@ -573,33 +575,6 @@ func TestExecuteHandleLessOpContract(t *testing.T) { } } -// TestExecuteRejectsStaging drives Execute with a staging statement (not just the -// isStagingStatement detector in isolation) to pin the detector→Execute wiring: a -// refactor that dropped or reordered the check would silently reopen the -// silent-no-op data-loss path. Mirrors TestExecuteRejectsParams. -func TestExecuteRejectsStaging(t *testing.T) { - k := &KernelBackend{valid: true} - op, err := k.Execute(context.Background(), backend.ExecRequest{ - Query: "PUT '/tmp/f' INTO '/Volumes/main/s/e/f.csv'", - }) - if err == nil { - t.Fatal("expected an error for a staging statement, got nil") - } - if !errors.Is(err, dbsqlerr.ErrNotSupportedByKernel) { - t.Errorf("staging rejection should wrap ErrNotSupportedByKernel, got %v", err) - } - if op == nil { - t.Fatal("Execute must return a non-nil Operation per the Backend contract") - } - closed, closeErr := op.Close(context.Background()) - if closeErr != nil { - t.Errorf("Close error = %v, want nil", closeErr) - } - if closed { - t.Error("Close on a handle-less op must report closed=false (no CLOSE_STATEMENT)") - } -} - // ExecutionError must satisfy the same public contract as the Thrift path so the // errors.Is → errors.As → SqlState()/QueryId() recipe documented in doc.go works // on the kernel backend too (it previously returned a bare *KernelError that @@ -611,7 +586,8 @@ func TestExecutionErrorContract(t *testing.T) { t.Errorf("ExecutionError(nil) = %v, want nil", got) } - cause := &KernelError{Code: statusSqlError, Message: "boom", SQLState: "42000", QueryID: "q-123"} + cause := &KernelError{Code: statusSqlError, Message: "boom", SQLState: "42000", QueryID: "q-123", + cause: &os.PathError{Op: "file", Path: "missing.bin", Err: syscall.ENOENT}} err := o.ExecutionError(context.Background(), cause) if err == nil { t.Fatal("ExecutionError(cause) should not be nil") @@ -637,6 +613,9 @@ func TestExecutionErrorContract(t *testing.T) { if !errors.As(err, &ke) { t.Error("the *KernelError cause should remain reachable via errors.As") } + if !errors.Is(err, fs.ErrNotExist) { + t.Errorf("local file error should match fs.ErrNotExist; got %v", err) + } } // The execute error path must NEVER report retryable, even when the kernel marks diff --git a/internal/backend/kernel/operation.go b/internal/backend/kernel/operation.go index 7b3ccd225..538e3b9bd 100644 --- a/internal/backend/kernel/operation.go +++ b/internal/backend/kernel/operation.go @@ -11,6 +11,7 @@ import "C" import ( "context" "database/sql/driver" + "encoding/json" "errors" "fmt" "sync" @@ -35,8 +36,9 @@ import ( // client-timeout path, let an in-flight cancel finish in the background so // it cannot extend the client deadline // -// Binds any query parameters (bindParams) before executing; staging statements -// are rejected up front by Execute, so none reach here. +// Binds any query parameters (bindParams) before executing. With staging paths on +// ctx it also sets the Volume options, so the kernel runs the file transfer of a +// Volume PUT, GET or REMOVE inside execute. func (k *KernelBackend) execute(ctx context.Context, req backend.ExecRequest) (backend.Operation, error) { // Log the SQL length, not the text: query bodies can carry PII/secrets in // WHERE/INSERT/SET, and this goes to stderr. Matches the driver's own @@ -113,6 +115,22 @@ func (k *KernelBackend) execute(ctx context.Context, req backend.ExecRequest) (b } } + roots := driverctx.StagingPathsFromContext(ctx) + if len(roots) != 0 { + encoded, _ := json.Marshal(roots) + paths := newCStr(string(encoded)) + err := call(func() C.KernelStatusCode { + // Go Thrift REMOVE treats a missing object as success. + return C.kernel_statement_set_volume_options(stmt, paths.c, true) + }) + paths.free() + if err != nil { + C.kernel_statement_close(stmt) + k.evictIfSessionFatal(err) + return &kernelOp{}, fmt.Errorf("kernel: set_volume_options: %w", toStatementError(err)) + } + } + // Detached canceller, obtained before execute so it observes the server // statement id the moment execute publishes it. Non-fatal on failure: proceed // without cancellation rather than failing the query. @@ -197,7 +215,7 @@ func (k *KernelBackend) execute(ctx context.Context, req backend.ExecRequest) (b } }) - op := &kernelOp{backend: k, stmt: stmt, location: k.cfg.Location, decimalAsFloat: k.cfg.DecimalAsFloat} + op := &kernelOp{backend: k, stmt: stmt, location: k.cfg.Location, decimalAsFloat: k.cfg.DecimalAsFloat, transferred: len(roots) != 0} if execErr != nil { // A session-fatal status (expired token, dropped/unavailable session) means // this conn is unusable: evict it so the pool doesn't hand it out again. This @@ -344,6 +362,9 @@ type kernelOp struct { // decimalAsFloat scans top-level DECIMAL to lossy float64 instead of exact // string (from Config.DecimalAsFloat). Carried onto the rows. decimalAsFloat bool + // transferred is set when the statement ran with Volume options, so the kernel + // already ran any Volume transfer. + transferred bool } var _ backend.Operation = (*kernelOp)(nil) @@ -386,11 +407,19 @@ func (o *kernelOp) Results(ctx context.Context, callbacks *dbsqlrows.TelemetryCa return newKernelRows(ctx, o, stream, callbacks) } -// IsStaging reports whether this is a staging (PUT/GET/REMOVE) operation. Always -// false on the kernel path: staging statements are rejected up front in -// Execute (isStagingStatement), so no kernelOp is ever produced for one — there -// is nothing for conn.execStagingOperation to act on here. -func (o *kernelOp) IsStaging(ctx context.Context) (bool, error) { return false, nil } +// IsStaging reports a Volume PUT, GET or REMOVE that ran without staging paths on +// ctx, so no file moved; conn.execStagingOperation then reports the missing +// staging context, as on Thrift. +func (o *kernelOp) IsStaging(ctx context.Context) (bool, error) { + if o.exec == nil || o.transferred { + return false, nil + } + var marked C.bool + err := call(func() C.KernelStatusCode { + return C.kernel_executed_statement_is_volume_operation(o.exec, &marked) + }) + return bool(marked), err +} // Close best-effort closes the executed statement and its statement handle. It is // idempotent (a second call, or a call after Rows.Close already tore the diff --git a/internal/backend/kernel/staging.go b/internal/backend/kernel/staging.go deleted file mode 100644 index c614169c2..000000000 --- a/internal/backend/kernel/staging.go +++ /dev/null @@ -1,67 +0,0 @@ -package kernel - -import "strings" - -// This file is intentionally NOT behind the `cgo && databricks_kernel` build tag. -// Staging detection is pure Go (string inspection of the SQL), so keeping it -// untagged lets its test run under CGO_ENABLED=0. - -// isStagingStatement reports whether sql is a Unity Catalog volume staging -// command (PUT / GET / REMOVE). The Thrift backend learns a statement is staging -// from server result metadata (IsStagingOperation); the kernel C ABI exposes no -// such signal, and the kernel path cannot perform the local file transfer these -// commands require. We therefore detect them from the SQL and reject at execute -// time (see Execute) rather than silently returning success with no file moved — -// which is what returning false from IsStaging would do. Case-insensitive; skips -// leading whitespace AND leading SQL comments (`-- ...` and `/* ... */`), so a -// comment-prefixed staging command is still caught rather than slipping through -// as a silent no-op. Errs toward matching only a clear leading keyword — a false -// negative just yields the kernel's normal "unsupported syntax" server error, -// whereas a false positive would reject a legitimate query. -func isStagingStatement(sql string) bool { - s := stripLeadingSQLComments(sql) - for _, kw := range []string{"PUT", "GET", "REMOVE"} { - if len(s) > len(kw) && - strings.EqualFold(s[:len(kw)], kw) && - isSQLTokenBreak(s[len(kw)]) { - return true - } - } - return false -} - -// stripLeadingSQLComments removes leading whitespace and leading SQL comments -// (both `-- ...` line comments and `/* ... */` block comments), repeatedly, so -// the first real token is exposed. An unterminated block comment consumes the -// rest of the string (yielding ""). Comment bodies are not scanned for nested -// markers — SQL block comments do not nest — and this only touches the LEADING -// run, so a comment later in the statement is untouched. -func stripLeadingSQLComments(sql string) string { - s := strings.TrimSpace(sql) - for { - switch { - case strings.HasPrefix(s, "--"): - if i := strings.IndexByte(s, '\n'); i >= 0 { - s = s[i+1:] - } else { - return "" // line comment to end of input - } - case strings.HasPrefix(s, "/*"): - if i := strings.Index(s[2:], "*/"); i >= 0 { - s = s[2+i+2:] - } else { - return "" // unterminated block comment - } - default: - return s - } - s = strings.TrimSpace(s) - } -} - -// isSQLTokenBreak reports whether b ends a leading keyword — a space or a quote -// (staging commands take a quoted path, e.g. PUT '' INTO ''), so -// "PUT '..." matches but an identifier like "PUTS" or "GETTER" does not. -func isSQLTokenBreak(b byte) bool { - return b == ' ' || b == '\t' || b == '\n' || b == '\r' || b == '\'' || b == '"' -} diff --git a/internal/backend/kernel/staging_test.go b/internal/backend/kernel/staging_test.go deleted file mode 100644 index 91d69794d..000000000 --- a/internal/backend/kernel/staging_test.go +++ /dev/null @@ -1,41 +0,0 @@ -package kernel - -import "testing" - -func TestIsStagingStatement(t *testing.T) { - staging := []string{ - "PUT '/tmp/f.csv' INTO '/Volumes/main/s/e/f.csv' OVERWRITE", - "GET '/Volumes/main/s/e/f.csv' TO 'local.csv'", - "REMOVE '/Volumes/main/s/e/f.csv'", - " put '/tmp/f' into '/Volumes/x'", // leading space + lowercase - "Get\t'/Volumes/x' to 'y'", // tab after keyword, mixed case - "/* audit */ PUT '/local' INTO '/Volumes/main/s/v'", // leading block comment - "/* a */ /* b */ PUT '/l' INTO '/Volumes/x'", // multiple block comments - "-- upload the file\nPUT '/l' INTO '/Volumes/x'", // leading line comment, then staging - " /* c */\n -- d\n REMOVE '/Volumes/x'", // mixed comments + whitespace - } - for _, sql := range staging { - if !isStagingStatement(sql) { - t.Errorf("expected staging: %q", sql) - } - } - - notStaging := []string{ - "SELECT 1", - "PUTS ON A SHOW", // PUT is a prefix of an identifier, not a token - "GETTER()", // likewise for GET - "REMOVED_AT FROM t", // likewise for REMOVE - "INSERT INTO t VALUES (1)", // contains INTO but is not staging - "", // empty - "-- PUT '/x' INTO '/y'", // whole line commented out; nothing after - "/* PUT '/x' INTO '/y' */", // whole statement inside a block comment - "SELECT 'PUT ' AS col", // keyword only inside a literal - "/* unterminated PUT '/x'", // unterminated block comment consumes the rest - "/* c */ SELECT 1", // real leading comment, but not a staging command - } - for _, sql := range notStaging { - if isStagingStatement(sql) { - t.Errorf("did not expect staging: %q", sql) - } - } -} diff --git a/staging_kernel_test.go b/staging_kernel_test.go new file mode 100644 index 000000000..7f9427488 --- /dev/null +++ b/staging_kernel_test.go @@ -0,0 +1,266 @@ +//go:build cgo && databricks_kernel + +package dbsql + +import ( + "bytes" + "context" + "database/sql" + "database/sql/driver" + "encoding/base64" + "encoding/json" + "io" + "io/fs" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/apache/arrow-go/v18/arrow" + "github.com/apache/arrow-go/v18/arrow/array" + "github.com/apache/arrow-go/v18/arrow/ipc" + "github.com/apache/arrow-go/v18/arrow/memory" + "github.com/databricks/databricks-sql-go/v2/driverctx" + dbsqlerr "github.com/databricks/databricks-sql-go/v2/errors" + "github.com/databricks/databricks-sql-go/v2/internal/backend/kernel" + "github.com/stretchr/testify/require" +) + +func TestKernelVolumeTransfer(t *testing.T) { + for _, tc := range []struct { + name, operation, local, errorCode, message string + status int + inFlight, success, noStagingContext, missingLocal, outsideRoot, query bool + }{ + {name: "storage401", status: 401, errorCode: "VOLUME_STORAGE_HTTP_ERROR"}, + {name: "storageBody", errorCode: "VOLUME_STORAGE_NETWORK_ERROR"}, + {name: "getSuccess", success: true}, + {name: "getQuery", success: true, query: true}, + {name: "putSuccess", operation: "PUT", success: true}, + {name: "queryNoStagingContext", noStagingContext: true, query: true}, + {name: "removeNotFound", operation: "REMOVE", status: 404, success: true}, + {name: "inFlightCancel", inFlight: true}, + {name: "streamPut", operation: "PUT", local: "__input_stream__", message: "needs input bytes"}, + {name: "noStagingContext", noStagingContext: true, message: "staging ctx must be provided"}, + {name: "putMissingFile", operation: "PUT", missingLocal: true, errorCode: "VOLUME_LOCAL_FILE_ERROR"}, + {name: "putOutsideRoot", operation: "PUT", outsideRoot: true, errorCode: "VOLUME_PATH_NOT_ALLOWED"}, + } { + t.Run(tc.name, func(t *testing.T) { + directory := t.TempDir() + destination := filepath.Join(directory, "download.bin") + var result map[string]any + var storageRequests atomic.Int64 + storageStarted := make(chan struct{}) + type storageRequest struct { + method string + body []byte + } + stored := make(chan storageRequest, 1) + server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + w.Header().Set("Content-Type", "application/json") + switch { + case r.Method == "POST" && strings.HasSuffix(r.URL.Path, "/sessions"): + _, _ = io.WriteString(w, `{"session_id":"volume-session"}`) + case r.Method == "POST" && r.URL.Path == "/api/2.0/sql/statements": + _ = json.NewEncoder(w).Encode(result) + case r.URL.Path == "/object": + storageRequests.Add(1) + select { + case stored <- storageRequest{r.Method, body}: + default: + } + if tc.inFlight { + close(storageStarted) + <-r.Context().Done() + } else if tc.status != 0 { + w.WriteHeader(tc.status) + } else if tc.success { + _, _ = io.WriteString(w, "downloaded") + } else { + w.Header().Set("Content-Length", "20") + _, _ = io.WriteString(w, "short") + } + default: + _, _ = io.WriteString(w, `{}`) + } + })) + defer server.Close() + names := []string{"operation", "presignedUrl", "headers", "localFile"} + operation, local := tc.operation, destination + if operation == "" { + operation = "GET" + } + if tc.local != "" { + local = tc.local + } + if tc.missingLocal { + local = filepath.Join(directory, "missing.bin") + } + if tc.outsideRoot || (operation == "PUT" && tc.success) { + root := directory + if tc.outsideRoot { + root = t.TempDir() + } + local = filepath.Join(root, "source.bin") + require.NoError(t, os.WriteFile(local, []byte("payload"), 0600)) + } + values := []string{operation, server.URL + "/object", "{}", local} + fields, columns := make([]arrow.Field, 4), make([]arrow.Array, 4) + manifestColumns := make([]map[string]any, 4) + for i, name := range names { + fields[i] = arrow.Field{Name: name, Type: arrow.BinaryTypes.String, Nullable: true} + builder := array.NewStringBuilder(memory.DefaultAllocator) + builder.Append(values[i]) + columns[i] = builder.NewStringArray() + builder.Release() + defer columns[i].Release() + manifestColumns[i] = map[string]any{"name": name, "type_name": "STRING", "type_text": "STRING", "position": i} + } + schema := arrow.NewSchema(fields, nil) + record := array.NewRecordBatch(schema, columns, 1) + defer record.Release() + var attachment bytes.Buffer + writer := ipc.NewWriter(&attachment, ipc.WithSchema(schema)) + require.NoError(t, writer.Write(record)) + require.NoError(t, writer.Close()) + chunk := map[string]any{"chunk_index": 0, "row_offset": 0, "row_count": 1, "attachment": base64.StdEncoding.EncodeToString(attachment.Bytes())} + result = map[string]any{ + "statement_id": "volume-stmt", "status": map[string]any{"state": "CLOSED"}, + "manifest": map[string]any{"format": "ARROW_STREAM", "is_volume_operation": true, "schema": map[string]any{"column_count": 4, "columns": manifestColumns}, "total_row_count": 1, "total_chunk_count": 1}, + "result": chunk, + } + connector, err := NewConnector(WithServerHostname(server.URL), WithHTTPPath("/sql/1.0/warehouses/test"), + WithAccessToken("test-token"), WithUseKernel(true), WithSkipTLSHostVerify(), WithRetries(-1, time.Millisecond, time.Millisecond)) + require.NoError(t, err) + db := sql.OpenDB(connector) + defer db.Close() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + connection, err := db.Conn(ctx) + require.NoError(t, err) + defer func() { + cancel() + closed := make(chan struct{}) + go func() { + defer close(closed) + _ = connection.Close() + _ = db.Close() + }() + select { + case <-closed: + case <-time.After(5 * time.Second): + t.Error("connection and database close did not return") + } + server.CloseClientConnections() + }() + var execResult sql.Result + execCtx := driverctx.NewContextWithStagingInfo(ctx, []string{directory}) + if tc.noStagingContext { + execCtx = ctx + } + if tc.inFlight { + go func() { + select { + case <-storageStarted: + cancel() + case <-ctx.Done(): + } + }() + } + type executionResult struct { + result sql.Result + operations []string + err error + } + done := make(chan executionResult, 1) + go func() { + if !tc.query { + result, err := connection.ExecContext(execCtx, "Volume instruction") + done <- executionResult{result: result, err: err} + return + } + rows, err := connection.QueryContext(execCtx, "Volume instruction") + if err != nil { + done <- executionResult{err: err} + return + } + defer rows.Close() + var operations []string + for rows.Next() { + var operation, url, headers, localFile string + if err := rows.Scan(&operation, &url, &headers, &localFile); err != nil { + done <- executionResult{err: err} + return + } + operations = append(operations, operation) + } + done <- executionResult{operations: operations, err: rows.Err()} + }() + var operations []string + select { + case completed := <-done: + execResult, operations, err = completed.result, completed.operations, completed.err + case <-time.After(10 * time.Second): + cancel() + t.Fatal("ExecContext did not return") + } + if tc.query { + // QueryContext returns the instruction row, with or without the transfer. + require.NoError(t, err) + require.Equal(t, []string{operation}, operations) + } + if tc.query && tc.noStagingContext { + require.Zero(t, storageRequests.Load()) + } else if tc.success { + require.NoError(t, err) + if !tc.query && operation != "REMOVE" { + n, _ := execResult.RowsAffected() + require.Zero(t, n) + } + switch operation { + case "GET": + content, readErr := fs.ReadFile(os.DirFS(directory), "download.bin") + require.NoError(t, readErr) + require.Equal(t, "downloaded", string(content)) + case "PUT": + upload := <-stored + require.Equal(t, http.MethodPut, upload.method) + require.Equal(t, "payload", string(upload.body)) + } + } else if tc.errorCode == "" { + if tc.noStagingContext { + require.ErrorIs(t, err, dbsqlerr.DriverError) + } else { + require.ErrorIs(t, err, dbsqlerr.ExecutionError) + } + if tc.message != "" { + require.ErrorContains(t, err, tc.message) + } + if tc.inFlight { + require.ErrorIs(t, err, context.Canceled) + } + } else { + require.Error(t, err) + require.NotErrorIs(t, err, driver.ErrBadConn) + var detail *kernel.KernelError + require.ErrorAs(t, err, &detail) + require.Equal(t, tc.errorCode, detail.ErrorCode) + if tc.missingLocal { + require.ErrorIs(t, err, fs.ErrNotExist) + } + } + if tc.outsideRoot { + require.Zero(t, storageRequests.Load()) + } + require.NoError(t, connection.Raw(func(raw any) error { + require.True(t, raw.(driver.Validator).IsValid()) + return nil + })) + }) + } +}