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 CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
# Unreleased
- Support `credentials_provider` on kernel connections (`use_kernel=True`), with the same header refresh and token federation as Thrift.
- 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.
- Support `_proxy_auth_method="negotiate"` (Kerberos proxy authentication) on kernel connections. It requires the `requests-kerberos` package and a kernel release with Negotiate proxy support.
- 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.

# 4.10.0 (2026-11-24)
Expand Down
8 changes: 4 additions & 4 deletions CONNECTION_PARAMETERS.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ to change without notice.
| `_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. |
| `_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). |
| `_proxy_auth_method` | `str` | ✅ | ✅ | `None` | `basic` or `negotiate` (Kerberos). Applied to both Thrift query traffic and the shared Python client. On Kernel, `negotiate` sends the system proxy and Kerberos tokens (from `requests-kerberos`) to the kernel and fails the connection if no token can be created; unset and `basic` keep the kernel's own environment-proxy handling. See [`docs/proxy.md`](docs/proxy.md). |
| `_retry_stop_after_attempts_count` | `int` | ✅ | ✅ | `30` | Max attempts in a retry sequence. Bounded to `[1, 60]` on Thrift; forwarded to the kernel's retry policy. |
| `_retry_stop_after_attempts_duration`| `float` (s) | ✅ | ⚠️ | `900` | Max total wall-clock seconds spent retrying. Kernel rounds to whole seconds. |
| `_retry_delay_min` | `float` (s) | ✅ | ⚠️ | `1` | Minimum backoff delay. Kernel rounds to whole seconds and floors a positive sub-second value at one second. |
Expand Down Expand Up @@ -233,8 +233,7 @@ are forwarded when supported by the installed kernel binding.
`_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
kernel-owned network stack.
9. `_pool_connections` does not configure the kernel-owned network stack.

### Supported on Kernel, missing / ignored on Thrift

Expand All @@ -253,7 +252,8 @@ are forwarded when supported by the installed kernel binding.
Databricks OAuth U2M. Kernel requires an explicit U2M `auth_type` or another
supported credential flow.
- **Connection pooling / proxy**: `_pool_connections` configures only the
shared Python client and `_proxy_auth_method` is not forwarded to Kernel.
shared Python client. Of the `_proxy_auth_method` values, only `negotiate`
changes the kernel's proxy handling.
`_pool_maxsize` also configures the kernel's Rust HTTP pool when positive and
using kernel ≥ 1.1.0. A value of `0` is treated as unset: the Python client
keeps 20 and the kernel keeps 100.
Expand Down
11 changes: 11 additions & 0 deletions docs/proxy.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,17 @@ export HTTPS_PROXY="http://proxy.company.com:8080"
python your_script.py
```

**Kernel backend (`use_kernel=True`):** `negotiate` also works on the kernel
backend, including Reyden connections that recover onto it. It needs the
`requests-kerberos` package, which the `[kernel]` extra does not install. The
proxy and `NO_PROXY` are discovered the same way as above, and a bypassed host
connects directly. The macOS and Windows system bypass lists apply only to the
workspace host; for other hosts, such as CloudFetch storage, the kernel honors
only `NO_PROXY`. A token is created when the session opens and once more if
the proxy answers 407, and it is sent only to the proxy. If no token can be
created (no ticket, expired ticket, missing package), the connection fails
before any request; it never falls back to Basic or a direct connection.

## Proxy Bypass

The connector respects system proxy bypass rules. Requests to hosts listed in `NO_PROXY` or system bypass lists will connect directly, bypassing the proxy.
Expand Down
47 changes: 47 additions & 0 deletions src/databricks/sql/backend/kernel/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,12 @@

from __future__ import annotations

import functools
import inspect
import logging
import threading
import urllib.parse
import urllib.request
import uuid
from typing import (
Any,
Expand Down Expand Up @@ -53,6 +56,7 @@
CommandState,
SessionId,
)
from databricks.sql.common.http_utils import detect_proxy, negotiate_proxy_token
from databricks.sql.exc import (
InterfaceError,
NotSupportedError,
Expand Down Expand Up @@ -238,6 +242,43 @@ def _kernel_geospatial_kwargs(value: bool) -> Dict[str, bool]:
return {"enable_geospatial_support": value}


def _kernel_proxy_kwargs(host: str, proxy_auth_method: Optional[str]) -> Dict[str, Any]:
"""Build the kernel proxy kwargs for ``_proxy_auth_method="negotiate"``.

The proxy is discovered as on Thrift (``getproxies()`` + ``proxy_bypass``).
When a proxy applies, the kernel gets its URL, the ``NO_PROXY`` list and a
callable that creates a fresh token for ``HTTP@<proxy host>``. The kernel
calls it at session open and once more on a proxy 407, and fails closed if
it raises. No proxy, a bypassed host, unset and ``basic`` pass nothing, so
the kernel keeps its environment-proxy behavior.
"""
if proxy_auth_method != "negotiate":
return {}
# A ``_connection_uri`` host is ``scheme://host[:port]``; look the proxy up by
# its scheme and bare hostname, as Thrift does.
target = urllib.parse.urlsplit(host if "://" in host else f"https://{host}")
proxy = detect_proxy(target.scheme, target.hostname)
if not proxy:
return {}
if not _kernel_session_accepts_kwarg("proxy_negotiate_token"):
raise NotSupportedError(
"_proxy_auth_method='negotiate' requires a newer databricks-sql-kernel "
"wheel that supports Negotiate proxy authentication."
)
parsed = urllib.parse.urlparse(proxy)
# Negotiate replaces Basic, so drop any user:password@ from the URL.
kwargs: Dict[str, Any] = {
"proxy_url": parsed._replace(netloc=parsed.netloc.rpartition("@")[2]).geturl(),
"proxy_negotiate_token": functools.partial(
negotiate_proxy_token, parsed.hostname
),
}
bypass = urllib.request.getproxies().get("no")
Comment thread
cathleeny marked this conversation as resolved.
Resolved
if bypass:
kwargs["proxy_bypass_hosts"] = bypass
return kwargs


def _validate_telemetry_flush_interval_ms(value: Any) -> None:
# PyO3 would accept True as 1ms and report other bad values without
# naming the option, so reject them before the kernel sees them.
Expand Down Expand Up @@ -365,6 +406,8 @@ def __init__(
# Kernel telemetry phase 7 adds binding/runtime identity and
# telemetry config kwargs directly to ``databricks_sql_kernel.Session``.
self._telemetry_options = kwargs.get("telemetry_options") or {}
# Only "negotiate" changes the kernel's proxy handling.
self._proxy_auth_method = kwargs.get("proxy_auth_method")
_validate_telemetry_flush_interval_ms(
self._telemetry_options.get("telemetry_flush_interval_ms")
)
Expand Down Expand Up @@ -506,6 +549,9 @@ def open_session(
"that accepts a connection port."
)
port_kwargs["port"] = self._port
proxy_kwargs = _kernel_proxy_kwargs(
self._server_hostname, self._proxy_auth_method
)
max_connections_kwargs: Dict[str, Any] = {}
if _kernel_session_accepts_kwarg("max_connections"):
max_connections_kwargs["max_connections"] = self._max_connections
Expand Down Expand Up @@ -557,6 +603,7 @@ def open_session(
**port_kwargs,
**max_connections_kwargs,
**http_headers_kwargs,
**proxy_kwargs,
)
except Exception as exc:
raise _wrap_kernel_exception("open_session", exc) from exc
Expand Down
72 changes: 60 additions & 12 deletions src/databricks/sql/common/http_utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import base64
import ssl
import urllib.parse
import urllib.request
Expand Down Expand Up @@ -31,18 +32,7 @@ def detect_and_parse_proxy(
Returns:
Tuple of (proxy_uri, proxy_headers) or (None, None) if no proxy
"""
try:
# returns a dictionary of scheme -> proxy server URL mappings.
# https://docs.python.org/3/library/urllib.request.html#urllib.request.getproxies
proxy = urllib.request.getproxies().get(scheme)
except (KeyError, AttributeError):
# No proxy found or getproxies() failed - disable proxy
proxy = None
else:
# Proxy found, but check if this host should bypass proxy (unless skipped)
if not skip_bypass and host and urllib.request.proxy_bypass(host):
proxy = None # Host bypasses proxy per system rules

proxy = detect_proxy(scheme, host, skip_bypass)
if not proxy:
return None, None

Expand All @@ -60,13 +50,71 @@ def detect_and_parse_proxy(
return proxy, proxy_headers


def detect_proxy(
scheme: str, host: Optional[str], skip_bypass: bool = False
) -> Optional[str]:
"""Return the system proxy URL for ``scheme``, or None if there is none
or ``host`` bypasses it."""
try:
# returns a dictionary of scheme -> proxy server URL mappings.
# https://docs.python.org/3/library/urllib.request.html#urllib.request.getproxies
proxy = urllib.request.getproxies().get(scheme)
except (KeyError, AttributeError):
# No proxy found or getproxies() failed - disable proxy
return None
# Proxy found, but check if this host should bypass proxy (unless skipped)
if not skip_bypass and host and urllib.request.proxy_bypass(host):
return None # Host bypasses proxy per system rules
return proxy


class _DropSpnegoTokenLogs(logging.Filter):
"""Drop pyspnego's DEBUG "<mech> step input/output: <token>" records."""

def filter(self, record: logging.LogRecord) -> bool:
return " step " not in str(record.msg)


_SPNEGO_TOKEN_FILTER = _DropSpnegoTokenLogs()


def _hide_spnego_tokens() -> None:
for name in ("spnego._gss", "spnego._negotiate", "spnego._sspi"):
spnego_logger = logging.getLogger(name)
if _SPNEGO_TOKEN_FILTER not in spnego_logger.filters:
spnego_logger.addFilter(_SPNEGO_TOKEN_FILTER)


def negotiate_proxy_token(proxy_hostname: Optional[str]) -> bytes:
"""Return one fresh raw Kerberos token for ``HTTP@<proxy_hostname>``.

Uses requests-kerberos like the Thrift path, but raises instead of
returning nothing so the caller fails closed.
"""
try:
from requests_kerberos import HTTPKerberosAuth
except ImportError as e:
raise ImportError(
"_proxy_auth_method='negotiate' requires the requests-kerberos package"
) from e
_hide_spnego_tokens()
header = HTTPKerberosAuth().generate_request_header(
None, proxy_hostname, is_preemptive=True
)
scheme, _, token = (header or "").partition(" ")
if scheme != "Negotiate" or not token:
raise ValueError("requests-kerberos returned no Negotiate token")
return base64.b64decode(token)


def _generate_negotiate_headers(
proxy_hostname: Optional[str],
) -> Optional[Dict[str, str]]:
"""Generate Kerberos/SPNEGO authentication headers"""
try:
from requests_kerberos import HTTPKerberosAuth

_hide_spnego_tokens()
logger.debug(
"Attempting to generate Kerberos SPNEGO token for proxy: %s", proxy_hostname
)
Expand Down
1 change: 1 addition & 0 deletions src/databricks/sql/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,7 @@ def _create_backend(
),
telemetry_options=kernel_telemetry_options,
escape_catalog_name=kwargs.get("escape_catalog_name", False),
proxy_auth_method=kwargs.get("_proxy_auth_method"),
)

# These reference the lazily-resolved module attributes defined via
Expand Down
Loading
Loading