Skip to content

Commit 12ed5dc

Browse files
cathleenyIsaac
andcommitted
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>
1 parent 233f2b5 commit 12ed5dc

7 files changed

Lines changed: 239 additions & 275 deletions

File tree

‎CHANGELOG.md‎

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

33
# Unreleased
4-
- Honor `_port` and `_connection_uri` on kernel connections (`use_kernel=True`), as Thrift does. `_port` sends the connection to that port (default 443 adds nothing); `_connection_uri` (`http(s)://host[:port]/path?query`) sets host, port, path and query and wins over `_port`; URI-only connections work. A port embedded in `server_hostname` wins over a differing `_port`, with a warning, as it did before. Invalid ports, an empty `server_hostname` with `_port`, and URIs without a scheme or path raise `ValueError`. With OAuth, a `_connection_uri` origin that differs from `server_hostname` raises. With OAuth and a non-default `_port`, the token exchange goes to the same host:port, unlike Thrift (documented, not guarded).
4+
- Honor `_port` and `_connection_uri` on kernel connections (`use_kernel=True`), as Thrift does. The kernel applies `_port`: a port other than 443 (or 80 for an `http://` host) makes the connection use `scheme://host:port`, bare IPv6 hosts are bracketed, and `0`, unset or `443` change nothing. A port embedded in `server_hostname` wins over a differing `_port`, with a warning. For a non-default `_port`, the kernel rejects credentials, a path, query or fragment in the host, an empty host, and a bad embedded port with `InvalidArgument`, which surfaces as `ProgrammingError`. `_connection_uri` (`http(s)://host[:port]/path?query`) sets host, port, path and query and wins over `_port`; URI-only connections work. Invalid `_port` values and malformed URIs raise `ValueError`. With OAuth, a `_connection_uri` origin that differs from `server_hostname` raises. With OAuth and a non-default `_port`, the token exchange goes to the same host:port, unlike Thrift (documented, not guarded). This needs a databricks-sql-kernel release that includes databricks-sql-kernel#505.
55
- Honor `max_download_threads` on kernel connections, with a default download window of 16 and explicit chunk-setting overrides. Invalid values raise `ValueError` when connecting with `use_kernel=True`.
66
- Fix the kernel backend ignoring `use_cloud_fetch=False`, so complete results can be fetched without cloud-storage downloads.
77
- Fix inline parameters (`use_inline_params=True`) so a sequence directly after `IN` renders as a list again: `x IN %(ids)s` renders as `x IN (1,2,3)` instead of `x IN ARRAY(1,2,3)`, which Spark rejects. Inside the list, tuples render as rows for a multi-column `IN`, and a `set` or `frozenset` is accepted again. Sequences anywhere else still render as `ARRAY(...)` ([#629](https://github.com/databricks/databricks-sql-python/issues/629))

‎CONNECTION_PARAMETERS.md‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ 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). On Kernel a falsy value means the default, and a port embedded in `server_hostname` wins over a differing `_port` (with a warning). |
76+
| `_port` | `int` | ✅ | ✅ | `443` | TCP port (advanced). On Kernel the kernel applies it: a port other than 443 makes the connection use `host:port` (bare IPv6 is bracketed); `0`, unset and `443` change nothing; a port embedded in `server_hostname` wins over a differing `_port` (with a warning). Needs a databricks-sql-kernel release that includes databricks-sql-kernel#505. |
7777
| `_connection_uri` | `str` | ✅ | ✅ | `None` | Overrides `server_hostname`, `_port` and `http_path` on both, and wins over `_port`. On Kernel with OAuth, the URI origin must match `server_hostname`, and OAuth uses the same host:port as the connection (Thrift keeps OAuth on the bare host). An `access_token` that is exchanged counts as OAuth here: a JWT from an issuer other than `server_hostname`, or any token with `identity_federation_client_id`. |
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.) |
@@ -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-
0b5d0edfed32c0745d5abc2468fc3070e2eb2a17
1+
22ae6ec250837b38d0e3dc720310d4dcfb81fa98

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

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,22 @@ def _kernel_geospatial_kwargs(value: bool) -> Dict[str, bool]:
238238
return {"enable_geospatial_support": value}
239239

240240

241+
def _kernel_port_kwargs(port: Optional[int]) -> Dict[str, int]:
242+
"""Build the kernel ``port`` kwarg. Only a port that applies is passed: unset, 0 and the
243+
default 443 send nothing, so the default path sends the same kwargs as before. The kernel
244+
applies the port to ``host``. A wheel without the kwarg raises rather than silently
245+
connecting to the default port.
246+
"""
247+
if not port or port == 443:
248+
return {}
249+
if not _kernel_session_accepts_kwarg("port"):
250+
raise NotSupportedError(
251+
"_port requires a newer databricks-sql-kernel wheel that exposes the "
252+
"port kwarg."
253+
)
254+
return {"port": port}
255+
256+
241257
def _validate_telemetry_flush_interval_ms(value: Any) -> None:
242258
# PyO3 would accept True as 1ms and report other bad values without
243259
# naming the option, so reject them before the kernel sees them.
@@ -321,10 +337,12 @@ def __init__(
321337
# toggles, mTLS client cert/key). ``http_headers`` is forwarded
322338
# to the kernel as custom request headers (it carries the
323339
# 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.
340+
# SPOG ``x-databricks-org-id``). ``port`` (the resolved ``_port``,
341+
# or ``None``) is forwarded as the kernel's ``port`` kwarg, which
342+
# the kernel applies to ``server_hostname``. ``http_client`` is
343+
# accept-and-ignore — the kernel manages its own HTTP stack.
327344
self._server_hostname = server_hostname
345+
self._port: Optional[int] = kwargs.get("port")
328346
self._http_path = http_path
329347
self._auth_provider = auth_provider
330348
self._ssl_options = ssl_options
@@ -488,6 +506,7 @@ def open_session(
488506
geospatial_kwargs = _kernel_geospatial_kwargs(
489507
self._enable_geospatial_support
490508
)
509+
port_kwargs = _kernel_port_kwargs(self._port)
491510
max_connections_kwargs: Dict[str, Any] = {}
492511
if _kernel_session_accepts_kwarg("max_connections"):
493512
max_connections_kwargs["max_connections"] = self._max_connections
@@ -536,6 +555,7 @@ def open_session(
536555
**retry_kwargs,
537556
**telemetry_kwargs,
538557
**geospatial_kwargs,
558+
**port_kwargs,
539559
**max_connections_kwargs,
540560
**http_headers_kwargs,
541561
)

‎src/databricks/sql/session.py‎

Lines changed: 31 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -97,42 +97,6 @@ def _redact(value: str) -> str:
9797
return f"{scheme}{sep}{host}"
9898

9999

100-
def _split_host(host: str) -> Tuple[str, str, Optional[int]]:
101-
"""Split ``[scheme://]name[:port]`` into ``(prefix, name, port)``. ``name`` keeps the
102-
input's case and any userinfo. IPv6 literals must be bracketed: urlsplit reads a bare
103-
``::1`` as a malformed port, so it is rejected.
104-
"""
105-
prefix, sep, rest = host.rstrip("/").rpartition("://")
106-
prefix += sep
107-
# urlsplit reads a trailing ':' as an empty port; with an explicit _port that is an error.
108-
if rest.endswith(":"):
109-
raise ValueError(
110-
f"Invalid server_hostname {_redact(host)!r}: malformed IPv6 literal or port"
111-
)
112-
try:
113-
parts = urlsplit(f"//{rest}")
114-
port = parts.port
115-
except ValueError:
116-
# ``from None`` drops the urlsplit exception, whose text can quote the raw netloc.
117-
raise ValueError(
118-
f"Invalid server_hostname {_redact(host)!r}: malformed IPv6 literal or port; "
119-
"a port must be 1-65535"
120-
) from None
121-
if "@" in parts.netloc and parts.password is not None:
122-
# A colon before '@' is userinfo, not a port, but a credential-bearing host is
123-
# still refused when a port is requested (as on main), so it is never folded.
124-
raise ValueError(
125-
f"Invalid server_hostname {_redact(host)!r}: malformed IPv6 literal or port"
126-
)
127-
if port is None:
128-
return prefix, parts.netloc, None
129-
if not 1 <= port <= 65535:
130-
raise ValueError(
131-
f"Invalid server_hostname {_redact(host)!r}: port {port} is out of range"
132-
)
133-
return prefix, parts.netloc.rpartition(":")[0], port
134-
135-
136100
def _uri_host_and_path(uri: str) -> Tuple[str, str]:
137101
"""Split a ``_connection_uri`` into the kernel host (scheme, authority) and path."""
138102
try:
@@ -164,47 +128,19 @@ def _uri_host_and_path(uri: str) -> Tuple[str, str]:
164128
)
165129

166130

167-
def _kernel_host_and_path(
131+
def _kernel_endpoint(
168132
server_hostname: str, http_path: str, kwargs: dict
169-
) -> Tuple[str, str]:
170-
"""Resolve the kernel ``(host, http_path)``. ``_connection_uri`` replaces both and wins over
171-
``_port``; ``_port`` folds into the host as ``host:port`` (default 443 adds nothing).
133+
) -> Tuple[str, str, Optional[int]]:
134+
"""Resolve the kernel ``(host, http_path, port)``. ``_connection_uri`` gives the host
135+
(with any port in it) and the path, and wins over ``_port``, so no port is passed.
136+
Otherwise ``server_hostname`` and ``http_path`` pass through and ``_port`` is passed as
137+
the kernel's ``port``, which applies it. ``None`` and the default 443 pass no port.
172138
"""
173139
if kwargs.get("_connection_uri"):
174-
return _uri_host_and_path(kwargs["_connection_uri"])
140+
host, path = _uri_host_and_path(kwargs["_connection_uri"])
141+
return host, path, None
175142
port = _port_or_none(kwargs.get("_port"))
176-
# The default 443 adds nothing, so the host is passed through unchanged, as on main,
177-
# before any of the checks below (a path, userinfo or bare IPv6 host keeps working).
178-
if port is None or port == 443:
179-
return server_hostname, http_path
180-
if not server_hostname:
181-
raise ValueError(
182-
"server_hostname is required on use_kernel=True when _port is set "
183-
"(or pass _connection_uri, which carries its own host)"
184-
)
185-
# Checked before the port is parsed: 'h.io/path:8443' would otherwise read as host
186-
# 'h.io/path' with port 8443. Only the text after any scheme is checked.
187-
authority = server_hostname.rstrip("/").rpartition("://")[2]
188-
if any(c in authority for c in "/?#"):
189-
raise ValueError(
190-
f"Invalid server_hostname {_redact(server_hostname)!r}: a path, query or "
191-
"fragment cannot be combined with _port; put the port in server_hostname"
192-
)
193-
prefix, name, embedded = _split_host(server_hostname)
194-
if embedded is not None:
195-
# A port embedded in server_hostname always wins, as on main (the kernel
196-
# connected to it); a differing _port is ignored with a warning, not an error.
197-
if embedded != port:
198-
logger.warning(
199-
"server_hostname %s carries port %d, which differs from _port=%d; "
200-
"connecting to port %d. Set the port in one place only.",
201-
_redact(server_hostname),
202-
embedded,
203-
port,
204-
embedded,
205-
)
206-
return server_hostname, http_path
207-
return f"{prefix}{name}:{port}", http_path
143+
return server_hostname, http_path, None if port == 443 else port
208144

209145

210146
def _is_foreign_jwt(access_token: str, server_hostname: str) -> bool:
@@ -219,6 +155,25 @@ def _is_foreign_jwt(access_token: str, server_hostname: str) -> bool:
219155
return not is_same_host(issuer, normalize_host_with_protocol(server_hostname))
220156

221157

158+
def _server_origin(server_hostname: str) -> Tuple[str, Optional[int]]:
159+
"""Host and port of ``server_hostname`` for the OAuth origin check. A value with no
160+
comparable origin (credentials, a bare IPv6 literal, an empty or out-of-range port)
161+
returns ``("", None)``, so it never matches and is reported as an origin mismatch.
162+
"""
163+
netloc = server_hostname.rstrip("/").rpartition("://")[2]
164+
# urlsplit reads a trailing ':' as an empty port, which has no origin.
165+
if netloc.endswith(":"):
166+
return "", None
167+
try:
168+
parts = urlsplit(f"//{netloc}")
169+
port = parts.port
170+
except ValueError:
171+
return "", None
172+
if port == 0 or ("@" in parts.netloc and parts.password is not None):
173+
return "", None
174+
return parts.hostname or "", port
175+
176+
222177
def _check_oauth_origin(server_hostname: str, kernel_host: str, kwargs: dict) -> None:
223178
"""AC-P4: with OAuth, a ``_connection_uri`` origin must equal ``https://server_hostname``.
224179
Thrift keeps OAuth on server_hostname; the kernel uses one host for API and token calls.
@@ -254,14 +209,7 @@ def _check_oauth_origin(server_hostname: str, kernel_host: str, kwargs: dict) ->
254209
)
255210
if routed_to_pat or not oauth:
256211
return
257-
try:
258-
_, name, port = _split_host(server_hostname)
259-
server_host = urlsplit(f"//{name}").hostname or ""
260-
except ValueError:
261-
# A server_hostname with no comparable origin (a bare IPv6 literal, an empty port,
262-
# credentials) cannot match the URI origin, so it is reported as an origin mismatch
263-
# rather than as a malformed host.
264-
server_host, port = "", None
212+
server_host, port = _server_origin(server_hostname)
265213
uri = urlsplit(kernel_host)
266214
if (uri.scheme, uri.hostname or "", uri.port or 443) != (
267215
"https",
@@ -552,7 +500,7 @@ def _create_backend(
552500
"_telemetry_circuit_breaker_enabled"
553501
),
554502
}
555-
kernel_host, kernel_http_path = _kernel_host_and_path(
503+
kernel_host, kernel_http_path, kernel_port = _kernel_endpoint(
556504
server_hostname, http_path, kwargs
557505
)
558506
_check_oauth_origin(server_hostname, kernel_host, kwargs)
@@ -569,6 +517,7 @@ def _create_backend(
569517
return KernelDatabricksClient(
570518
server_hostname=kernel_host,
571519
http_path=kernel_http_path,
520+
port=kernel_port,
572521
http_headers=all_headers,
573522
auth_provider=auth_provider,
574523
ssl_options=self.ssl_options,

‎tests/unit/test_kernel_client.py‎

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

543543

544+
@pytest.mark.parametrize("port", [1, 8443, 65535])
545+
def test_open_session_passes_port_to_kernel_as_port_kwarg(monkeypatch, port):
546+
"""A resolved ``_port`` reaches the binding as ``port=``. The host is passed
547+
unchanged: the kernel applies the port, 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+
@pytest.mark.parametrize("port", [None, 443])
569+
def test_open_session_sends_no_port_kwarg_when_no_port_applies(monkeypatch, port):
570+
"""Unset (``None``) and the default 443 send no ``port`` kwarg, so the default path
571+
is unchanged for wheels that predate the kwarg."""
572+
captured = {}
573+
574+
def fake_session(**kw):
575+
captured.update(kw)
576+
return MagicMock(session_id="sess-id")
577+
578+
monkeypatch.setattr(kernel_client._kernel, "Session", fake_session)
579+
c = kernel_client.KernelDatabricksClient(
580+
server_hostname="example.cloud.databricks.com",
581+
http_path="/sql/1.0/warehouses/abc",
582+
auth_provider=AccessTokenAuthProvider("dapi-test"),
583+
ssl_options=None,
584+
port=port,
585+
)
586+
c.open_session(session_configuration=None, catalog=None, schema=None)
587+
588+
assert "port" not in captured
589+
assert captured["host"] == "example.cloud.databricks.com"
590+
591+
592+
def test_port_kwargs_are_empty_without_a_port():
593+
assert kernel_client._kernel_port_kwargs(None) == {}
594+
595+
596+
def test_port_requires_kernel_wheel_that_accepts_port(monkeypatch):
597+
"""A wheel whose fixed ``Session`` signature has no ``port`` raises instead of
598+
connecting to the default port."""
599+
fake_session = MagicMock()
600+
monkeypatch.setattr(
601+
kernel_client, "_kernel_session_accepts_kwarg", lambda name: name != "port"
602+
)
603+
monkeypatch.setattr(kernel_client._kernel, "Session", fake_session)
604+
c = kernel_client.KernelDatabricksClient(
605+
server_hostname="example.cloud.databricks.com",
606+
http_path="/sql/1.0/warehouses/abc",
607+
auth_provider=AccessTokenAuthProvider("dapi-test"),
608+
ssl_options=None,
609+
port=8443,
610+
)
611+
612+
with pytest.raises(NotSupportedError, match="newer databricks-sql-kernel"):
613+
c.open_session(session_configuration=None, catalog=None, schema=None)
614+
fake_session.assert_not_called()
615+
616+
544617
def test_open_session_passes_phase_7_telemetry_kwargs_to_kernel(monkeypatch):
545618
"""Kernel telemetry phase 7 added binding/runtime identity and
546619
telemetry config kwargs to ``databricks_sql_kernel.Session``."""

0 commit comments

Comments
 (0)