Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
db9a0fe
feat(kernel): honor _port and _connection_uri on use_kernel connections
cathleeny Nov 19, 2026
d98ca45
fix(kernel): type _kernel_host_and_path http_path as str
cathleeny Nov 19, 2026
5bb846e
fix(kernel): match main for default host resolution and PAT OAuth guard
cathleeny Nov 19, 2026
6a78cef
fix(kernel): black formatting and OAuth guard follows the auth bridge
cathleeny Nov 19, 2026
8f96c0b
fix(kernel): keep credentials and resolved host details out of error …
cathleeny Nov 19, 2026
6250c28
fix(kernel): sanitize connection-URI parse errors and wrap long messages
cathleeny Nov 19, 2026
f27c165
fix(kernel): drop the whole authority from errors when credentials ma…
cathleeny Nov 19, 2026
c90459f
Embedded host port wins over a differing _port on the kernel path
cathleeny Nov 19, 2026
bc7c09e
Reject a path, query or fragment host combined with _port; document k…
cathleeny Nov 19, 2026
bdeef64
kernel: parse host:port with urllib and check the JWT issuer origin
cathleeny Nov 20, 2026
f242c0f
kernel: skip ip_address for host names on the host:port path
cathleeny Nov 20, 2026
5082c7e
kernel: drop bare IPv6 support on the host:port path
cathleeny Nov 20, 2026
0de7c86
fix(kernel): narrow access_token before the foreign-JWT check
cathleeny Nov 20, 2026
a6936af
fix(kernel): don't echo a non-http(s) prefix in _connection_uri errors
cathleeny Nov 20, 2026
973b4e2
fix(kernel): guard the URI origin when identity_federation_client_id …
cathleeny Nov 20, 2026
81c1cff
fix(kernel): pass the host through unchanged for _port=443
cathleeny Nov 23, 2026
233f2b5
fix(kernel): report an uncomparable server_hostname as an OAuth origi…
cathleeny Nov 23, 2026
12ed5dc
refactor(kernel): let the kernel apply _port
cathleeny Nov 25, 2026
6272ae0
Merge origin/main (4.10.0) into feat/kernel-honor-port-uri-parity
cathleeny Nov 25, 2026
01999fa
fix(kernel): guard a JWT that is foreign to the _connection_uri host
cathleeny Nov 25, 2026
1453b26
fix(kernel): reject a _connection_uri with an empty port
cathleeny Nov 25, 2026
7f13a63
docs(changelog): shorten the port entry
cathleeny Nov 30, 2026
bad2b25
refactor(kernel): pass _port to the kernel as is
cathleeny Nov 30, 2026
b0e2329
refactor(kernel): drop the OAuth origin guard and trim _connection_ur…
cathleeny Nov 30, 2026
65679c4
docs(kernel): an invalid _port raises OperationalError
cathleeny Nov 30, 2026
4b29999
fix(kernel): raise NotSupportedError for _port on a kernel without port
cathleeny Nov 30, 2026
26b187a
chore(kernel): pin KERNEL_REV to the merged kernel port change
cathleeny Nov 30, 2026
4849a44
test(kernel): fail the loopback tests clearly when a stub shadows the…
cathleeny Nov 30, 2026
976b80c
ci(kernel-e2e): run the real-kernel session tests on the source-built…
cathleeny Nov 30, 2026
c4f02b4
fix(kernel): accept a digit-string _port on the kernel path
cathleeny Dec 1, 2026
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
5 changes: 5 additions & 0 deletions .github/workflows/kernel-e2e.yml
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,11 @@ jobs:
- name: Run async reader routing tests
run: $CONNECTOR_VENV_PY -m pytest tests/unit/test_kernel_async_readers.py -m realkernel -v

- name: Run real-kernel session tests (port loopback dials)
# Published wheels without the `port` kwarg skip these, so run them
# against the wheel built from KERNEL_REV.
run: $CONNECTOR_VENV_PY -m pytest tests/unit/test_session.py -m realkernel -v

- name: Run kernel e2e tests
run: poetry run pytest tests/e2e/test_kernel_backend.py -v

Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Release History

# 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.

# 4.10.0 (2026-11-24)
Expand Down
7 changes: 3 additions & 4 deletions CONNECTION_PARAMETERS.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ to change without notice.
| ----------------- | ----- | :----: | :----: | ------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `server_hostname` | `str` | ✅ | ✅ | — (required) | Workspace hostname, e.g. `dbc-12345.cloud.databricks.com`. |
| `http_path` | `str` | ✅ | ✅ | — (required) | Thrift accepts a SQL-warehouse path **or** an all-purpose-cluster path; Kernel requires a warehouse/endpoint path. |
| `_port` | `int` | ✅ | — | `443` | TCP port (advanced). Not threaded to the kernel; it derives host/port from `server_hostname` + `http_path`. |
| `_connection_uri` | `str` | ✅ | — | `None` | Thrift-only internal override of `server_hostname`/`http_path`. No kernel equivalent. |
| `_port` | `int` | ✅ | ✅ | `443` | TCP port (advanced). A digit string such as `"8443"` is accepted as that int. On Kernel it is passed to the kernel, which validates and applies it: a port other than 443 makes the connection use `host:port`; `0`, unset and `443` change nothing; a non-default port embedded in `server_hostname` wins over a differing `_port` (with a warning). An IPv6 host needs brackets (`[::1]`). An invalid port raises `OperationalError` (wrapping the kernel's `ValueError`); a host that can't take the port raises `ProgrammingError`, and the error never repeats the host. Needs a databricks-sql-kernel release that includes databricks-sql-kernel#505. |
| `_connection_uri` | `str` | ✅ | ✅ | `None` | Overrides `server_hostname`, `_port` and `http_path` on both, and wins over `_port`. On Kernel, OAuth also uses the URI's host:port (Thrift keeps OAuth on `server_hostname`). Credentials in the URI are rejected. |
| `http_headers` | `List[Tuple[str, str]]` | ✅ | ⚠️ | `None` | Extra headers sent on requests. Kernel filters `Authorization` and `x-databricks-org-id` because it manages them itself; other headers are forwarded. |
| `user_agent_entry`| `str` | ✅ | ✅ | `None` | Custom tag folded into the composed `User-Agent` on both. (`_user_agent_entry` is a deprecated alias that warns.) |

Expand Down Expand Up @@ -213,8 +213,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. `_port` and `_connection_uri`.
10. `_pool_connections` and `_proxy_auth_method` do not configure the
9. `_pool_connections` and `_proxy_auth_method` do not configure the
kernel-owned network stack.

### Supported on Kernel, missing / ignored on Thrift
Expand Down
2 changes: 1 addition & 1 deletion KERNEL_REV
Original file line number Diff line number Diff line change
@@ -1 +1 @@
5c3a909771f749174567af074bfe18c24a335f5c
3b691d2a2c235ef847d61b308c31604979830994
18 changes: 15 additions & 3 deletions src/databricks/sql/backend/kernel/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,10 +321,12 @@ def __init__(
# toggles, mTLS client cert/key). ``http_headers`` is forwarded
# to the kernel as custom request headers (it carries the
# connector's composed ``User-Agent`` + any caller headers + the
# SPOG ``x-databricks-org-id``). ``http_client`` / ``port`` are
# still accept-and-ignore — the kernel manages its own HTTP
# stack.
# SPOG ``x-databricks-org-id``). ``port`` (the resolved ``_port``,
# or ``None``) is forwarded as the kernel's ``port`` kwarg, which
# the kernel applies to ``server_hostname``. ``http_client`` is
# accept-and-ignore — the kernel manages its own HTTP stack.
self._server_hostname = server_hostname
self._port: Any = kwargs.get("port")
self._http_path = http_path
self._auth_provider = auth_provider
self._ssl_options = ssl_options
Expand Down Expand Up @@ -488,6 +490,15 @@ def open_session(
geospatial_kwargs = _kernel_geospatial_kwargs(
self._enable_geospatial_support
)
# The kernel validates the port and applies it to the host; unset sends nothing.
port_kwargs: Dict[str, Any] = {}
if self._port is not None:
Comment thread
cathleeny marked this conversation as resolved.
Resolved
Comment thread
cathleeny marked this conversation as resolved.
Resolved
Comment thread
cathleeny marked this conversation as resolved.
Resolved
Comment thread
cathleeny marked this conversation as resolved.
Resolved
if not _kernel_session_accepts_kwarg("port"):
Comment thread
cathleeny marked this conversation as resolved.
Resolved
raise NotSupportedError(
Comment thread
cathleeny marked this conversation as resolved.
Resolved
"_port requires a newer databricks-sql-kernel wheel "
"that accepts a connection port."
)
port_kwargs["port"] = self._port
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 @@ -536,6 +547,7 @@ def open_session(
**retry_kwargs,
**telemetry_kwargs,
**geospatial_kwargs,
**port_kwargs,
Comment thread
cathleeny marked this conversation as resolved.
Resolved
Comment thread
cathleeny marked this conversation as resolved.
Resolved
**max_connections_kwargs,
**http_headers_kwargs,
)
Expand Down
4 changes: 4 additions & 0 deletions src/databricks/sql/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,10 @@ def __init__(
decision. This is an intentional divergence from the
Thrift/SEA paths, where an explicit ``True`` can still
be suppressed by the feature flag.

Kernel overrides: _port is passed to the kernel, which applies it to
the host. _connection_uri (https://host[:port]/path?query) sets host,
port, path and query, as on Thrift, and wins over _port.
:param enable_geospatial_support: `bool`, optional (default is False)
Kernel backend only. Controls the public representation of
``GEOMETRY`` and ``GEOGRAPHY`` result values. ``True`` returns
Expand Down
44 changes: 42 additions & 2 deletions src/databricks/sql/session.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import logging
import re
from functools import cached_property
from urllib.parse import urlsplit
from typing import Dict, Tuple, List, Optional, Any, Type, TYPE_CHECKING

from databricks.sql.types import SSLOptions
Expand Down Expand Up @@ -47,6 +48,31 @@ def __getattr__(name: str) -> Any:
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")


def _kernel_endpoint(
server_hostname: str, http_path: str, kwargs: dict
) -> Tuple[str, str, Any]:
"""Resolve the kernel ``(host, http_path, port)``. ``_connection_uri`` gives the host
(with any port in it) and the path, and wins over ``_port``. Otherwise the arguments
pass through as is; the kernel validates the port and applies it to the host.
"""
uri = kwargs.get("_connection_uri")
if not uri:
port = kwargs.get("_port")
# A digit string (e.g. from an env var or DSN) becomes the int it names, as Thrift
# accepts it. This is type coercion only; any other value reaches the kernel as is.
if isinstance(port, str) and port.strip().isascii() and port.strip().isdigit():
port = int(port)
return server_hostname, http_path, port
parts = urlsplit(uri)
# Credentials in the URI would reach the transport, so they are refused here.
if parts.scheme not in ("http", "https") or not parts.netloc or "@" in parts.netloc:
raise ValueError(
"Invalid _connection_uri: expected http(s)://host[:port]/path with no credentials"
)
path = parts.path + (f"?{parts.query}" if parts.query else "")
return f"{parts.scheme}://{parts.netloc}", path, None


class Session:
def __init__(
self,
Expand Down Expand Up @@ -323,9 +349,23 @@ def _create_backend(
"_telemetry_circuit_breaker_enabled"
),
}
kernel_host, kernel_http_path, kernel_port = _kernel_endpoint(
server_hostname, http_path, kwargs
)
if kernel_http_path != http_path:
# A _connection_uri can point at another workspace: re-derive the
# SPOG org-id header from the resolved path (a caller header still wins).
base_headers = [
h for h in all_headers if h not in self._spog_headers.items()
]
self._spog_headers = self._extract_spog_headers(
kernel_http_path, base_headers
)
all_headers = base_headers + list(self._spog_headers.items())
return KernelDatabricksClient(
server_hostname=server_hostname,
http_path=http_path,
server_hostname=kernel_host,
Comment thread
oss-reviewer-bot[bot] marked this conversation as resolved.
Resolved
http_path=kernel_http_path,
port=kernel_port,
http_headers=all_headers,
auth_provider=auth_provider,
ssl_options=self.ssl_options,
Expand Down
64 changes: 64 additions & 0 deletions tests/unit/test_kernel_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,70 @@ def test_geospatial_option_rejects_non_bool():
kernel_client._kernel_geospatial_kwargs("false")


@pytest.mark.parametrize("port", [8443, 443, 0])
def test_open_session_passes_port_to_kernel_as_port_kwarg(monkeypatch, port):
"""A set ``_port`` reaches the binding as ``port=`` as is. The host is passed
unchanged: the kernel validates the port and applies it, not the driver."""
captured = {}

def fake_session(**kw):
captured.update(kw)
return MagicMock(session_id="sess-id")

monkeypatch.setattr(kernel_client._kernel, "Session", fake_session)
c = kernel_client.KernelDatabricksClient(
server_hostname="example.cloud.databricks.com",
http_path="/sql/1.0/warehouses/abc",
auth_provider=AccessTokenAuthProvider("dapi-test"),
ssl_options=None,
port=port,
)
c.open_session(session_configuration=None, catalog=None, schema=None)

assert captured["host"] == "example.cloud.databricks.com"
assert captured["port"] == port


def test_open_session_sends_no_port_kwarg_without_a_port(monkeypatch):
"""An unset ``_port`` sends no ``port`` kwarg, so the default path is unchanged."""
captured = {}

def fake_session(**kw):
captured.update(kw)
return MagicMock(session_id="sess-id")

monkeypatch.setattr(kernel_client._kernel, "Session", fake_session)
c = kernel_client.KernelDatabricksClient(
server_hostname="example.cloud.databricks.com",
http_path="/sql/1.0/warehouses/abc",
auth_provider=AccessTokenAuthProvider("dapi-test"),
ssl_options=None,
)
c.open_session(session_configuration=None, catalog=None, schema=None)

assert "port" not in captured
assert captured["host"] == "example.cloud.databricks.com"


def test_open_session_port_on_a_kernel_without_port_raises_not_supported(
monkeypatch,
):
def fake_session_without_port(host, http_path, *, enable_geospatial_support=False):
raise AssertionError("must not construct a session")

monkeypatch.setattr(kernel_client._kernel, "Session", fake_session_without_port)
c = kernel_client.KernelDatabricksClient(
server_hostname="example.cloud.databricks.com",
http_path="/sql/1.0/warehouses/abc",
auth_provider=AccessTokenAuthProvider("dapi-test"),
ssl_options=None,
port=8443,
)

with pytest.raises(NotSupportedError, match="newer databricks-sql-kernel"):
c.open_session(session_configuration=None, catalog=None, schema=None)


def test_open_session_passes_phase_7_telemetry_kwargs_to_kernel(monkeypatch):
"""Kernel telemetry phase 7 added binding/runtime identity and
telemetry config kwargs to ``databricks_sql_kernel.Session``."""
Expand Down
Loading
Loading