Skip to content

Commit c5b633a

Browse files
cathleenyIsaac
andcommitted
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 <no-reply@databricks.com>
1 parent 72ac235 commit c5b633a

3 files changed

Lines changed: 266 additions & 0 deletions

File tree

‎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+
- 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.
45
- 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.
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: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,18 @@ environment. The backends differ for SOCKS proxies:
178178
| `_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. |
179179
| `_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. |
180180

181+
## Cursor fetch options
182+
183+
These knobs are set per cursor via `connection.cursor(...)`, not at
184+
`connect(...)` time. `arraysize` and `buffer_size_bytes` are fetch-batch
185+
(performance) knobs; `row_limit` caps the result itself.
186+
187+
| Option | Type | Thrift | Kernel | Default Value | Note |
188+
| ------------------- | --------------- | :----: | :----: | ------------- | ---- |
189+
| `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. |
190+
| `buffer_size_bytes` | `int` | ✅ | ❌ | `104857600` | Thrift sends it as `maxBytes` on direct results and `FetchResults`. Accepted and ignored on Kernel. |
191+
| `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`). |
192+
181193
## Session defaults & transactions
182194

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

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

Lines changed: 250 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,250 @@
1+
"""Hermetic tests for the cursor fetch-size knobs on the kernel backend.
2+
3+
Covers the maxRows (fetch size) parity criteria for ``use_kernel=True``:
4+
5+
- ``fetchmany(n)`` returns exactly ``n`` rows per call (except the last)
6+
even when the kernel's own Arrow batch boundaries are larger or
7+
smaller than ``n`` — arraysize only slices client-side;
8+
- ``arraysize`` / ``buffer_size_bytes`` are accepted but never forwarded
9+
to the kernel statement: the kernel/SEA transport controls chunk size;
10+
- ``row_limit`` is threaded to the kernel statement's ``set_row_limit``.
11+
12+
No network and no Rust extension dependency: a fake kernel module is
13+
installed before import (same approach as ``test_kernel_client.py``) and
14+
the result-set tests drive ``KernelResultSet`` with a fake handle.
15+
"""
16+
17+
from __future__ import annotations
18+
19+
import sys
20+
import types
21+
from typing import Optional
22+
from unittest.mock import MagicMock
23+
24+
import pytest
25+
26+
# pyarrow is an optional connector dep; both KernelResultSet and the
27+
# kernel client import it eagerly, so this module must skip without it.
28+
pa = pytest.importorskip("pyarrow")
29+
30+
31+
# Install the same session-global fake ``databricks_sql_kernel`` stub
32+
# used by test_kernel_client.py (client.py imports the extension at
33+
# module import time). ``setdefault`` keeps it idempotent when both
34+
# files run in one pytest session.
35+
_fake_kernel_module = types.ModuleType("databricks_sql_kernel")
36+
37+
38+
class _FakeKernelError(Exception):
39+
def __init__(self, code: str = "Unknown", message: str = "boom") -> None:
40+
super().__init__(message)
41+
self.code = code
42+
self.message = message
43+
self.sql_state = None
44+
self.error_code = None
45+
self.vendor_code = None
46+
self.http_status = None
47+
self.retryable = False
48+
self.query_id = None
49+
self.diagnostic_info: Optional[str] = None
50+
self.display_message: Optional[str] = None
51+
self.error_details_json: Optional[str] = None
52+
53+
54+
_fake_kernel_module.KernelError = _FakeKernelError # type: ignore[attr-defined]
55+
_fake_kernel_module.Session = MagicMock() # type: ignore[attr-defined]
56+
sys.modules.setdefault("databricks_sql_kernel", _fake_kernel_module)
57+
58+
from databricks.sql.auth.authenticators import AccessTokenAuthProvider
59+
from databricks.sql.backend.kernel import client as kernel_client
60+
from databricks.sql.backend.kernel.result_set import KernelResultSet
61+
from databricks.sql.backend.types import CommandId
62+
63+
# ---------------------------------------------------------------------------
64+
# Helpers
65+
# ---------------------------------------------------------------------------
66+
67+
68+
class _CountingKernelHandle:
69+
"""Fake kernel result handle that yields configured RecordBatches and
70+
counts how many times the kernel was actually pulled from."""
71+
72+
def __init__(self, schema: pa.Schema, batches):
73+
self._schema = schema
74+
self._batches = list(batches)
75+
self.fetch_calls = 0
76+
self.arrow_calls = 0
77+
78+
def arrow_schema(self) -> pa.Schema:
79+
self.arrow_calls += 1
80+
return self._schema
81+
82+
def fetch_next_batch(self):
83+
self.fetch_calls += 1
84+
if not self._batches:
85+
return None
86+
return self._batches.pop(0)
87+
88+
def close(self):
89+
pass
90+
91+
92+
def _int_batch(n_rows: int) -> pa.RecordBatch:
93+
schema = pa.schema([("n", pa.int64())])
94+
return pa.RecordBatch.from_arrays(
95+
[pa.array(range(n_rows), type=pa.int64())], schema=schema
96+
)
97+
98+
99+
def _make_kernel_client() -> kernel_client.KernelDatabricksClient:
100+
return kernel_client.KernelDatabricksClient(
101+
server_hostname="example.cloud.databricks.com",
102+
http_path="/sql/1.0/warehouses/abc",
103+
auth_provider=AccessTokenAuthProvider("dapi-test"),
104+
ssl_options=None,
105+
)
106+
107+
108+
def _make_cursor(arraysize: int = 1000, buffer_size_bytes: int = 4096) -> MagicMock:
109+
cursor = MagicMock()
110+
cursor.arraysize = arraysize
111+
cursor.buffer_size_bytes = buffer_size_bytes
112+
return cursor
113+
114+
115+
def _make_stmt() -> MagicMock:
116+
stmt = MagicMock()
117+
stmt.execute.return_value = MagicMock(
118+
statement_id="stmt-id",
119+
arrow_schema=MagicMock(return_value=pa.schema([("x", pa.int64())])),
120+
)
121+
return stmt
122+
123+
124+
def _run_execute(c, cursor, stmt, **kwargs):
125+
c._kernel_session = MagicMock()
126+
c._kernel_session.statement.return_value = stmt
127+
args = dict(
128+
operation="SELECT id FROM range(100000)",
129+
session_id=MagicMock(),
130+
max_rows=cursor.arraysize,
131+
max_bytes=cursor.buffer_size_bytes,
132+
lz4_compression=False,
133+
cursor=cursor,
134+
use_cloud_fetch=False,
135+
parameters=[],
136+
async_op=False,
137+
enforce_embedded_schema_correctness=False,
138+
)
139+
args.update(kwargs)
140+
return c.execute_command(**args)
141+
142+
143+
# ---------------------------------------------------------------------------
144+
# AC-1: fetchmany(n) returns exactly n rows per call across kernel batches
145+
# ---------------------------------------------------------------------------
146+
147+
148+
def test_fetchmany_exact_over_kernel_batches():
149+
"""A kernel result delivered as a 4096-row batch followed by a
150+
781-row batch (the real shapes seen on DBSQL / Reyden) must be
151+
re-sliced by ``fetchmany(1000)`` to exactly 1000 rows per call,
152+
1000, 1000, 1000, 1000 and a final 877 — with no extra kernel
153+
pulls while a batch is already buffered."""
154+
handle = _CountingKernelHandle(
155+
pa.schema([("n", pa.int64())]),
156+
[_int_batch(4096), _int_batch(781)],
157+
)
158+
rs = KernelResultSet(
159+
connection=MagicMock(),
160+
backend=MagicMock(),
161+
kernel_handle=handle,
162+
command_id=CommandId.from_sea_statement_id("fetch-size-test"),
163+
arraysize=1000,
164+
buffer_size_bytes=4096,
165+
)
166+
167+
sizes = []
168+
total = 0
169+
while True:
170+
rows = rs.fetchmany(1000)
171+
if not rows:
172+
break
173+
sizes.append(len(rows))
174+
total += len(rows)
175+
176+
assert sizes == [1000, 1000, 1000, 1000, 877]
177+
assert total == 4096 + 781
178+
# Two data batches plus one end-of-stream probe; no re-fetch while
179+
# rows were already buffered.
180+
assert handle.fetch_calls == 3
181+
assert rs.has_more_rows is False
182+
183+
184+
def test_fetchmany_exact_smaller_than_kernel_batch():
185+
"""Slicing *within* one kernel batch: every fetchmany(1000) on a
186+
single 4096-row batch returns 1000 rows until only 96 remain."""
187+
handle = _CountingKernelHandle(pa.schema([("n", pa.int64())]), [_int_batch(4096)])
188+
rs = KernelResultSet(
189+
connection=MagicMock(),
190+
backend=MagicMock(),
191+
kernel_handle=handle,
192+
command_id=CommandId.from_sea_statement_id("fetch-size-test"),
193+
arraysize=1000,
194+
buffer_size_bytes=4096,
195+
)
196+
sizes = [len(rs.fetchmany(1000)) for _ in range(5)]
197+
assert sizes == [1000, 1000, 1000, 1000, 96]
198+
assert handle.fetch_calls == 2 # one data batch + end-of-stream probe
199+
200+
201+
# ---------------------------------------------------------------------------
202+
# AC-3: arraysize / buffer_size_bytes are accepted but not forwarded
203+
# ---------------------------------------------------------------------------
204+
205+
206+
def test_arraysize_not_forwarded_to_kernel():
207+
"""``Cursor.execute`` passes ``max_rows=cursor.arraysize`` /
208+
``max_bytes=cursor.buffer_size_bytes`` into ``execute_command``, but
209+
the kernel backend must not forward either to the kernel statement:
210+
the kernel/SEA transport picks its own chunk size. The only
211+
statement-level setters that may fire are ``set_sql`` and
212+
``set_row_limit`` (plus the internal canceller / execute)."""
213+
c = _make_kernel_client()
214+
cursor = _make_cursor(arraysize=1000, buffer_size_bytes=4096)
215+
stmt = _make_stmt()
216+
217+
result_set = _run_execute(c, cursor, stmt)
218+
219+
called_names = [name for name, _args, _kwargs in stmt.method_calls]
220+
allowed = {"set_sql", "set_row_limit", "canceller", "execute"}
221+
unexpected = [n for n in called_names if n not in allowed]
222+
assert unexpected == [], (
223+
f"kernel statement received unexpected calls (arraysize or "
224+
f"buffer_size_bytes must not reach the kernel): {unexpected}"
225+
)
226+
# No setter may smuggle the fetch-size knobs in under another name —
227+
# row_limit stays None regardless of arraysize.
228+
stmt.set_row_limit.assert_called_once_with(None)
229+
# arraysize is still honored client-side by the result set.
230+
assert result_set.arraysize == 1000
231+
assert result_set.buffer_size_bytes == 4096
232+
233+
234+
# ---------------------------------------------------------------------------
235+
# AC-4: row_limit is threaded to the kernel statement
236+
# ---------------------------------------------------------------------------
237+
238+
239+
@pytest.mark.parametrize("row_limit", [None, 0, 500])
240+
def test_execute_passes_row_limit_to_statement(row_limit):
241+
"""``execute_command(row_limit=...)`` must reach the kernel
242+
statement as ``set_row_limit`` so the SEA request carries the
243+
result-row limit, independent of ``arraysize``."""
244+
c = _make_kernel_client()
245+
cursor = _make_cursor(arraysize=100000)
246+
stmt = _make_stmt()
247+
248+
_run_execute(c, cursor, stmt, row_limit=row_limit)
249+
250+
stmt.set_row_limit.assert_called_once_with(row_limit)

0 commit comments

Comments
 (0)