From c5b633a9f07bbea9b1babf32635322355bf742f1 Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:41:14 +0000 Subject: [PATCH 1/3] docs: document cursor fetch options per backend, with kernel tests Document arraysize, buffer_size_bytes and row_limit for Thrift and Kernel. Clarify that fetchmany(size) requires an explicit size and that kernel fetches slice server-selected batches without forwarding fetch knobs. Add hermetic coverage for exact fetchmany slices across kernel batches, inert arraysize/buffer_size_bytes and row_limit forwarding. Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac --- CHANGELOG.md | 1 + CONNECTION_PARAMETERS.md | 15 ++ tests/unit/test_kernel_fetch_size.py | 250 +++++++++++++++++++++++++++ 3 files changed, 266 insertions(+) create mode 100644 tests/unit/test_kernel_fetch_size.py diff --git a/CHANGELOG.md b/CHANGELOG.md index c31d6927f..5f3592672 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. - 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. diff --git a/CONNECTION_PARAMETERS.md b/CONNECTION_PARAMETERS.md index 4e91c6597..d78f99ff5 100644 --- a/CONNECTION_PARAMETERS.md +++ b/CONNECTION_PARAMETERS.md @@ -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 | @@ -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 diff --git a/tests/unit/test_kernel_fetch_size.py b/tests/unit/test_kernel_fetch_size.py new file mode 100644 index 000000000..bce20477b --- /dev/null +++ b/tests/unit/test_kernel_fetch_size.py @@ -0,0 +1,250 @@ +"""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: a fake kernel module is +installed before import (same approach as ``test_kernel_client.py``) and +the result-set tests drive ``KernelResultSet`` with a fake handle. +""" + +from __future__ import annotations + +import sys +import types +from typing import Optional +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") + + +# Install the same session-global fake ``databricks_sql_kernel`` stub +# used by test_kernel_client.py (client.py imports the extension at +# module import time). ``setdefault`` keeps it idempotent when both +# files run in one pytest session. +_fake_kernel_module = types.ModuleType("databricks_sql_kernel") + + +class _FakeKernelError(Exception): + def __init__(self, code: str = "Unknown", message: str = "boom") -> None: + super().__init__(message) + self.code = code + self.message = message + self.sql_state = None + self.error_code = None + self.vendor_code = None + self.http_status = None + self.retryable = False + self.query_id = None + self.diagnostic_info: Optional[str] = None + self.display_message: Optional[str] = None + self.error_details_json: Optional[str] = None + + +_fake_kernel_module.KernelError = _FakeKernelError # type: ignore[attr-defined] +_fake_kernel_module.Session = MagicMock() # type: ignore[attr-defined] +sys.modules.setdefault("databricks_sql_kernel", _fake_kernel_module) + +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 + +# --------------------------------------------------------------------------- +# 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) From 86dd495ec78bfde002b8f63ab4a4e441e45300df Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:17:55 +0000 Subject: [PATCH 2/3] test: share the fake kernel stub in test_kernel_fetch_size test_kernel_fetch_size.py installed its own databricks_sql_kernel stub with a separate KernelError class. When that file was imported before test_kernel_client.py, client.py bound the wrong class and two client tests failed. Reuse test_kernel_client.py's stub and assert both files see the same KernelError. Co-authored-by: Isaac Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> --- tests/unit/test_kernel_fetch_size.py | 47 +++++++++------------------- 1 file changed, 15 insertions(+), 32 deletions(-) diff --git a/tests/unit/test_kernel_fetch_size.py b/tests/unit/test_kernel_fetch_size.py index bce20477b..e14e8fa1a 100644 --- a/tests/unit/test_kernel_fetch_size.py +++ b/tests/unit/test_kernel_fetch_size.py @@ -9,16 +9,13 @@ 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: a fake kernel module is -installed before import (same approach as ``test_kernel_client.py``) and -the result-set tests drive ``KernelResultSet`` with a fake handle. +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 -import sys -import types -from typing import Optional from unittest.mock import MagicMock import pytest @@ -28,38 +25,24 @@ pa = pytest.importorskip("pyarrow") -# Install the same session-global fake ``databricks_sql_kernel`` stub -# used by test_kernel_client.py (client.py imports the extension at -# module import time). ``setdefault`` keeps it idempotent when both -# files run in one pytest session. -_fake_kernel_module = types.ModuleType("databricks_sql_kernel") - - -class _FakeKernelError(Exception): - def __init__(self, code: str = "Unknown", message: str = "boom") -> None: - super().__init__(message) - self.code = code - self.message = message - self.sql_state = None - self.error_code = None - self.vendor_code = None - self.http_status = None - self.retryable = False - self.query_id = None - self.diagnostic_info: Optional[str] = None - self.display_message: Optional[str] = None - self.error_details_json: Optional[str] = None - - -_fake_kernel_module.KernelError = _FakeKernelError # type: ignore[attr-defined] -_fake_kernel_module.Session = MagicMock() # type: ignore[attr-defined] -sys.modules.setdefault("databricks_sql_kernel", _fake_kernel_module) +# 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 # --------------------------------------------------------------------------- From f5049ad78953e08fc70a73afb6c3833918a3ed56 Mon Sep 17 00:00:00 2001 From: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Date: Fri, 4 Dec 2026 01:34:09 +0000 Subject: [PATCH 3/3] test: isolate downloader clock from logging Signed-off-by: Cathleen Yan <58714163+cathleeny@users.noreply.github.com> Co-authored-by: Isaac --- tests/unit/test_downloader.py | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/tests/unit/test_downloader.py b/tests/unit/test_downloader.py index 00b1b849a..80190dd12 100644 --- a/tests/unit/test_downloader.py +++ b/tests/unit/test_downloader.py @@ -1,3 +1,4 @@ +import logging import unittest from unittest.mock import patch, MagicMock, Mock import requests @@ -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() @@ -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() @@ -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): @@ -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, @@ -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,