Skip to content

Commit 07da392

Browse files
vuanhphungIsaac
andcommitted
perf: don't import requests and oauthlib in connect()
common/http.py imported requests, urllib3 and the retry policy without using them, auth/common.py imported the retry policy without using it, and auth/authenticators.py imported the OAuth client (oauthlib, jwt) at module load for two code paths that need it. Every connect() paid for these in its first import. Drop the unused imports and import the OAuth classes where they are used. Co-authored-by: Isaac <no-reply@databricks.com> Signed-off-by: Vu Anh Phung <vu.phung@databricks.com>
1 parent 0c1b9e8 commit 07da392

5 files changed

Lines changed: 79 additions & 16 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
- Fix the kernel backend ignoring `use_cloud_fetch=False`, so complete results can be fetched without cloud-storage downloads.
55
- 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))
66
- Speed up Thrift response handling: read replies in 1 MiB chunks and decode them with Thrift's C-accelerated protocol, and stop stringifying every request/response for the default no-op debug logger. Wide result schemas, metadata calls with many rows, and inline Arrow results benefit most.
7+
- Speed up the first `connect()` in a process by not importing `requests` and the OAuth client libraries until an auth flow that uses them runs.
78

89
# 4.9.0 (2026-11-04)
910
- Upgrade Databricks SQL Kernel to 1.4.0, which keeps Lakehouse Real-Time session affinity and flushes shared telemetry only after the final session closes.

‎src/databricks/sql/auth/authenticators.py‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
import abc
22
import logging
3-
from typing import Callable, Dict, List
3+
from typing import Callable, Dict, List, TYPE_CHECKING
44
from databricks.sql.common.http import HttpHeader
5-
from databricks.sql.auth.oauth import (
6-
OAuthManager,
7-
RefreshableTokenSource,
8-
ClientCredentialsTokenSource,
9-
)
105
from databricks.sql.auth.endpoint import get_oauth_endpoints
6+
7+
if TYPE_CHECKING:
8+
from databricks.sql.auth.oauth import RefreshableTokenSource
119
from databricks.sql.auth.common import (
1210
AuthType,
1311
get_effective_azure_login_app_id,
@@ -74,6 +72,8 @@ def __init__(
7472
# Convert to the corresponding scopes in the corresponding IdP
7573
cloud_scopes = idp_endpoint.get_scopes_mapping(scopes)
7674

75+
from databricks.sql.auth.oauth import OAuthManager
76+
7777
self.oauth_manager = OAuthManager(
7878
port_range=redirect_port_range,
7979
client_id=client_id,
@@ -204,7 +204,9 @@ def __init__(
204204
def auth_type(self) -> str:
205205
return AuthType.AZURE_SP_M2M.value
206206

207-
def get_token_source(self, resource: str) -> RefreshableTokenSource:
207+
def get_token_source(self, resource: str) -> "RefreshableTokenSource":
208+
from databricks.sql.auth.oauth import ClientCredentialsTokenSource
209+
208210
return ClientCredentialsTokenSource(
209211
token_url=f"{self.AZURE_AAD_ENDPOINT}/{self.azure_tenant_id}/{self.AZURE_TOKEN_ENDPOINT}",
210212
client_id=self.azure_client_id,

‎src/databricks/sql/auth/common.py‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
import logging
33
from typing import Optional, List
44
from urllib.parse import urlparse
5-
from databricks.sql.auth.retry import DatabricksRetryPolicy
65
from databricks.sql.common.http import HttpMethod
76

87
logger = logging.getLogger(__name__)

‎src/databricks/sql/common/http.py‎

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,6 @@
1-
import requests
2-
from requests.adapters import HTTPAdapter
3-
from urllib3.util.retry import Retry
41
from enum import Enum
5-
import threading
62
from dataclasses import dataclass
7-
from contextlib import contextmanager
8-
from typing import Generator, Optional
93
import logging
10-
from requests.adapters import HTTPAdapter
11-
from databricks.sql.auth.retry import DatabricksRetryPolicy, CommandType
124

135
logger = logging.getLogger(__name__)
146

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
"""Importing the connector must not import requests or the OAuth client libraries.
2+
3+
They are only needed by the auth flows and HTTP paths that use them. Each check runs
4+
in a fresh interpreter because ``sys.modules`` is process-global.
5+
"""
6+
7+
import subprocess
8+
import sys
9+
import textwrap
10+
11+
import pytest
12+
13+
# Sentinel exit codes, distinct from the 1 of an uncaught exception.
14+
_CLEAN, _LOADED, _IMPORT_FAILED = 10, 11, 12
15+
16+
MODULES = [
17+
"databricks.sql",
18+
"databricks.sql.client",
19+
"databricks.sql.session",
20+
"databricks.sql.auth.authenticators",
21+
"databricks.sql.common.http",
22+
]
23+
UNWANTED = ["requests", "oauthlib"]
24+
25+
26+
@pytest.mark.parametrize("module_name", MODULES)
27+
def test_module_does_not_import_http_client_libraries(module_name):
28+
script = f"""
29+
import sys
30+
try:
31+
import {module_name} # noqa: F401
32+
except BaseException:
33+
import traceback
34+
traceback.print_exc()
35+
sys.exit({_IMPORT_FAILED})
36+
loaded = [m for m in {UNWANTED!r} if m in sys.modules]
37+
print(loaded)
38+
sys.exit({_LOADED} if loaded else {_CLEAN})
39+
"""
40+
proc = subprocess.run(
41+
[sys.executable, "-c", textwrap.dedent(script)],
42+
capture_output=True,
43+
text=True,
44+
)
45+
if proc.returncode == _IMPORT_FAILED:
46+
pytest.skip(f"{module_name} not importable here:\n{proc.stderr}")
47+
assert proc.returncode != _LOADED, f"importing {module_name} loaded {proc.stdout}"
48+
assert (
49+
proc.returncode == _CLEAN
50+
), f"unexpected exit {proc.returncode}:\n{proc.stderr}"
51+
52+
53+
def test_oauth_provider_still_builds_its_manager():
54+
from unittest.mock import MagicMock, patch
55+
56+
from databricks.sql.auth.authenticators import DatabricksOAuthProvider
57+
58+
with patch("databricks.sql.auth.oauth.OAuthManager") as manager, patch.object(
59+
DatabricksOAuthProvider, "_initial_get_token"
60+
):
61+
DatabricksOAuthProvider(
62+
hostname="example.cloud.databricks.com",
63+
oauth_persistence=None,
64+
redirect_port_range=[8020],
65+
client_id="client",
66+
scopes=["sql"],
67+
http_client=MagicMock(),
68+
)
69+
manager.assert_called_once()

0 commit comments

Comments
 (0)