Skip to content
Open
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
1 change: 1 addition & 0 deletions .github/workflows/kernel-e2e.yml
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@ jobs:
DATABRICKS_SERVER_HOSTNAME: ${{ secrets.DATABRICKS_HOST }}
DATABRICKS_HTTP_PATH: ${{ secrets.TEST_PECO_WAREHOUSE_HTTP_PATH }}
DATABRICKS_TOKEN: ${{ secrets.DATABRICKS_TOKEN }}
DATABRICKS_CATALOG: peco
steps:
- name: Check out connector
uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# Unreleased
- 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.
- 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.
- 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`. Requires a databricks-sql-kernel release that includes databricks/databricks-sql-kernel#520 and #521.

# 4.10.0 (2026-11-24)
- Upgrade Databricks SQL Kernel to 1.5.0, with lower overhead for buffered fetches and closing drained cursors, and Arrow and Quinn security updates.
Expand Down
20 changes: 14 additions & 6 deletions CONNECTION_PARAMETERS.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ to change without notice.

| Option | Type | Thrift | Kernel | Default Value | Note |
| ------------------------------------ | ----------- | :----: | :----: | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `_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. |
| `_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. |
| `_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. |
| `_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. |
| `_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). |
Expand Down Expand Up @@ -191,7 +191,7 @@ environment. The backends differ for SOCKS proxies:
| `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. |
| `ignore_transactions` | `bool` | ✅ | ✅ | `True` | When `True`: `commit()` is a no-op, `rollback()` raises `NotSupportedError`, and setting `autocommit` is a no-op. |
| `fetch_autocommit_from_server`| `bool` | ✅ | ✅ | `False` | Query the server (`SET AUTOCOMMIT`) for autocommit state instead of returning the cached value. |
| `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. |
| `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). |

## Telemetry

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

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

### Volume file paths

With `use_kernel=True`, SQL `PUT`, `GET` and `REMOVE` run their file transfer
inside `execute()` or `get_async_execution_result()`. `PUT` and `GET` need local
paths, with symlinks resolved, within `staging_allowed_local_path`; `REMOVE`
needs none. `execute(input_stream=stream)` reads the stream before the statement
runs. A `PUT` reads a regular file; pass other data, such as a pipe's content,
as `input_stream`. Cancelling or closing the cursor stops a running transfer.

> All kernel-path behavior reflects the current **early-access** surface and is
> subject to change. Generated against connector version `4.5.0`; the source of
> truth is `Connection.__init__` (`src/databricks/sql/client.py`) and the
Expand Down
2 changes: 1 addition & 1 deletion KERNEL_REV
Original file line number Diff line number Diff line change
@@ -1 +1 @@
a29235cbea9532efa5572ebff010045583a19cbe
d18b044bdd8d6a3ef7c7dd763a5f38c1532a213f
5 changes: 4 additions & 1 deletion src/databricks/sql/backend/databricks_client.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

from abc import ABC, abstractmethod
from typing import Dict, List, Optional, Any, Union, TYPE_CHECKING
from typing import BinaryIO, Dict, List, Optional, Any, Union, TYPE_CHECKING

if TYPE_CHECKING:
from databricks.sql.client import Cursor
Expand Down Expand Up @@ -90,6 +90,7 @@ def execute_command(
enforce_embedded_schema_correctness: bool,
row_limit: Optional[int] = None,
query_tags: Optional[Dict[str, Optional[str]]] = None,
input_stream: Optional[BinaryIO] = None,
) -> Union[ResultSet, None]:
"""
Executes a SQL command or query within the specified session.
Expand All @@ -110,6 +111,8 @@ def execute_command(
enforce_embedded_schema_correctness: Whether to enforce schema correctness
row_limit: Maximum number of rows in the response.
query_tags: Optional dictionary of query tags to apply for this query only.
input_stream: The content a `PUT '__input_stream__'` uploads, for a
backend that runs Volume transfers inside execute.

Returns:
If async_op is False, returns a ResultSet object containing the
Expand Down
9 changes: 8 additions & 1 deletion src/databricks/sql/backend/kernel/_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,14 @@ def reraise_kernel_error(exc: "_kernel.KernelError") -> "Error":
"operation-id": getattr(exc, "query_id", None),
"diagnostic-info": getattr(exc, "diagnostic_info", None),
}
new = cls(getattr(exc, "message", str(exc)), context)
message = getattr(exc, "message", str(exc))
if getattr(exc, "error_code", None) == "VOLUME_STORAGE_HTTP_ERROR":
cls = OperationalError
message = (
"Staging operation over HTTP was unsuccessful: "
f"{getattr(exc, 'http_status', None)}-{message}"
)
new = cls(message, context)

for attr in (
"code",
Expand Down
125 changes: 57 additions & 68 deletions src/databricks/sql/backend/kernel/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,18 @@

- ``query_tags`` on execute is not supported (kernel exposes
``statement_conf`` but PyO3 doesn't surface it).
- Volume PUT/GET (staging operations): kernel has no Volume API
yet. Users on Thrift-only paths.
"""

from __future__ import annotations

import inspect
import logging
import os
import threading
import uuid
from typing import (
Any,
BinaryIO,
Dict,
FrozenSet,
List,
Expand Down Expand Up @@ -84,40 +84,49 @@
# per-request skip-and-warn.
_KERNEL_MANAGED_HEADERS = frozenset({"authorization", "x-databricks-org-id"})

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

def _staging_paths(paths: object) -> List[str]:
"""``staging_allowed_local_path`` as a list. A value that is not a path or
a list of paths allows none, so a PUT or GET fails while a REMOVE still
runs, as on Thrift."""
if isinstance(paths, (str, os.PathLike)):
paths = [paths]
if isinstance(paths, (list, tuple)) and all(
isinstance(path, (str, os.PathLike)) for path in paths
):
return [os.fspath(path) for path in paths]
return []

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

Needed so staging detection sees the real leading verb: a
comment-prefixed staging op (``-- upload\\nPUT …`` or
``/* c */ PUT …``, common in ETL scripts) must still be classified
as staging, or it would slip past the guard into the silent-no-op
bug. Block comments do not nest in Databricks SQL, so a simple
scan-to-``*/`` is correct.
"""
i = 0
n = len(sql)
while i < n:
if sql[i].isspace():
i += 1
elif sql.startswith("--", i):
# Line comment: skip to end of line (or string).
nl = sql.find("\n", i)
i = n if nl == -1 else nl + 1
elif sql.startswith("/*", i):
# Block comment: skip to closing */ (or end if unterminated).
close = sql.find("*/", i + 2)
i = n if close == -1 else close + 2
else:
break
return sql[i:]
def _read_stream(stream: Optional[BinaryIO]) -> Optional[bytes]:
if stream is None:
return None
data = stream.read()
return data.encode("utf-8") if isinstance(data, str) else data


def _volume_error(
exc: BaseException, staging_allowed_local_path: object
) -> Optional[Exception]:
"""The exception the Thrift backend raises for the local side of a failed
Volume transfer, or None."""
if getattr(exc, "error_code", None) == "VOLUME_PATH_NOT_ALLOWED":
if _staging_paths(staging_allowed_local_path):
return ProgrammingError(
"Local file operations are restricted to paths within the configured staging_allowed_local_path"
)
return ProgrammingError(
"You must provide at least one staging_allowed_local_path when initialising a connection to perform ingestion commands"
)
os_code = getattr(exc, "local_os_error", None)
if os_code is None:
return None
local_path = getattr(exc, "local_path", None)
if os.name == "nt":
# On Windows the kernel reports a Windows error code, which OSError
# maps to errno itself.
return OSError(0, "Local file operation failed", local_path, os_code)
return OSError(os_code, os.strerror(os_code), local_path)


def _is_not_found(exc: BaseException) -> bool:
Expand Down Expand Up @@ -155,21 +164,6 @@ def _catalog_or_none(value: Optional[str]) -> Optional[str]:
return value


def _is_staging_statement(operation: str) -> bool:
"""True iff ``operation`` is a volume/staging statement (PUT / GET /
REMOVE).

Strips leading whitespace + SQL comments first (so a comment-
prefixed staging op is still caught), then matches the leading token
only — so a normal query that merely *contains* the word (e.g.
``SELECT 'GET' AS x``) isn't misflagged.
"""
stripped = _strip_leading_sql_comments(operation)
# First whitespace-delimited token, uppercased.
verb = stripped.split(None, 1)[0].upper() if stripped.strip() else ""
return verb in _STAGING_VERBS


class _KernelSessionParameterSupport(NamedTuple):
session_type: Any
parameters: FrozenSet[str]
Expand Down Expand Up @@ -643,6 +637,7 @@ def execute_command(
enforce_embedded_schema_correctness: bool,
row_limit: Optional[int] = None,
query_tags: Optional[Dict[str, Optional[str]]] = None,
input_stream: Optional[BinaryIO] = None,
) -> Union["ResultSet", None]:
if self._kernel_session is None:
raise InterfaceError("Cannot execute_command without an open session.")
Expand All @@ -655,24 +650,6 @@ def execute_command(
# ``_async_statements`` and closed by ``close_command``); the sync
# path drops it in finally. ``close_stmt`` is the post-success
# decision flag — it stays True on sync, flips to False on async.
# Volume/staging (PUT/GET/REMOVE) is not supported on the kernel
# path: the kernel returns the staging control row as a normal
# result set (``KernelResultSet.is_staging_operation`` is always
# False), so the connector's ``_handle_staging_operation`` never
# fires and NO file is transferred. Rather than silently no-op
# (the Thrift path performs the presigned-URL upload/download),
# fail loud at the call site so ETL scripts don't ingest
# stale/missing data. Detected by the leading SQL verb — the
# only signal available pre-execute, since the kernel exposes no
# staging marker today.
if _is_staging_statement(operation):
raise NotSupportedError(
"Volume / staging operations (PUT / GET / REMOVE) are not "
"supported on the kernel backend (use_kernel=True); the file "
"transfer would silently not happen. Use the Thrift backend "
"for staging operations."
)

close_stmt = True
try:
try:
Expand All @@ -687,6 +664,12 @@ def execute_command(
stmt.set_query_tags(query_tags)
if parameters:
bind_tspark_params(stmt, parameters)
# The kernel then runs the file transfer of a Volume PUT, GET or
# REMOVE inside execute.
stmt.set_volume_options(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High — The kernel client now calls stmt.set_volume_options and reads is_volume_operation on every statement. pyproject still allows kernel ^1.5.0, which lacks those APIs, so every execute can fail with AttributeError. Raise the dependency floor and the lock to the kernel release that has the Volume API.

🔀 Found by GPT-6.1 Sol · confirmed by the judge

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same release gate as #1057 (comment). databricks/databricks-sql-kernel#520 and #521 are merged (KERNEL_REV now pins d18b044b), but the floor and lock in pyproject.toml and poetry.lock can only move once a kernel release ships, so this stays open until then.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still open at c3cce98: the kernel ^1.5.0 floor and lock remain unchanged, so this stays release-gated until a kernel release with the Volume API ships.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High — set_volume_options is called on every kernel statement, but pyproject.toml still allows ^1.5.0, which lacks it. Every execute(), including SELECT, would fail on a released wheel. Gate the call on the method existing, or raise the floor when the supporting kernel ships.

🔀 Found by both reviewers · confirmed by the judge

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same release gate as #1057 (comment). databricks/databricks-sql-kernel#520 and #521 are merged (KERNEL_REV now pins d18b044b), but the floor and lock in pyproject.toml and poetry.lock can only move once a kernel release ships, so this stays open until then.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still open at c3cce98: client.py:669 calls set_volume_options unconditionally, and the kernel floor still allows wheels that lack it.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High — set_volume_options is called on every statement, and KernelResultSet reads kernel_handle.is_volume_operation on every result. Neither is gated, and pyproject.toml still allows kernel ^1.5.0. If 1.5.0 lacks these APIs, every execute() fails. Gate both with hasattr and keep rejecting PUT/GET/REMOVE on old wheels, or raise the kernel floor in pyproject.toml and poetry.lock to a release that has them.

🔀 Found by both reviewers · confirmed by the judge

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same release gate as #1057 (comment). databricks/databricks-sql-kernel#520 and #521 are merged (KERNEL_REV now pins d18b044b), but the floor and lock in pyproject.toml and poetry.lock can only move once a kernel release ships, so this stays open until then.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still open at c3cce98: set_volume_options at client.py:669 isn't gated, and the kernel floor in pyproject.toml/poetry.lock is still ^1.5.0.

_staging_paths(cursor.connection.staging_allowed_local_path),
input_bytes=_read_stream(input_stream),
)
if async_op:
async_exec = stmt.submit()
command_id = CommandId.from_sea_statement_id(
Expand Down Expand Up @@ -749,7 +732,10 @@ def execute_command(
)
except Exception:
pass
raise _wrap_kernel_exception("execute_command", exc) from exc
raise (
_volume_error(exc, cursor.connection.staging_allowed_local_path)
or _wrap_kernel_exception("execute_command", exc)
) from exc
finally:
with self._sync_cancellers_lock:
self._sync_cancellers.pop(id(cursor), None)
Expand Down Expand Up @@ -1031,7 +1017,10 @@ def get_execution_result(
if uses_owning_handle:
with self._async_handles_lock:
self._async_result_stream_started.discard(command_id.guid)
raise _wrap_kernel_exception("get_execution_result", exc) from exc
raise (
Comment thread
aakash-saravanan-db marked this conversation as resolved.
Resolved
_volume_error(exc, cursor.connection.staging_allowed_local_path)
or _wrap_kernel_exception("get_execution_result", exc)
) from exc
# ``KernelResultSet.__init__`` calls ``arrow_schema()`` which
# can raise — map that to PEP 249 too.
#
Expand Down
5 changes: 5 additions & 0 deletions src/databricks/sql/backend/kernel/result_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,11 @@ def __init__(
# stays O(1) instead of walking the deque.
self._buffered_count: int = 0
self._exhausted: bool = False
if kernel_handle.is_volume_operation:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High — kernel_handle.is_volume_operation is read unconditionally in KernelResultSet.__init__. A 1.5.0 kernel handle lacks it, so every result set raises AttributeError. Use getattr(kernel_handle, 'is_volume_operation', False) or raise the dependency floor.

🔀 Found by Claude Opus 5.5 · confirmed by the judge

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same release gate as #1057 (comment). databricks/databricks-sql-kernel#520 and #521 are merged (KERNEL_REV now pins d18b044b), but the floor and lock in pyproject.toml and poetry.lock can only move once a kernel release ships, so this stays open until then.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still open at c3cce98: result_set.py:103 reads is_volume_operation without a guard, and the kernel floor hasn't been raised. Waiting on the kernel release.

# The transfer ran inside execute. Like the Thrift backend, which
# reads the instruction row to run it, return no rows.
self._exhausted = True
self.has_more_rows = False

# ----- internal helpers -----

Expand Down
3 changes: 2 additions & 1 deletion src/databricks/sql/backend/sea/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import logging
import time
import re
from typing import Any, Dict, Tuple, List, Optional, Union, TYPE_CHECKING, Set
from typing import Any, BinaryIO, Dict, Tuple, List, Optional, Union, TYPE_CHECKING, Set

from databricks.sql.backend.sea.models.base import (
ExternalLink,
Expand Down Expand Up @@ -482,6 +482,7 @@ def execute_command(
enforce_embedded_schema_correctness: bool,
row_limit: Optional[int] = None,
query_tags: Optional[Dict[str, Optional[str]]] = None,
input_stream: Optional[BinaryIO] = None,
) -> Union[SeaResultSet, None]:
"""
Execute a SQL command using the SEA backend.
Expand Down
3 changes: 2 additions & 1 deletion src/databricks/sql/backend/thrift_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import time
import threading
import weakref
from typing import Dict, List, Optional, Union, Any, TYPE_CHECKING
from typing import BinaryIO, Dict, List, Optional, Union, Any, TYPE_CHECKING
from uuid import UUID

from databricks.sql.common.unified_http_client import UnifiedHttpClient
Expand Down Expand Up @@ -1107,6 +1107,7 @@ def execute_command(
enforce_embedded_schema_correctness=False,
row_limit: Optional[int] = None,
query_tags: Optional[Dict[str, Optional[str]]] = None,
input_stream: Optional[BinaryIO] = None,
) -> Union["ResultSet", None]:
thrift_handle = session_id.to_thrift_handle()
if not thrift_handle:
Expand Down
4 changes: 3 additions & 1 deletion src/databricks/sql/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,8 @@ def read(self) -> Optional[OAuthToken]:
# On Thrift, the timeout in seconds for socket send, recv and connect
# operations. On the kernel path, a positive value is the total HTTP
# request deadline. Kernel values of None or 0 select its 120-second
# default; 0 is neither unlimited nor an immediate timeout.
# default; 0 is neither unlimited nor an immediate timeout. For a
# Volume file transfer the kernel uses it as an idle limit instead.
# _disable_pandas
# In case the deserialisation through pandas causes any issues, it can be disabled with
# this flag.
Expand Down Expand Up @@ -1613,6 +1614,7 @@ def execute(
enforce_embedded_schema_correctness=enforce_embedded_schema_correctness,
row_limit=self.row_limit,
query_tags=query_tags,
input_stream=input_stream,
)

# Surface the affected-row count for DML (INSERT/UPDATE/DELETE/MERGE) as
Expand Down
Loading
Loading