Skip to content

Commit 543777a

Browse files
cathleenyIsaac
andauthored
feat(kernel): honor _port and _connection_uri on use_kernel connections (#1071)
* feat(kernel): honor _port and _connection_uri on use_kernel connections The kernel backend (use_kernel=True) ignored the Thrift-style _port and _connection_uri overrides. Resolve both connector-side onto the kernel's single host and http_path, with the Thrift rules: - _port (1..65535; 0 or None mean the default) folds into server_hostname as host:port. The default 443 adds nothing, IPv6 literals are bracketed, and an embedded port equal to _port is accepted. An empty server_hostname with _port raises ValueError. - _connection_uri (http(s)://host[:port]/path?query) replaces host, port, path and query, and wins over _port. Scheme-less, non-http(s), path-less and credential-bearing URIs raise ValueError. URI-only use works. - With OAuth (U2M, Azure service principal, JWT key file, or M2M client id and secret), a _connection_uri whose origin differs from https://server_hostname raises before a kernel session opens. PAT is not affected. A non-default _port with OAuth is not guarded: the token exchange goes to the same host:port, which is documented. - The SPOG x-databricks-org-id header follows the resolved path. Tests cover the resolver tables, the OAuth origin guard, the SPOG re-derivation, and a real-wheel loopback dial proving the kernel reaches the requested port over TLS for _port and for _connection_uri. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> * fix(kernel): type _kernel_host_and_path http_path as str The helper returned Optional[str] for the resolved path, but KernelDatabricksClient takes a str, so mypy fails in check-types on every supported Python. Session.__init__ already types http_path as str, so this is an annotation-only change with no runtime effect. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> * fix(kernel): match main for default host resolution and PAT OAuth guard A kernel connection without _port or _connection_uri again passes server_hostname through unchanged, so odd hosts no longer raise on the default path. The OAuth origin guard now skips connections the kernel auth bridge routes to PAT: an access_token with no JWT or client-secret M2M credentials, even when auth_type is databricks-oauth. azure-sp-m2m and M2M/JWT stay guarded. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> * fix(kernel): black formatting and OAuth guard follows the auth bridge Wraps the origin-guard condition to the repo's black line length (check-linting). The guard no longer treats a custom credentials_provider as OAuth: the kernel auth bridge rejects that provider with NotSupportedError, so no OAuth origin is involved. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> * fix(kernel): keep credentials and resolved host details out of error messages Error messages that echoed a _connection_uri, server_hostname or the OAuth origin now show only scheme and host[:port] through a redaction helper, so userinfo, path, query and fragment never reach exception text or logs. Adds regression tests that the secret does not appear in the message, and a mocked connect() test that the resolved kernel host and path reach KernelDatabricksClient. Removes a duplicate import in the unit test module. No validation semantics change. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> * fix(kernel): sanitize connection-URI parse errors and wrap long messages urlsplit ran outside the error handling, so a malformed URI whose NFKC-normalized netloc failed raised a ValueError that echoed the raw netloc, password included. The parse is now wrapped and re-raised as a redacted ValueError with from None; a regression row covers it. Long error messages and docstrings are wrapped to the 100-column limit in CONTRIBUTING.md. No validation semantics change. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> * fix(kernel): drop the whole authority from errors when credentials may be present _redact split at the first slash before stripping userinfo, so a password containing a slash left part of the secret in the message. Whenever the raw value contains an @ or a percent-encoded %40, only the scheme is kept. The parse failure is now raised outside the except block, so no chained exception can carry urlsplit's netloc. Regression rows cover an @ after the host, a percent-encoded %40, and passwords containing a slash or a question mark. No validation semantics change. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> * Embedded host port wins over a differing _port on the kernel path A port embedded in server_hostname now wins over a differing _port, with a warning, as on main, where the kernel connected to the embedded port. A falsy _port (None, 0, '', False) means the default, as on Thrift (port or 443). A trailing '/' is trimmed before port handling. A truthy invalid _port still raises, as Thrift fails on it (LocationParseError). Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> * Reject a path, query or fragment host combined with _port; document kernel port rules Check the host for a path, query or fragment before the port is parsed, so 'h.io/path:8443' with _port cannot read as port 8443. Only explicit _port is affected; a host without _port passes through unchanged, as on main. Add Thrift tests pinning that host and _port reach ThriftDatabricksClient unchanged. Update CONNECTION_PARAMETERS.md: _port and _connection_uri are now kernel options, with the embedded-port and falsy rules and the OAuth origin rule. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> * kernel: parse host:port with urllib and check the JWT issuer origin Replace the _HOSTPORT_RE regex, the _port regex and the manual bracketing in the kernel host folding with urllib.parse.urlsplit, int() and an ipaddress pre-check for bare IPv6 literals. The original host string still passes through unchanged unless a port is folded in; folded IPv6 hosts are bracketed. _check_oauth_origin treats an access_token that decodes as a JWT whose issuer is not server_hostname as OAuth. The kernel wraps every provider with the connection host, so such a token would be exchanged at the _connection_uri origin, while Thrift exchanges it at server_hostname. A mismatched origin now raises before any request. PATs and same-host issuers are unaffected. The port-conflict warning is skipped when _port is the default 443, matching Node. Non-default ports still warn on a mismatch. Behavior-table tests in test_session.py pass unchanged. One warning test changed: test_embedded_port_wins_over_differing_explicit_port lost its ('h.io:8443', 443) row, which asserted the 443 warning. That case moved to test_embedded_port_with_default_443_does_not_warn under the new rule. Known differences from bc7c09e: the OAuth origin check now compares the parsed hostname, so a server_hostname such as 'h.io/x' or 'user@h' with a matching _connection_uri origin passes where it was previously refused. The error text for 'h:70000', 'h:abc' and '[::1' is now one generic malformed-or-out-of-range message. 'user:pass@h' with _port is still refused. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> * kernel: skip ip_address for host names on the host:port path _is_bare_ipv6 now returns early unless the text has at least two colons and no leading bracket. ip_address raised a ValueError for every host name and host:port string, which made the folding path about 2x slower than bc7c09e. A bare IPv6 literal always has two or more colons, so behavior is unchanged; the session tests and the realkernel loopback tests pass. Microbenchmark, median us per call (20000 calls x 7 repeats): - bare host, _port 8443: 1.305 base, 1.261 new - host:port, _port 8443: 1.364 base, 1.393 new (+2%) - IPv6 bracketed, _port 8443: 1.340 base, 1.355 new (+1%) - IPv6 bare, _port 8443: 1.413 base, 2.642 new (+87%, the successful ip_address parse) Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> * kernel: drop bare IPv6 support on the host:port path Remove _is_bare_ipv6 and the ipaddress import. Bare IPv6 hosts such as ::1 never worked on the kernel path: the kernel prepends https:// and its URL parser rejects an unbracketed IPv6 literal. IPv6 literals must be bracketed ([::1]). With _port set, urlsplit reads everything after the first colon of a bare IPv6 literal as the port. That text always contains another colon, so the integer parse fails and the existing "malformed IPv6 literal or port" ValueError is raised before any request. This includes _port=443. Without _port the host still passes through unchanged, as on main. Tests: the ("::1", 8443) -> "[::1]:8443" row is removed. ::1 with _port 8443 or 443, and 2001:db8::1 with _port 8443, are now in the reject table. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> * fix(kernel): narrow access_token before the foreign-JWT check mypy (check-types) rejected passing the Optional access_token to _is_foreign_jwt, because bool(access_token) does not narrow its type. Use `access_token and _is_foreign_jwt(...)` inside bool(), which narrows it. The behavior is the same; the session tests pass. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> * fix(kernel): don't echo a non-http(s) prefix in _connection_uri errors _redact kept everything before the first "://" as the scheme. In a scheme-less _connection_uri such as "h.io/sql/x?token=secret&redirect=https://example.com", that prefix is the path and query, so the error message echoed token=secret. The prefix is now kept only when it is http or https; otherwise it is shown as <redacted>. Two regression rows in test_invalid_connection_uri_message_omits_credentials fail without this change. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> * fix(kernel): guard the URI origin when identity_federation_client_id is set With identity_federation_client_id, the kernel bridge forwards the access_token for mandatory workload-identity token exchange at the connection host. _check_oauth_origin routed any access_token that wasn't a foreign-issuer JWT to the PAT exemption, so a mismatched _connection_uri origin could receive that exchange, where Thrift exchanges at server_hostname. Such a token now counts as OAuth for the origin check, so a mismatched origin raises before any request. A plain PAT without a federation client id is unaffected. Also close the connection in test_resolved_kernel_host_and_path_reach_kernel_client, and describe the exchanged-token rule in CONNECTION_PARAMETERS.md. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> * fix(kernel): pass the host through unchanged for _port=443 An explicit _port=443 adds nothing to the kernel host, but it still ran the checks for a folded port, so a host that main sent through as-is was now rejected: a path or query (`h.io/x`, `h.io?x=1`), a bare IPv6 literal (`::1`), userinfo (`user:pw@h`), or an empty host. 443 now returns the host unchanged before those checks, as on main and as the Node driver does. A non-default _port is unchanged. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> * fix(kernel): report an uncomparable server_hostname as an OAuth origin mismatch With OAuth and _connection_uri, the origin guard parsed server_hostname with the _port parser, so a host such as '::1', 'h.io:' or 'user:pass@h.io' raised 'malformed IPv6 literal or port' even though no _port was set. The guard now treats a server_hostname it cannot parse as an origin that cannot match, and raises its own origin-mismatch error. The changelog entry no longer says 'as on main'. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> * refactor(kernel): let the kernel apply _port The kernel now folds _port into the connection host (databricks-sql-kernel #505), so the driver no longer rewrites server_hostname. The session passes server_hostname through unchanged and the parsed _port as the binding's port= kwarg. The driver keeps what is driver-specific: _port parsing (falsy means the default, invalid values raise ValueError), _connection_uri resolution into host, port and path, the OAuth origin guard, and redaction of its own error messages. port= is sent only when a non-default port applies, so the default path sends the same kwargs as before. A wheel without the kwarg raises NotSupportedError instead of silently connecting to port 443. Removed the driver-side folding rules (embedded-port-wins and its warning, path/userinfo/IPv6 checks, _split_host). Kernel InvalidArgument errors now surface as ProgrammingError rather than ValueError. KERNEL_REV is pinned to 22ae6ec250837b38d0e3dc720310d4dcfb81fa98 so the kernel-e2e workflow builds the kernel with port support. This PR needs a kernel release that includes databricks-sql-kernel#505. Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac <no-reply@databricks.com> * fix(kernel): guard a JWT that is foreign to the _connection_uri host The OAuth origin guard judged a JWT's issuer only against server_hostname. The kernel judges it against its connection host, so a token issued by server_hostname with a _connection_uri on another host was treated as a PAT here but exchanged by the kernel at that other host. A token foreign to either host now counts as exchanged, so the mismatched origin is rejected. Added the h.io issuer + other.io URI case. Tests: - The loopback realkernel tests skip when the installed wheel has no port kwarg, and re-raise NotSupportedError instead of swallowing it and timing out. They pass on a wheel built from the kernel PR and skip on the published 1.4.0 wheel. - The old-wheel port test uses a fixed-signature fake Session, so the real signature introspection decides, as in the geospatial test. Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac <no-reply@databricks.com> * fix(kernel): reject a _connection_uri with an empty port urlsplit reads "https://h.io:/sql/x" as having no port, so the URI passed validation and "https://h.io:" went to the kernel. An authority that ends in ":" is now rejected as malformed, like port 0. Covered for a host name and a bracketed IPv6 literal. Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac <no-reply@databricks.com> * docs(changelog): shorten the port entry Keep the user-facing change and its requirement; the detailed rules stay in the connection parameter docs and the PR description. Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac <no-reply@databricks.com> * refactor(kernel): pass _port to the kernel as is The kernel now validates the port and applies it to the host, so the driver drops its own port handling: `_port_or_none` (falsy/string parsing and the 1..65535 check), the 443 drop, and the wheel-capability gate. A set `_port` reaches the kernel's `port=` unchanged; an invalid value raises the kernel's ValueError. `_connection_uri` parsing and the OAuth origin guard are unchanged. KERNEL_REV moves to the kernel PR head (403ef24), and the docs describe the kernel's rules: IPv6 hosts need brackets, and errors never repeat the host. Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac <no-reply@databricks.com> * refactor(kernel): drop the OAuth origin guard and trim _connection_uri handling Remove the OAuth origin check for `_connection_uri` (and its JWT issuer, server-origin and redaction helpers). `_connection_uri` now only splits into host and path, rejecting a non-http(s) scheme, a missing host, or credentials in the URI; the kernel validates the rest. The related tests go too. KERNEL_REV moves to the kernel PR head (7e76a60). Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac <no-reply@databricks.com> * docs(kernel): an invalid _port raises OperationalError The kernel's ValueError for a bad port value reaches the caller through the binding's usual wrapper, which maps non-kernel exceptions to OperationalError. Say so instead of ValueError. Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac <no-reply@databricks.com> * fix(kernel): raise NotSupportedError for _port on a kernel without port A kernel wheel whose Session does not declare `port` rejected the kwarg with a TypeError. Gate it like the other optional kwargs so the error names the fix. Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac <no-reply@databricks.com> * chore(kernel): pin KERNEL_REV to the merged kernel port change databricks-sql-kernel#505 merged as 3b691d2; pin that commit instead of the PR head. Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac <no-reply@databricks.com> * test(kernel): fail the loopback tests clearly when a stub shadows the kernel Match the existing real-wheel guard: if sys.modules holds a fake databricks_sql_kernel, fail with a clear message instead of a listener timeout. Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac <no-reply@databricks.com> * ci(kernel-e2e): run the real-kernel session tests on the source-built wheel The port loopback tests in test_session.py skip on published wheels without `port`. Run them in kernel-e2e, against the wheel built from KERNEL_REV. Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac <no-reply@databricks.com> * fix(kernel): accept a digit-string _port on the kernel path The kernel binding takes only an int, so _port="443" (from an env var or a DSN) raised OperationalError, while Thrift accepts it. Coerce a digit string to the int it names before passing the port on; any other value still goes to the kernel as is, which validates it. Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac <no-reply@databricks.com> --------- Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac <no-reply@databricks.com>
1 parent 75a0d5d commit 543777a

9 files changed

Lines changed: 499 additions & 12 deletions

File tree

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,11 @@ jobs:
351351
- name: Run async reader routing tests
352352
run: $CONNECTOR_VENV_PY -m pytest tests/unit/test_kernel_async_readers.py -m realkernel -v
353353

354+
- name: Run real-kernel session tests (port loopback dials)
355+
# Published wheels without the `port` kwarg skip these, so run them
356+
# against the wheel built from KERNEL_REV.
357+
run: $CONNECTOR_VENV_PY -m pytest tests/unit/test_session.py -m realkernel -v
358+
354359
- name: Run kernel e2e tests
355360
run: poetry run pytest tests/e2e/test_kernel_backend.py -v
356361

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Release History
22

33
# Unreleased
4+
- 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.
45
- 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.
56

67
# 4.10.0 (2026-11-24)

‎CONNECTION_PARAMETERS.md‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,8 +73,8 @@ to change without notice.
7373
| ----------------- | ----- | :----: | :----: | ------------- | ----------------------------------------------------------------------------------------------------------------------- |
7474
| `server_hostname` | `str` | ✅ | ✅ | — (required) | Workspace hostname, e.g. `dbc-12345.cloud.databricks.com`. |
7575
| `http_path` | `str` | ✅ | ✅ | — (required) | Thrift accepts a SQL-warehouse path **or** an all-purpose-cluster path; Kernel requires a warehouse/endpoint path. |
76-
| `_port` | `int` | ✅ | — | `443` | TCP port (advanced). Not threaded to the kernel; it derives host/port from `server_hostname` + `http_path`. |
77-
| `_connection_uri` | `str` | ✅ | — | `None` | Thrift-only internal override of `server_hostname`/`http_path`. No kernel equivalent. |
76+
| `_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. |
77+
| `_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. |
7878
| `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. |
7979
| `user_agent_entry`| `str` | ✅ | ✅ | `None` | Custom tag folded into the composed `User-Agent` on both. (`_user_agent_entry` is a deprecated alias that warns.) |
8080

@@ -213,8 +213,7 @@ are forwarded when supported by the installed kernel binding.
213213
`_retry_dangerous_codes`, `_respect_server_retry_after_header`,
214214
`_retry_max_redirects`, `_enable_v3_retries`.
215215
8. `force_enable_telemetry`.
216-
9. `_port` and `_connection_uri`.
217-
10. `_pool_connections` and `_proxy_auth_method` do not configure the
216+
9. `_pool_connections` and `_proxy_auth_method` do not configure the
218217
kernel-owned network stack.
219218

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

‎KERNEL_REV‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
5c3a909771f749174567af074bfe18c24a335f5c
1+
3b691d2a2c235ef847d61b308c31604979830994

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

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -321,10 +321,12 @@ def __init__(
321321
# toggles, mTLS client cert/key). ``http_headers`` is forwarded
322322
# to the kernel as custom request headers (it carries the
323323
# connector's composed ``User-Agent`` + any caller headers + the
324-
# SPOG ``x-databricks-org-id``). ``http_client`` / ``port`` are
325-
# still accept-and-ignore — the kernel manages its own HTTP
326-
# stack.
324+
# SPOG ``x-databricks-org-id``). ``port`` (the resolved ``_port``,
325+
# or ``None``) is forwarded as the kernel's ``port`` kwarg, which
326+
# the kernel applies to ``server_hostname``. ``http_client`` is
327+
# accept-and-ignore — the kernel manages its own HTTP stack.
327328
self._server_hostname = server_hostname
329+
self._port: Any = kwargs.get("port")
328330
self._http_path = http_path
329331
self._auth_provider = auth_provider
330332
self._ssl_options = ssl_options
@@ -488,6 +490,15 @@ def open_session(
488490
geospatial_kwargs = _kernel_geospatial_kwargs(
489491
self._enable_geospatial_support
490492
)
493+
# The kernel validates the port and applies it to the host; unset sends nothing.
494+
port_kwargs: Dict[str, Any] = {}
495+
if self._port is not None:
496+
if not _kernel_session_accepts_kwarg("port"):
497+
raise NotSupportedError(
498+
"_port requires a newer databricks-sql-kernel wheel "
499+
"that accepts a connection port."
500+
)
501+
port_kwargs["port"] = self._port
491502
max_connections_kwargs: Dict[str, Any] = {}
492503
if _kernel_session_accepts_kwarg("max_connections"):
493504
max_connections_kwargs["max_connections"] = self._max_connections
@@ -536,6 +547,7 @@ def open_session(
536547
**retry_kwargs,
537548
**telemetry_kwargs,
538549
**geospatial_kwargs,
550+
**port_kwargs,
539551
**max_connections_kwargs,
540552
**http_headers_kwargs,
541553
)

‎src/databricks/sql/client.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,10 @@ def __init__(
193193
decision. This is an intentional divergence from the
194194
Thrift/SEA paths, where an explicit ``True`` can still
195195
be suppressed by the feature flag.
196+
197+
Kernel overrides: _port is passed to the kernel, which applies it to
198+
the host. _connection_uri (https://host[:port]/path?query) sets host,
199+
port, path and query, as on Thrift, and wins over _port.
196200
:param enable_geospatial_support: `bool`, optional (default is False)
197201
Kernel backend only. Controls the public representation of
198202
``GEOMETRY`` and ``GEOGRAPHY`` result values. ``True`` returns

‎src/databricks/sql/session.py‎

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import logging
22
import re
33
from functools import cached_property
4+
from urllib.parse import urlsplit
45
from typing import Dict, Tuple, List, Optional, Any, Type, TYPE_CHECKING
56

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

4950

51+
def _kernel_endpoint(
52+
server_hostname: str, http_path: str, kwargs: dict
53+
) -> Tuple[str, str, Any]:
54+
"""Resolve the kernel ``(host, http_path, port)``. ``_connection_uri`` gives the host
55+
(with any port in it) and the path, and wins over ``_port``. Otherwise the arguments
56+
pass through as is; the kernel validates the port and applies it to the host.
57+
"""
58+
uri = kwargs.get("_connection_uri")
59+
if not uri:
60+
port = kwargs.get("_port")
61+
# A digit string (e.g. from an env var or DSN) becomes the int it names, as Thrift
62+
# accepts it. This is type coercion only; any other value reaches the kernel as is.
63+
if isinstance(port, str) and port.strip().isascii() and port.strip().isdigit():
64+
port = int(port)
65+
return server_hostname, http_path, port
66+
parts = urlsplit(uri)
67+
# Credentials in the URI would reach the transport, so they are refused here.
68+
if parts.scheme not in ("http", "https") or not parts.netloc or "@" in parts.netloc:
69+
raise ValueError(
70+
"Invalid _connection_uri: expected http(s)://host[:port]/path with no credentials"
71+
)
72+
path = parts.path + (f"?{parts.query}" if parts.query else "")
73+
return f"{parts.scheme}://{parts.netloc}", path, None
74+
75+
5076
class Session:
5177
def __init__(
5278
self,
@@ -323,9 +349,23 @@ def _create_backend(
323349
"_telemetry_circuit_breaker_enabled"
324350
),
325351
}
352+
kernel_host, kernel_http_path, kernel_port = _kernel_endpoint(
353+
server_hostname, http_path, kwargs
354+
)
355+
if kernel_http_path != http_path:
356+
# A _connection_uri can point at another workspace: re-derive the
357+
# SPOG org-id header from the resolved path (a caller header still wins).
358+
base_headers = [
359+
h for h in all_headers if h not in self._spog_headers.items()
360+
]
361+
self._spog_headers = self._extract_spog_headers(
362+
kernel_http_path, base_headers
363+
)
364+
all_headers = base_headers + list(self._spog_headers.items())
326365
return KernelDatabricksClient(
327-
server_hostname=server_hostname,
328-
http_path=http_path,
366+
server_hostname=kernel_host,
367+
http_path=kernel_http_path,
368+
port=kernel_port,
329369
http_headers=all_headers,
330370
auth_provider=auth_provider,
331371
ssl_options=self.ssl_options,

‎tests/unit/test_kernel_client.py‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -541,6 +541,70 @@ def test_geospatial_option_rejects_non_bool():
541541
kernel_client._kernel_geospatial_kwargs("false")
542542

543543

544+
@pytest.mark.parametrize("port", [8443, 443, 0])
545+
def test_open_session_passes_port_to_kernel_as_port_kwarg(monkeypatch, port):
546+
"""A set ``_port`` reaches the binding as ``port=`` as is. The host is passed
547+
unchanged: the kernel validates the port and applies it, not the driver."""
548+
captured = {}
549+
550+
def fake_session(**kw):
551+
captured.update(kw)
552+
return MagicMock(session_id="sess-id")
553+
554+
monkeypatch.setattr(kernel_client._kernel, "Session", fake_session)
555+
c = kernel_client.KernelDatabricksClient(
556+
server_hostname="example.cloud.databricks.com",
557+
http_path="/sql/1.0/warehouses/abc",
558+
auth_provider=AccessTokenAuthProvider("dapi-test"),
559+
ssl_options=None,
560+
port=port,
561+
)
562+
c.open_session(session_configuration=None, catalog=None, schema=None)
563+
564+
assert captured["host"] == "example.cloud.databricks.com"
565+
assert captured["port"] == port
566+
567+
568+
def test_open_session_sends_no_port_kwarg_without_a_port(monkeypatch):
569+
"""An unset ``_port`` sends no ``port`` kwarg, so the default path is unchanged."""
570+
captured = {}
571+
572+
def fake_session(**kw):
573+
captured.update(kw)
574+
return MagicMock(session_id="sess-id")
575+
576+
monkeypatch.setattr(kernel_client._kernel, "Session", fake_session)
577+
c = kernel_client.KernelDatabricksClient(
578+
server_hostname="example.cloud.databricks.com",
579+
http_path="/sql/1.0/warehouses/abc",
580+
auth_provider=AccessTokenAuthProvider("dapi-test"),
581+
ssl_options=None,
582+
)
583+
c.open_session(session_configuration=None, catalog=None, schema=None)
584+
585+
assert "port" not in captured
586+
assert captured["host"] == "example.cloud.databricks.com"
587+
588+
589+
def test_open_session_port_on_a_kernel_without_port_raises_not_supported(
590+
monkeypatch,
591+
):
592+
def fake_session_without_port(host, http_path, *, enable_geospatial_support=False):
593+
raise AssertionError("must not construct a session")
594+
595+
monkeypatch.setattr(kernel_client._kernel, "Session", fake_session_without_port)
596+
c = kernel_client.KernelDatabricksClient(
597+
server_hostname="example.cloud.databricks.com",
598+
http_path="/sql/1.0/warehouses/abc",
599+
auth_provider=AccessTokenAuthProvider("dapi-test"),
600+
ssl_options=None,
601+
port=8443,
602+
)
603+
604+
with pytest.raises(NotSupportedError, match="newer databricks-sql-kernel"):
605+
c.open_session(session_configuration=None, catalog=None, schema=None)
606+
607+
544608
def test_open_session_passes_phase_7_telemetry_kwargs_to_kernel(monkeypatch):
545609
"""Kernel telemetry phase 7 added binding/runtime identity and
546610
telemetry config kwargs to ``databricks_sql_kernel.Session``."""

0 commit comments

Comments
 (0)