Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# Release History

# Unreleased
- Document the cursor options `arraysize`, `buffer_size_bytes` and `row_limit` for each backend. On kernel connections, `arraysize` and `buffer_size_bytes` do not change server round trips, while `fetchmany(n)` and `row_limit` behave as on Thrift.
- Support `credentials_provider` on kernel connections (`use_kernel=True`), with the same header refresh and token federation as Thrift.
- 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.
- 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.
Expand Down
15 changes: 15 additions & 0 deletions CONNECTION_PARAMETERS.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,18 @@ environment. The backends differ for SOCKS proxies:
| `_use_arrow_native_decimals` | `bool` | ✅ | ❌ | `True` | Thrift wire encoding for `DECIMAL`: `True` → native Arrow `decimal128`, `False` → Arrow string. **No value-level effect**, though: the connector unconditionally re-casts the column back to `decimal128` (`convert_decimals_in_arrow_table`, `thrift_backend.py`), so both `fetchall()` and `fetchall_arrow()` yield `Decimal` / `decimal128(p,s)` either way (verified live). Not forwarded to the kernel, which always returns native Arrow decimals. |
| `_use_arrow_native_timestamps` | `bool` | ✅ | ❌ | `True` | Thrift wire encoding for `TIMESTAMP`: `True` → native Arrow timestamp (→ Python `datetime`), `False` → Arrow string (→ Python **`str`**). **Unlike decimals there is no re-cast**, so `False` genuinely surfaces strings — and `cursor.description` still reports the type code as `'timestamp'`, a mismatch to watch for (verified live). Note the connector always also sends the `spark.thriftserver.arrowBasedRowSet.timestampAsString=false` conf, but the `timestampAsArrow=False` flag wins. Not forwarded to the kernel, which always returns native Arrow timestamps. |

## Cursor fetch options

These knobs are set per cursor via `connection.cursor(...)`, not at
`connect(...)` time. `arraysize` and `buffer_size_bytes` are fetch-batch
(performance) knobs; `row_limit` caps the result itself.

| Option | Type | Thrift | Kernel | Default Value | Note |
| ------------------- | --------------- | :----: | :----: | ------------- | ---- |
| `arraysize` | `int` | ✅ | ⚠️ | `100000` | Thrift sends it as `maxRows` on direct results and `FetchResults`, which affects how many server round trips a result takes. `fetchmany(size)` requires an explicit size on both backends. Kernel does not forward `arraysize`: the kernel picks its own batch sizes, and `fetchmany(n)` slices them client-side, so `fetchmany(n)` still returns exactly `n` rows per call except the last. |
| `buffer_size_bytes` | `int` | ✅ | ❌ | `104857600` | Thrift sends it as `maxBytes` on direct results and `FetchResults`. Accepted and ignored on Kernel. |
| `row_limit` | `Optional[int]` | ✅ | ✅ | `None` | Maximum number of rows in the result; `None` means no limit. Thrift sends it as `resultRowLimit`; Kernel passes it to the kernel statement (`set_row_limit`). |

## Session defaults & transactions

| Option | Type | Thrift | Kernel | Default Value | Note |
Expand Down Expand Up @@ -235,6 +247,9 @@ are forwarded when supported by the installed kernel binding.
8. `force_enable_telemetry`.
9. `_pool_connections` and `_proxy_auth_method` do not configure the
kernel-owned network stack.
10. Cursor fetch tuning: `buffer_size_bytes` is ignored on Kernel, and
`arraysize` does not change server round trips there (`fetchmany(n)`
sizes are unchanged) — see [Cursor fetch options](#cursor-fetch-options).

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

Expand Down
28 changes: 20 additions & 8 deletions tests/unit/test_downloader.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
import unittest
from unittest.mock import patch, MagicMock, Mock
import requests
Expand Down Expand Up @@ -45,8 +46,9 @@ def time_side_effect():

mock_time.side_effect = time_side_effect

@patch("time.time", return_value=1000)
@patch("databricks.sql.cloudfetch.downloader.time")
def test_run_link_expired(self, mock_time):
mock_time.time.return_value = 1000
mock_http_client = MagicMock()
settings = Mock()
result_link = Mock()
Expand All @@ -66,10 +68,11 @@ def test_run_link_expired(self, mock_time):
d.run()
self.assertTrue("link has expired" in context.exception.message)

mock_time.assert_called_once()
mock_time.time.assert_called_once()

@patch("time.time", return_value=1000)
@patch("databricks.sql.cloudfetch.downloader.time")
def test_run_link_past_expiry_buffer(self, mock_time):
mock_time.time.return_value = 1000
mock_http_client = MagicMock()
settings = Mock(link_expiry_buffer_secs=5)
result_link = Mock()
Expand All @@ -85,11 +88,15 @@ def test_run_link_past_expiry_buffer(self, mock_time):
http_client=mock_http_client,
)

# Unrelated logging can occur while this test runs (e.g. when cyclic
# GC closes a session). Its timestamp must not count as a download clock call.
with self.assertLogs("databricks.sql.session", level="INFO"):
logging.getLogger("databricks.sql.session").info("Closing session")
with self.assertRaises(Error) as context:
d.run()
self.assertTrue("link has expired" in context.exception.message)

mock_time.assert_called_once()
mock_time.time.assert_called_once()

@patch("time.time", return_value=1000)
def test_run_get_response_not_ok(self, mock_time):
Expand Down Expand Up @@ -131,7 +138,7 @@ def test_run_uncompressed_successful(self, mock_time):
self._setup_mock_http_response(mock_http_client, status=200, data=file_bytes)

# Patch the log metrics method to avoid division by zero
with patch.object(downloader.ResultSetDownloadHandler, '_log_download_metrics'):
with patch.object(downloader.ResultSetDownloadHandler, "_log_download_metrics"):
d = downloader.ResultSetDownloadHandler(
settings,
result_link,
Expand Down Expand Up @@ -160,11 +167,16 @@ def test_run_compressed_successful(self, mock_time):
result_link.fileLink = "https://s3.amazonaws.com/bucket/file.arrow?token=xyz789"

# Setup mock HTTP response using helper method
self._setup_mock_http_response(mock_http_client, status=200, data=compressed_bytes)
self._setup_mock_http_response(
mock_http_client, status=200, data=compressed_bytes
)

# Mock the decompression method and log metrics to avoid issues
with patch.object(downloader.ResultSetDownloadHandler, '_decompress_data', return_value=file_bytes), \
patch.object(downloader.ResultSetDownloadHandler, '_log_download_metrics'):
with patch.object(
downloader.ResultSetDownloadHandler,
"_decompress_data",
return_value=file_bytes,
), patch.object(downloader.ResultSetDownloadHandler, "_log_download_metrics"):
d = downloader.ResultSetDownloadHandler(
settings,
result_link,
Expand Down
233 changes: 233 additions & 0 deletions tests/unit/test_kernel_fetch_size.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,233 @@
"""Hermetic tests for the cursor fetch-size knobs on the kernel backend.

Covers the maxRows (fetch size) parity criteria for ``use_kernel=True``:

- ``fetchmany(n)`` returns exactly ``n`` rows per call (except the last)
even when the kernel's own Arrow batch boundaries are larger or
smaller than ``n`` — arraysize only slices client-side;
- ``arraysize`` / ``buffer_size_bytes`` are accepted but never forwarded
to the kernel statement: the kernel/SEA transport controls chunk size;
- ``row_limit`` is threaded to the kernel statement's ``set_row_limit``.

No network and no Rust extension dependency: ``test_kernel_client.py``'s
fake kernel module is installed before import, and the result-set tests
drive ``KernelResultSet`` with a fake handle.
"""

from __future__ import annotations

from unittest.mock import MagicMock

import pytest

# pyarrow is an optional connector dep; both KernelResultSet and the
# kernel client import it eagerly, so this module must skip without it.
pa = pytest.importorskip("pyarrow")


# Reuse test_kernel_client.py's session-global fake
# ``databricks_sql_kernel`` stub (client.py imports the extension at
# module import time). Importing that module installs its stub, so both
# files share one ``KernelError`` class in any collection order.
import tests.unit.test_kernel_client as _shared_kernel_stub # noqa: E402

from databricks.sql.auth.authenticators import AccessTokenAuthProvider
from databricks.sql.backend.kernel import client as kernel_client
from databricks.sql.backend.kernel.result_set import KernelResultSet
from databricks.sql.backend.types import CommandId


def test_shares_kernel_stub_with_client_tests():
"""client.py must bind the same fake ``KernelError`` that
test_kernel_client.py raises, whichever file pytest imports first."""
assert kernel_client._kernel.KernelError is _shared_kernel_stub._FakeKernelError


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------


class _CountingKernelHandle:
"""Fake kernel result handle that yields configured RecordBatches and
counts how many times the kernel was actually pulled from."""

def __init__(self, schema: pa.Schema, batches):
self._schema = schema
self._batches = list(batches)
self.fetch_calls = 0
self.arrow_calls = 0

def arrow_schema(self) -> pa.Schema:
self.arrow_calls += 1
return self._schema

def fetch_next_batch(self):
self.fetch_calls += 1
if not self._batches:
return None
return self._batches.pop(0)

def close(self):
pass


def _int_batch(n_rows: int) -> pa.RecordBatch:
schema = pa.schema([("n", pa.int64())])
return pa.RecordBatch.from_arrays(
[pa.array(range(n_rows), type=pa.int64())], schema=schema
)


def _make_kernel_client() -> kernel_client.KernelDatabricksClient:
return kernel_client.KernelDatabricksClient(
server_hostname="example.cloud.databricks.com",
http_path="/sql/1.0/warehouses/abc",
auth_provider=AccessTokenAuthProvider("dapi-test"),
ssl_options=None,
)


def _make_cursor(arraysize: int = 1000, buffer_size_bytes: int = 4096) -> MagicMock:
cursor = MagicMock()
cursor.arraysize = arraysize
cursor.buffer_size_bytes = buffer_size_bytes
return cursor


def _make_stmt() -> MagicMock:
stmt = MagicMock()
stmt.execute.return_value = MagicMock(
statement_id="stmt-id",
arrow_schema=MagicMock(return_value=pa.schema([("x", pa.int64())])),
)
return stmt


def _run_execute(c, cursor, stmt, **kwargs):
c._kernel_session = MagicMock()
c._kernel_session.statement.return_value = stmt
args = dict(
operation="SELECT id FROM range(100000)",
session_id=MagicMock(),
max_rows=cursor.arraysize,
max_bytes=cursor.buffer_size_bytes,
lz4_compression=False,
cursor=cursor,
use_cloud_fetch=False,
parameters=[],
async_op=False,
enforce_embedded_schema_correctness=False,
)
args.update(kwargs)
return c.execute_command(**args)


# ---------------------------------------------------------------------------
# AC-1: fetchmany(n) returns exactly n rows per call across kernel batches
# ---------------------------------------------------------------------------


def test_fetchmany_exact_over_kernel_batches():
"""A kernel result delivered as a 4096-row batch followed by a
781-row batch (the real shapes seen on DBSQL / Reyden) must be
re-sliced by ``fetchmany(1000)`` to exactly 1000 rows per call,
1000, 1000, 1000, 1000 and a final 877 — with no extra kernel
pulls while a batch is already buffered."""
handle = _CountingKernelHandle(
pa.schema([("n", pa.int64())]),
[_int_batch(4096), _int_batch(781)],
)
rs = KernelResultSet(
connection=MagicMock(),
backend=MagicMock(),
kernel_handle=handle,
command_id=CommandId.from_sea_statement_id("fetch-size-test"),
arraysize=1000,
buffer_size_bytes=4096,
)

sizes = []
total = 0
while True:
rows = rs.fetchmany(1000)
if not rows:
break
sizes.append(len(rows))
total += len(rows)

assert sizes == [1000, 1000, 1000, 1000, 877]
assert total == 4096 + 781
# Two data batches plus one end-of-stream probe; no re-fetch while
# rows were already buffered.
assert handle.fetch_calls == 3
assert rs.has_more_rows is False


def test_fetchmany_exact_smaller_than_kernel_batch():
"""Slicing *within* one kernel batch: every fetchmany(1000) on a
single 4096-row batch returns 1000 rows until only 96 remain."""
handle = _CountingKernelHandle(pa.schema([("n", pa.int64())]), [_int_batch(4096)])
rs = KernelResultSet(
connection=MagicMock(),
backend=MagicMock(),
kernel_handle=handle,
command_id=CommandId.from_sea_statement_id("fetch-size-test"),
arraysize=1000,
buffer_size_bytes=4096,
)
sizes = [len(rs.fetchmany(1000)) for _ in range(5)]
assert sizes == [1000, 1000, 1000, 1000, 96]
assert handle.fetch_calls == 2 # one data batch + end-of-stream probe


# ---------------------------------------------------------------------------
# AC-3: arraysize / buffer_size_bytes are accepted but not forwarded
# ---------------------------------------------------------------------------


def test_arraysize_not_forwarded_to_kernel():
"""``Cursor.execute`` passes ``max_rows=cursor.arraysize`` /
``max_bytes=cursor.buffer_size_bytes`` into ``execute_command``, but
the kernel backend must not forward either to the kernel statement:
the kernel/SEA transport picks its own chunk size. The only
statement-level setters that may fire are ``set_sql`` and
``set_row_limit`` (plus the internal canceller / execute)."""
c = _make_kernel_client()
cursor = _make_cursor(arraysize=1000, buffer_size_bytes=4096)
stmt = _make_stmt()

result_set = _run_execute(c, cursor, stmt)

called_names = [name for name, _args, _kwargs in stmt.method_calls]
allowed = {"set_sql", "set_row_limit", "canceller", "execute"}
unexpected = [n for n in called_names if n not in allowed]
assert unexpected == [], (
f"kernel statement received unexpected calls (arraysize or "
f"buffer_size_bytes must not reach the kernel): {unexpected}"
)
# No setter may smuggle the fetch-size knobs in under another name —
# row_limit stays None regardless of arraysize.
stmt.set_row_limit.assert_called_once_with(None)
# arraysize is still honored client-side by the result set.
assert result_set.arraysize == 1000
assert result_set.buffer_size_bytes == 4096


# ---------------------------------------------------------------------------
# AC-4: row_limit is threaded to the kernel statement
# ---------------------------------------------------------------------------


@pytest.mark.parametrize("row_limit", [None, 0, 500])
def test_execute_passes_row_limit_to_statement(row_limit):
"""``execute_command(row_limit=...)`` must reach the kernel
statement as ``set_row_limit`` so the SEA request carries the
result-row limit, independent of ``arraysize``."""
c = _make_kernel_client()
cursor = _make_cursor(arraysize=100000)
stmt = _make_stmt()

_run_execute(c, cursor, stmt, row_limit=row_limit)

stmt.set_row_limit.assert_called_once_with(row_limit)
Loading