Skip to content

Commit bad2b25

Browse files
cathleenyIsaac
andcommitted
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>
1 parent 7f13a63 commit bad2b25

6 files changed

Lines changed: 20 additions & 128 deletions

File tree

‎CONNECTION_PARAMETERS.md‎

Lines changed: 1 addition & 1 deletion
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 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. |
76+
| `_port` | `int` | ✅ | ✅ | `443` | TCP port (advanced). On Kernel it is passed to the kernel as is, 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 `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. |
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.) |

‎KERNEL_REV‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
22ae6ec250837b38d0e3dc720310d4dcfb81fa98
1+
403ef247a71c3e49297d7cb7fc97211db942d200

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

Lines changed: 3 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -238,22 +238,6 @@ 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-
257241
def _validate_telemetry_flush_interval_ms(value: Any) -> None:
258242
# PyO3 would accept True as 1ms and report other bad values without
259243
# naming the option, so reject them before the kernel sees them.
@@ -342,7 +326,7 @@ def __init__(
342326
# the kernel applies to ``server_hostname``. ``http_client`` is
343327
# accept-and-ignore — the kernel manages its own HTTP stack.
344328
self._server_hostname = server_hostname
345-
self._port: Optional[int] = kwargs.get("port")
329+
self._port: Any = kwargs.get("port")
346330
self._http_path = http_path
347331
self._auth_provider = auth_provider
348332
self._ssl_options = ssl_options
@@ -506,7 +490,8 @@ def open_session(
506490
geospatial_kwargs = _kernel_geospatial_kwargs(
507491
self._enable_geospatial_support
508492
)
509-
port_kwargs = _kernel_port_kwargs(self._port)
493+
# The kernel validates the port and applies it to the host; unset sends nothing.
494+
port_kwargs = {} if self._port is None else {"port": self._port}
510495
max_connections_kwargs: Dict[str, Any] = {}
511496
if _kernel_session_accepts_kwarg("max_connections"):
512497
max_connections_kwargs["max_connections"] = self._max_connections

‎src/databricks/sql/session.py‎

Lines changed: 4 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -53,25 +53,6 @@ def __getattr__(name: str) -> Any:
5353
_OAUTH_AUTH_TYPES = ("databricks-oauth", "azure-oauth", "azure-sp-m2m")
5454

5555

56-
def _port_or_none(value: Any) -> Optional[int]:
57-
"""Validate ``_port``. A falsy value (None, 0, '', False) means the default, as on
58-
Thrift (``port or 443``); a truthy value must be an integer between 1 and 65535.
59-
"""
60-
if not value or (isinstance(value, str) and not value.strip()):
61-
return None
62-
text = (
63-
str(value).strip()
64-
if isinstance(value, (int, str)) and not isinstance(value, bool)
65-
else ""
66-
)
67-
# isdigit with isascii rejects signs, whitespace and underscores that int() would accept.
68-
if not (text.isascii() and text.isdigit()) or int(text) > 65535:
69-
raise ValueError(
70-
f"Invalid _port {value!r}: expected an integer between 1 and 65535"
71-
)
72-
return int(text) or None
73-
74-
7556
def _redact(value: str) -> str:
7657
"""Keep only scheme and host[:port] of a URI or host string for an error message.
7758
@@ -132,17 +113,16 @@ def _uri_host_and_path(uri: str) -> Tuple[str, str]:
132113

133114
def _kernel_endpoint(
134115
server_hostname: str, http_path: str, kwargs: dict
135-
) -> Tuple[str, str, Optional[int]]:
116+
) -> Tuple[str, str, Any]:
136117
"""Resolve the kernel ``(host, http_path, port)``. ``_connection_uri`` gives the host
137118
(with any port in it) and the path, and wins over ``_port``, so no port is passed.
138-
Otherwise ``server_hostname`` and ``http_path`` pass through and ``_port`` is passed as
139-
the kernel's ``port``, which applies it. ``None`` and the default 443 pass no port.
119+
Otherwise ``server_hostname``, ``http_path`` and ``_port`` pass through as is: the
120+
kernel validates the port and applies it to the host.
140121
"""
141122
if kwargs.get("_connection_uri"):
142123
host, path = _uri_host_and_path(kwargs["_connection_uri"])
143124
return host, path, None
144-
port = _port_or_none(kwargs.get("_port"))
145-
return server_hostname, http_path, None if port == 443 else port
125+
return server_hostname, http_path, kwargs.get("_port")
146126

147127

148128
def _is_foreign_jwt(access_token: str, server_hostname: str) -> bool:

‎tests/unit/test_kernel_client.py‎

Lines changed: 5 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -541,10 +541,10 @@ def test_geospatial_option_rejects_non_bool():
541541
kernel_client._kernel_geospatial_kwargs("false")
542542

543543

544-
@pytest.mark.parametrize("port", [1, 8443, 65535])
544+
@pytest.mark.parametrize("port", [8443, 443, 0])
545545
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."""
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."""
548548
captured = {}
549549

550550
def fake_session(**kw):
@@ -565,10 +565,8 @@ def fake_session(**kw):
565565
assert captured["port"] == port
566566

567567

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."""
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."""
572570
captured = {}
573571

574572
def fake_session(**kw):
@@ -581,56 +579,13 @@ def fake_session(**kw):
581579
http_path="/sql/1.0/warehouses/abc",
582580
auth_provider=AccessTokenAuthProvider("dapi-test"),
583581
ssl_options=None,
584-
port=port,
585582
)
586583
c.open_session(session_configuration=None, catalog=None, schema=None)
587584

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

591588

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. The real signature introspection decides."""
599-
calls = []
600-
601-
def fake_session_without_port(
602-
host,
603-
http_path,
604-
*,
605-
catalog=None,
606-
schema=None,
607-
session_conf=None,
608-
complex_types_as_json=False,
609-
intervals_as_string=False,
610-
request_timeout_secs=None,
611-
auth_type=None,
612-
access_token=None,
613-
enable_geospatial_support=False,
614-
):
615-
calls.append(host)
616-
sess = MagicMock()
617-
sess.session_id = "sess-id"
618-
return sess
619-
620-
monkeypatch.setattr(kernel_client._kernel, "Session", fake_session_without_port)
621-
c = kernel_client.KernelDatabricksClient(
622-
server_hostname="example.cloud.databricks.com",
623-
http_path="/sql/1.0/warehouses/abc",
624-
auth_provider=AccessTokenAuthProvider("dapi-test"),
625-
ssl_options=None,
626-
port=8443,
627-
)
628-
629-
with pytest.raises(NotSupportedError, match="_port requires a newer"):
630-
c.open_session(session_configuration=None, catalog=None, schema=None)
631-
assert calls == []
632-
633-
634589
def test_open_session_passes_phase_7_telemetry_kwargs_to_kernel(monkeypatch):
635590
"""Kernel telemetry phase 7 added binding/runtime identity and
636591
telemetry config kwargs to ``databricks_sql_kernel.Session``."""

‎tests/unit/test_session.py‎

Lines changed: 6 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1205,26 +1205,11 @@ def test_pat_recovery_does_not_inject_auth_type(self, mock_thrift):
12051205
@pytest.mark.parametrize(
12061206
"server, kwargs, expected_port",
12071207
[
1208-
# A non-default _port is passed as port=; server_hostname is passed unchanged.
1208+
# _port and server_hostname reach the kernel as is; the kernel validates both.
12091209
("h.io", {"_port": 8443}, 8443),
1210-
("h.io", {"_port": "8443"}, 8443),
1211-
("h.io", {"_port": 1}, 1),
1212-
("h.io", {"_port": 65535}, 65535),
1213-
("[::1]", {"_port": 8443}, 8443),
1214-
("h.io:8443", {"_port": 8443}, 8443),
1215-
("h.io/x", {"_port": 8443}, 8443),
1216-
("", {"_port": 8443}, 8443),
1217-
# Unset, falsy and the default 443 pass no port, so the host is untouched.
1210+
("h.io", {"_port": 443}, 443),
1211+
("h.io:8443", {"_port": "bad"}, "bad"),
12181212
("h.io", {}, None),
1219-
("h.io", {"_port": None}, None),
1220-
("h.io", {"_port": ""}, None),
1221-
("h.io", {"_port": " "}, None),
1222-
("h.io", {"_port": False}, None),
1223-
("h.io", {"_port": 0}, None),
1224-
("h.io", {"_port": "0"}, None),
1225-
("h.io", {"_port": 443}, None),
1226-
("h.io", {"_port": "443"}, None),
1227-
("h.io:0", {}, None),
12281213
],
12291214
)
12301215
def test_kernel_endpoint_passes_host_unchanged_and_port_separately(
@@ -1271,12 +1256,6 @@ def test_connection_uri_only_resolves_host_and_path():
12711256
@pytest.mark.parametrize(
12721257
"kwargs, message",
12731258
[
1274-
# The driver parses _port as an int in 1..65535 (falsy means the default).
1275-
({"_port": -1}, "Invalid _port"),
1276-
({"_port": 65536}, "Invalid _port"),
1277-
({"_port": "abc"}, "Invalid _port"),
1278-
({"_port": True}, "Invalid _port"),
1279-
({"_port": 8443.5}, "Invalid _port"),
12801259
# _connection_uri must be http(s) with a host and a warehouse path, no credentials.
12811260
({"_connection_uri": "d.io/sql/x"}, "Invalid _connection_uri"),
12821261
({"_connection_uri": "ftp://h.io/sql/x"}, "Invalid _connection_uri"),
@@ -1541,23 +1520,16 @@ def test_oauth_origin_message_omits_uri_query():
15411520
@pytest.mark.parametrize(
15421521
"conn_kwargs, expected_host, expected_path, expected_port",
15431522
[
1544-
# _port reaches the kernel client as port=; server_hostname is unchanged.
1523+
# _port reaches the kernel client as is; server_hostname is unchanged.
15451524
(
15461525
{"server_hostname": "h.io", "http_path": _P, "_port": 8443},
15471526
"h.io",
15481527
_P,
15491528
8443,
15501529
),
1551-
(
1552-
{"server_hostname": "h.io", "http_path": _P, "_port": "8443"},
1553-
"h.io",
1554-
_P,
1555-
8443,
1556-
),
1557-
# Unset, falsy and 443 send no port.
1530+
({"server_hostname": "h.io", "http_path": _P, "_port": 443}, "h.io", _P, 443),
1531+
# Unset sends no port.
15581532
({"server_hostname": "h.io", "http_path": _P}, "h.io", _P, None),
1559-
({"server_hostname": "h.io", "http_path": _P, "_port": 443}, "h.io", _P, None),
1560-
({"server_hostname": "h.io", "http_path": _P, "_port": 0}, "h.io", _P, None),
15611533
# _connection_uri supplies the host (with its port) and the path; no port.
15621534
(
15631535
{

0 commit comments

Comments
 (0)