Skip to content

Commit 188aec4

Browse files
aakash-saravanan-dbIsaac
andcommitted
feat(kernel): run Volume PUT, GET and REMOVE on the kernel backend
The kernel backend sets the Volume options on every statement before it runs, so the kernel transfers the file of a PUT, GET or REMOVE inside execute. staging_allowed_local_path becomes the allowed directories (an empty list when unset, which still allows a REMOVE, as on Thrift), and execute(input_stream=...) supplies the bytes for PUT '__input_stream__'. A Volume result returns no rows, and local path and storage errors raise the exceptions the Thrift backend raises. Removes the guard that refused staging statements on the kernel backend. Pins KERNEL_REV to databricks-sql-kernel#521. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Aakash Saravanan <aakash.saravanan@databricks.com>
1 parent 72ac235 commit 188aec4

14 files changed

Lines changed: 188 additions & 147 deletions

‎.github/workflows/kernel-e2e.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,7 @@ jobs:
241241
DATABRICKS_SERVER_HOSTNAME: ${{ secrets.DATABRICKS_HOST }}
242242
DATABRICKS_HTTP_PATH: ${{ secrets.TEST_PECO_WAREHOUSE_HTTP_PATH }}
243243
DATABRICKS_TOKEN: ${{ secrets.DATABRICKS_TOKEN }}
244+
DATABRICKS_CATALOG: peco
244245
steps:
245246
- name: Check out connector
246247
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
# Unreleased
44
- Honor `_port` and `_connection_uri` on kernel connections (`use_kernel=True`), as Thrift does. Requires a databricks-sql-kernel release that includes databricks/databricks-sql-kernel#505.
55
- Speed up `fetchone()`, `fetchmany()` and `fetchall()` by building each result `Row` with fewer Python calls. The rows are unchanged. Large results and many concurrent cursors in one process benefit most.
6+
- Support Volume `PUT`, `GET` and `REMOVE` on the kernel backend (`use_kernel=True`), including `input_stream` uploads. Local paths, with symlinks resolved, must be within `staging_allowed_local_path`.
67

78
# 4.10.0 (2026-11-24)
89
- Upgrade Databricks SQL Kernel to 1.5.0, with lower overhead for buffered fetches and closing drained cursors, and Arrow and Quinn security updates.

‎CONNECTION_PARAMETERS.md‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ to change without notice.
114114
115115
| Option | Type | Thrift | Kernel | Default Value | Note |
116116
| ------------------------------------ | ----------- | :----: | :----: | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
117-
| `_socket_timeout` | `float` (s) | ✅ | ✅ | `900` (Thrift); `120` (kernel) | Thrift: socket send/recv/connect timeout. Kernel: total HTTP request deadline from connect through response-body completion. A positive value is forwarded; unset or `0` selects the kernel's 120s default. On the kernel path, `0` is neither unlimited nor an immediate timeout. |
117+
| `_socket_timeout` | `float` (s) | ✅ | ✅ | `900` (Thrift); `120` (kernel) | Thrift: socket send/recv/connect timeout. Kernel: total HTTP request deadline from connect through response-body completion. A positive value is forwarded; unset or `0` selects the kernel's 120s default. On the kernel path, `0` is neither unlimited nor an immediate timeout. For a Volume file transfer, the kernel uses it as an idle limit instead. |
118118
| `_pool_connections` | `int` | ⚠️ | ❌ | `10` | Number of pools in the shared Python HTTP client. On Thrift this affects auxiliary auth/feature-flag/telemetry traffic, not the separate Thrift query transport. Kernel-owned network traffic does not use this client. |
119119
| `_pool_maxsize` | `int` | ⚠️ | ⚠️ | `20` (Python); `100` (kernel when unset) | Max idle connections retained per host. It configures the shared Python client but not the Thrift query transport. With kernel ≥ 1.1.0, a positive value also configures the kernel's Rust HTTP pool. Unset or `0` keeps each client's default. |
120120
| `_proxy_auth_method` | `str` | ✅ | ❌ | `None` | `basic` or `negotiate` (Kerberos). Applied to both Thrift query traffic and the shared Python client. It is not forwarded to the kernel's Rust transport. See [`docs/proxy.md`](docs/proxy.md). |
@@ -191,7 +191,7 @@ environment. The backends differ for SOCKS proxies:
191191
| `use_inline_params` | `bool` \| `"silent"` | ✅ | ✅ | `False` | Render parameters inline (legacy) vs. native bound params (DBR 14.1+). Shared cursor code performs the rendering before dispatch, so both backends honor it identically. |
192192
| `ignore_transactions` | `bool` | ✅ | ✅ | `True` | When `True`: `commit()` is a no-op, `rollback()` raises `NotSupportedError`, and setting `autocommit` is a no-op. |
193193
| `fetch_autocommit_from_server`| `bool` | ✅ | ✅ | `False` | Query the server (`SET AUTOCOMMIT`) for autocommit state instead of returning the cached value. |
194-
| `staging_allowed_local_path` | `str` \| `List[str]` | ✅ | ❌ | `None` | Local path(s) permitted for Unity Catalog Volume `PUT`/`GET`. **Thrift-only** — the kernel has no Volume API yet. |
194+
| `staging_allowed_local_path` | `str` \| `List[str]` | ✅ | ✅ | `None` | Local path(s) permitted for Unity Catalog Volume `PUT`/`GET`. The kernel also checks resolved symlink targets; see [Volume file paths](#volume-file-paths). |
195195

196196
## Telemetry
197197

@@ -228,12 +228,11 @@ are forwarded when supported by the installed kernel binding.
228228
`enable_query_result_lz4_compression`.
229229
5. Arrow-native rendering for `_use_arrow_native_decimals` /
230230
`_use_arrow_native_timestamps` (complex types **are** forwarded).
231-
6. `staging_allowed_local_path` (Volume `PUT`/`GET`).
232-
7. Retry fine-tuning beyond the four forwarded knobs: `_retry_delay_default`,
231+
6. Retry fine-tuning beyond the four forwarded knobs: `_retry_delay_default`,
233232
`_retry_dangerous_codes`, `_respect_server_retry_after_header`,
234233
`_retry_max_redirects`, `_enable_v3_retries`.
235-
8. `force_enable_telemetry`.
236-
9. `_pool_connections` and `_proxy_auth_method` do not configure the
234+
7. `force_enable_telemetry`.
235+
8. `_pool_connections` and `_proxy_auth_method` do not configure the
237236
kernel-owned network stack.
238237

239238
### Supported on Kernel, missing / ignored on Thrift
@@ -263,6 +262,15 @@ are forwarded when supported by the installed kernel binding.
263262
`force_enable_telemetry`, and an omitted `enable_telemetry` or circuit-breaker
264263
setting uses the kernel's default.
265264

265+
### Volume file paths
266+
267+
With `use_kernel=True`, SQL `PUT`, `GET` and `REMOVE` run their file transfer
268+
inside `execute()` or `get_async_execution_result()`. `PUT` and `GET` need local
269+
paths, with symlinks resolved, within `staging_allowed_local_path`; `REMOVE`
270+
needs none. `execute(input_stream=stream)` reads the stream before the statement
271+
runs. A `PUT` reads a regular file; pass other data, such as a pipe's content,
272+
as `input_stream`. Cancelling or closing the cursor stops a running transfer.
273+
266274
> All kernel-path behavior reflects the current **early-access** surface and is
267275
> subject to change. Generated against connector version `4.5.0`; the source of
268276
> truth is `Connection.__init__` (`src/databricks/sql/client.py`) and the

‎KERNEL_REV‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
a29235cbea9532efa5572ebff010045583a19cbe
1+
4471d5cd5ec0819037293344c1a0bf1d54f2a9d1

‎src/databricks/sql/backend/databricks_client.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from __future__ import annotations
22

33
from abc import ABC, abstractmethod
4-
from typing import Dict, List, Optional, Any, Union, TYPE_CHECKING
4+
from typing import BinaryIO, Dict, List, Optional, Any, Union, TYPE_CHECKING
55

66
if TYPE_CHECKING:
77
from databricks.sql.client import Cursor
@@ -90,6 +90,7 @@ def execute_command(
9090
enforce_embedded_schema_correctness: bool,
9191
row_limit: Optional[int] = None,
9292
query_tags: Optional[Dict[str, Optional[str]]] = None,
93+
input_stream: Optional[BinaryIO] = None,
9394
) -> Union[ResultSet, None]:
9495
"""
9596
Executes a SQL command or query within the specified session.
@@ -110,6 +111,8 @@ def execute_command(
110111
enforce_embedded_schema_correctness: Whether to enforce schema correctness
111112
row_limit: Maximum number of rows in the response.
112113
query_tags: Optional dictionary of query tags to apply for this query only.
114+
input_stream: The content a `PUT '__input_stream__'` uploads, for a
115+
backend that runs Volume transfers inside execute.
113116
114117
Returns:
115118
If async_op is False, returns a ResultSet object containing the

‎src/databricks/sql/backend/kernel/_errors.py‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,14 @@ def reraise_kernel_error(exc: "_kernel.KernelError") -> "Error":
141141
"operation-id": getattr(exc, "query_id", None),
142142
"diagnostic-info": getattr(exc, "diagnostic_info", None),
143143
}
144-
new = cls(getattr(exc, "message", str(exc)), context)
144+
message = getattr(exc, "message", str(exc))
145+
if getattr(exc, "error_code", None) == "VOLUME_STORAGE_HTTP_ERROR":
146+
cls = OperationalError
147+
message = (
148+
"Staging operation over HTTP was unsuccessful: "
149+
f"{getattr(exc, 'http_status', None)}-{message}"
150+
)
151+
new = cls(message, context)
145152

146153
for attr in (
147154
"code",

‎src/databricks/sql/backend/kernel/client.py‎

Lines changed: 52 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -16,18 +16,18 @@
1616
1717
- ``query_tags`` on execute is not supported (kernel exposes
1818
``statement_conf`` but PyO3 doesn't surface it).
19-
- Volume PUT/GET (staging operations): kernel has no Volume API
20-
yet. Users on Thrift-only paths.
2119
"""
2220

2321
from __future__ import annotations
2422

2523
import inspect
2624
import logging
25+
import os
2726
import threading
2827
import uuid
2928
from typing import (
3029
Any,
30+
BinaryIO,
3131
Dict,
3232
FrozenSet,
3333
List,
@@ -84,40 +84,44 @@
8484
# per-request skip-and-warn.
8585
_KERNEL_MANAGED_HEADERS = frozenset({"authorization", "x-databricks-org-id"})
8686

87-
# Leading verbs of SQL volume/staging statements. Detected by the
88-
# leading token (case-insensitive) so the kernel backend can fail loud
89-
# on staging ops it can't service — see ``execute_command``.
90-
_STAGING_VERBS = ("PUT", "GET", "REMOVE")
9187

88+
def _staging_paths(paths: Union[None, str, List[str]]) -> List[str]:
89+
"""``staging_allowed_local_path`` as a list. With none, a REMOVE still
90+
runs, as on Thrift."""
91+
if paths is None:
92+
return []
93+
return [paths] if isinstance(paths, str) else list(paths)
9294

93-
def _strip_leading_sql_comments(sql: str) -> str:
94-
"""Strip leading whitespace and SQL comments (``-- …`` line and
95-
``/* … */`` block, possibly several) from ``sql``, returning the
96-
remainder.
9795

98-
Needed so staging detection sees the real leading verb: a
99-
comment-prefixed staging op (``-- upload\\nPUT …`` or
100-
``/* c */ PUT …``, common in ETL scripts) must still be classified
101-
as staging, or it would slip past the guard into the silent-no-op
102-
bug. Block comments do not nest in Databricks SQL, so a simple
103-
scan-to-``*/`` is correct.
104-
"""
105-
i = 0
106-
n = len(sql)
107-
while i < n:
108-
if sql[i].isspace():
109-
i += 1
110-
elif sql.startswith("--", i):
111-
# Line comment: skip to end of line (or string).
112-
nl = sql.find("\n", i)
113-
i = n if nl == -1 else nl + 1
114-
elif sql.startswith("/*", i):
115-
# Block comment: skip to closing */ (or end if unterminated).
116-
close = sql.find("*/", i + 2)
117-
i = n if close == -1 else close + 2
118-
else:
119-
break
120-
return sql[i:]
96+
def _read_stream(stream: Optional[BinaryIO]) -> Optional[bytes]:
97+
if stream is None:
98+
return None
99+
data = stream.read()
100+
return data.encode("utf-8") if isinstance(data, str) else data
101+
102+
103+
def _volume_error(
104+
exc: BaseException, staging_allowed_local_path: Union[None, str, List[str]]
105+
) -> Optional[Exception]:
106+
"""The exception the Thrift backend raises for the local side of a failed
107+
Volume transfer, or None."""
108+
if getattr(exc, "error_code", None) == "VOLUME_PATH_NOT_ALLOWED":
109+
if staging_allowed_local_path:
110+
return ProgrammingError(
111+
"Local file operations are restricted to paths within the configured staging_allowed_local_path"
112+
)
113+
return ProgrammingError(
114+
"You must provide at least one staging_allowed_local_path when initialising a connection to perform ingestion commands"
115+
)
116+
os_code = getattr(exc, "local_os_error", None)
117+
if os_code is None:
118+
return None
119+
local_path = getattr(exc, "local_path", None)
120+
if os.name == "nt":
121+
# On Windows the kernel reports a Windows error code, which OSError
122+
# maps to errno itself.
123+
return OSError(0, "Local file operation failed", local_path, os_code)
124+
return OSError(os_code, os.strerror(os_code), local_path)
121125

122126

123127
def _is_not_found(exc: BaseException) -> bool:
@@ -155,21 +159,6 @@ def _catalog_or_none(value: Optional[str]) -> Optional[str]:
155159
return value
156160

157161

158-
def _is_staging_statement(operation: str) -> bool:
159-
"""True iff ``operation`` is a volume/staging statement (PUT / GET /
160-
REMOVE).
161-
162-
Strips leading whitespace + SQL comments first (so a comment-
163-
prefixed staging op is still caught), then matches the leading token
164-
only — so a normal query that merely *contains* the word (e.g.
165-
``SELECT 'GET' AS x``) isn't misflagged.
166-
"""
167-
stripped = _strip_leading_sql_comments(operation)
168-
# First whitespace-delimited token, uppercased.
169-
verb = stripped.split(None, 1)[0].upper() if stripped.strip() else ""
170-
return verb in _STAGING_VERBS
171-
172-
173162
class _KernelSessionParameterSupport(NamedTuple):
174163
session_type: Any
175164
parameters: FrozenSet[str]
@@ -643,6 +632,7 @@ def execute_command(
643632
enforce_embedded_schema_correctness: bool,
644633
row_limit: Optional[int] = None,
645634
query_tags: Optional[Dict[str, Optional[str]]] = None,
635+
input_stream: Optional[BinaryIO] = None,
646636
) -> Union["ResultSet", None]:
647637
if self._kernel_session is None:
648638
raise InterfaceError("Cannot execute_command without an open session.")
@@ -655,24 +645,6 @@ def execute_command(
655645
# ``_async_statements`` and closed by ``close_command``); the sync
656646
# path drops it in finally. ``close_stmt`` is the post-success
657647
# decision flag — it stays True on sync, flips to False on async.
658-
# Volume/staging (PUT/GET/REMOVE) is not supported on the kernel
659-
# path: the kernel returns the staging control row as a normal
660-
# result set (``KernelResultSet.is_staging_operation`` is always
661-
# False), so the connector's ``_handle_staging_operation`` never
662-
# fires and NO file is transferred. Rather than silently no-op
663-
# (the Thrift path performs the presigned-URL upload/download),
664-
# fail loud at the call site so ETL scripts don't ingest
665-
# stale/missing data. Detected by the leading SQL verb — the
666-
# only signal available pre-execute, since the kernel exposes no
667-
# staging marker today.
668-
if _is_staging_statement(operation):
669-
raise NotSupportedError(
670-
"Volume / staging operations (PUT / GET / REMOVE) are not "
671-
"supported on the kernel backend (use_kernel=True); the file "
672-
"transfer would silently not happen. Use the Thrift backend "
673-
"for staging operations."
674-
)
675-
676648
close_stmt = True
677649
try:
678650
try:
@@ -687,6 +659,12 @@ def execute_command(
687659
stmt.set_query_tags(query_tags)
688660
if parameters:
689661
bind_tspark_params(stmt, parameters)
662+
# The kernel then runs the file transfer of a Volume PUT, GET or
663+
# REMOVE inside execute.
664+
stmt.set_volume_options(
665+
_staging_paths(cursor.connection.staging_allowed_local_path),
666+
input_bytes=_read_stream(input_stream),
667+
)
690668
if async_op:
691669
async_exec = stmt.submit()
692670
command_id = CommandId.from_sea_statement_id(
@@ -749,7 +727,10 @@ def execute_command(
749727
)
750728
except Exception:
751729
pass
752-
raise _wrap_kernel_exception("execute_command", exc) from exc
730+
raise (
731+
_volume_error(exc, cursor.connection.staging_allowed_local_path)
732+
or _wrap_kernel_exception("execute_command", exc)
733+
) from exc
753734
finally:
754735
with self._sync_cancellers_lock:
755736
self._sync_cancellers.pop(id(cursor), None)
@@ -1031,7 +1012,10 @@ def get_execution_result(
10311012
if uses_owning_handle:
10321013
with self._async_handles_lock:
10331014
self._async_result_stream_started.discard(command_id.guid)
1034-
raise _wrap_kernel_exception("get_execution_result", exc) from exc
1015+
raise (
1016+
_volume_error(exc, cursor.connection.staging_allowed_local_path)
1017+
or _wrap_kernel_exception("get_execution_result", exc)
1018+
) from exc
10351019
# ``KernelResultSet.__init__`` calls ``arrow_schema()`` which
10361020
# can raise — map that to PEP 249 too.
10371021
#

‎src/databricks/sql/backend/kernel/result_set.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,11 @@ def __init__(
100100
# stays O(1) instead of walking the deque.
101101
self._buffered_count: int = 0
102102
self._exhausted: bool = False
103+
if kernel_handle.is_volume_operation:
104+
# The transfer ran inside execute. Like the Thrift backend, which
105+
# reads the instruction row to run it, return no rows.
106+
self._exhausted = True
107+
self.has_more_rows = False
103108

104109
# ----- internal helpers -----
105110

‎src/databricks/sql/backend/sea/backend.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import logging
44
import time
55
import re
6-
from typing import Any, Dict, Tuple, List, Optional, Union, TYPE_CHECKING, Set
6+
from typing import Any, BinaryIO, Dict, Tuple, List, Optional, Union, TYPE_CHECKING, Set
77

88
from databricks.sql.backend.sea.models.base import (
99
ExternalLink,
@@ -482,6 +482,7 @@ def execute_command(
482482
enforce_embedded_schema_correctness: bool,
483483
row_limit: Optional[int] = None,
484484
query_tags: Optional[Dict[str, Optional[str]]] = None,
485+
input_stream: Optional[BinaryIO] = None,
485486
) -> Union[SeaResultSet, None]:
486487
"""
487488
Execute a SQL command using the SEA backend.

‎src/databricks/sql/backend/thrift_backend.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import time
88
import threading
99
import weakref
10-
from typing import Dict, List, Optional, Union, Any, TYPE_CHECKING
10+
from typing import BinaryIO, Dict, List, Optional, Union, Any, TYPE_CHECKING
1111
from uuid import UUID
1212

1313
from databricks.sql.common.unified_http_client import UnifiedHttpClient
@@ -1107,6 +1107,7 @@ def execute_command(
11071107
enforce_embedded_schema_correctness=False,
11081108
row_limit: Optional[int] = None,
11091109
query_tags: Optional[Dict[str, Optional[str]]] = None,
1110+
input_stream: Optional[BinaryIO] = None,
11101111
) -> Union["ResultSet", None]:
11111112
thrift_handle = session_id.to_thrift_handle()
11121113
if not thrift_handle:

0 commit comments

Comments
 (0)