Skip to content

Commit 1980bb0

Browse files
committed
Merge remote-tracking branch 'upstream/main' into allow-dateutil-3-and-4
# Conflicts: # CHANGELOG.md
2 parents 9d5bf40 + 543777a commit 1980bb0

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
- Allow python-dateutil 3.x and 4.x (the dependency was capped at `<3`).
56
- 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.
67

‎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)