Skip to content

Commit 53893d3

Browse files
vuanhphungIsaac
andcommitted
perf: skip latency timing nothing records; build rows in fewer calls
log_latency timed every decorated call (execute, execute_async, metadata calls) and then dropped the result when telemetry was off and DEBUG logging was disabled, which is always the case on kernel connections. It now checks first and calls the method directly. Row factories built each row through Row.__call__, _create_row, Row.__new__ and Row.__setattr__; they now build the tuple and set __fields__ directly, producing the same object. Single-thread benchmark of one-row kernel queries with the kernel faked: 17.2 -> 16.2 us of Python per query; a 5-column row factory call drops from 402 to 288 ns. Signed-off-by: Vu Anh Phung <vu.phung@databricks.com> Co-authored-by: Isaac <no-reply@databricks.com>
1 parent bc2e0f2 commit 53893d3

5 files changed

Lines changed: 176 additions & 7 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
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.
77
- Speed up fetching small results on the kernel backend (`use_kernel=True`): they are converted to rows without building a pandas DataFrame when that is cheaper and gives the same values, which cut client CPU per query by 47% in a local benchmark of 200 concurrent sessions running one-row queries against a mock server.
88
- Cut more per-query work on the kernel backend: reuse the cursor description while a connection's statements return the same result schema, and build small results' rows straight from the record batches instead of first combining them into a table.
9+
- Cut per-call and per-row work on all backends: don't time `execute()` and metadata calls when neither telemetry nor debug logging would record the latency, and build each result `Row` with fewer Python calls.
910

1011
# 4.9.0 (2026-11-04)
1112
- 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/telemetry/latency_logger.py‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,17 @@ def execute(self, query):
177177
def decorator(func):
178178
@functools.wraps(func)
179179
def wrapper(self, *args, **kwargs):
180+
# Fast check: use cached telemetry_enabled flag from connection
181+
# Avoids dictionary lookup + instance check on every operation
182+
connection = getattr(self, "connection", None)
183+
telemetry_enabled = bool(connection) and getattr(
184+
connection, "telemetry_enabled", False
185+
)
186+
if not telemetry_enabled and not logger.isEnabledFor(logging.DEBUG):
187+
# Nothing would record the latency (always the case on kernel
188+
# connections, which export telemetry from the kernel).
189+
return func(self, *args, **kwargs)
190+
180191
start_time = time.monotonic()
181192
try:
182193
return func(self, *args, **kwargs)
@@ -186,10 +197,7 @@ def wrapper(self, *args, **kwargs):
186197
# Always log for debugging
187198
logger.debug("%s completed in %dms", func.__name__, duration_ms)
188199

189-
# Fast check: use cached telemetry_enabled flag from connection
190-
# Avoids dictionary lookup + instance check on every operation
191-
connection = getattr(self, "connection", None)
192-
if connection and getattr(connection, "telemetry_enabled", False):
200+
if telemetry_enabled:
193201
session_id_hex = connection.get_session_id_hex()
194202
if session_id_hex:
195203
# Telemetry enabled - extract and send

‎src/databricks/sql/types.py‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,10 @@ def __call__(self, *args: Any) -> "Row":
257257
"Can not create Row with fields %s, expected %d values "
258258
"but got %s" % (self, len(self), args)
259259
)
260-
return _create_row(self, args)
260+
# Same as _create_row(self, args), inlined: this runs once per fetched row.
261+
row = _tuple_new(Row, args)
262+
row.__dict__["__fields__"] = self
263+
return row
261264

262265
def __getitem__(self, item: Any) -> Any:
263266
if isinstance(item, (int, slice)):
@@ -309,9 +312,14 @@ def __repr__(self) -> str:
309312
return "<Row(%s)>" % ", ".join("%r" % field for field in self)
310313

311314

315+
_tuple_new = tuple.__new__
316+
317+
312318
def _create_row(
313319
fields: Union["Row", List[str]], values: Union[Tuple[Any, ...], List[Any]]
314320
) -> "Row":
315-
row = Row(*values)
316-
row.__fields__ = fields
321+
# Equivalent to ``row = Row(*values); row.__fields__ = fields`` without the
322+
# Row.__new__ and Row.__setattr__ calls.
323+
row = _tuple_new(Row, values)
324+
row.__dict__["__fields__"] = fields
317325
return row

‎tests/unit/test_latency_logger.py‎

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import logging
2+
from unittest.mock import MagicMock, patch
3+
4+
import pytest
5+
6+
from databricks.sql.telemetry.latency_logger import log_latency
7+
from databricks.sql.telemetry.models.enums import StatementType
8+
9+
LOGGER = "databricks.sql.telemetry.latency_logger"
10+
11+
12+
class Cursor:
13+
"""Stand-in for databricks.sql.client.Cursor (telemetry keys on the class name)."""
14+
15+
def __init__(self, telemetry_enabled):
16+
self.connection = MagicMock()
17+
self.connection.telemetry_enabled = telemetry_enabled
18+
self.connection.get_session_id_hex.return_value = "session-hex"
19+
self.connection.session.host = "host"
20+
self.connection.lz4_compression = False
21+
self.query_id = "statement-id"
22+
self.active_result_set = None
23+
self.backend = MagicMock(retry_policy=None)
24+
25+
@log_latency(StatementType.QUERY)
26+
def execute(self, value):
27+
return value
28+
29+
@log_latency(StatementType.QUERY)
30+
def fail(self):
31+
raise ValueError("boom")
32+
33+
34+
@pytest.fixture
35+
def telemetry_client():
36+
client = MagicMock()
37+
with patch(
38+
"databricks.sql.telemetry.latency_logger.TelemetryClientFactory.get_telemetry_client",
39+
return_value=client,
40+
):
41+
yield client
42+
43+
44+
@pytest.fixture
45+
def no_debug():
46+
logger = logging.getLogger(LOGGER)
47+
level = logger.level
48+
logger.setLevel(logging.INFO)
49+
yield
50+
logger.setLevel(level)
51+
52+
53+
def test_disabled_telemetry_without_debug_only_calls_the_method(
54+
telemetry_client, no_debug, caplog
55+
):
56+
cursor = Cursor(telemetry_enabled=False)
57+
with caplog.at_level(logging.INFO, logger=LOGGER):
58+
assert cursor.execute(42) == 42
59+
with pytest.raises(ValueError, match="boom"):
60+
cursor.fail()
61+
telemetry_client.export_latency_log.assert_not_called()
62+
assert not caplog.records
63+
64+
65+
def test_debug_logging_records_latency_without_telemetry(telemetry_client, caplog):
66+
cursor = Cursor(telemetry_enabled=False)
67+
with caplog.at_level(logging.DEBUG, logger=LOGGER):
68+
assert cursor.execute(1) == 1
69+
assert [r.getMessage() for r in caplog.records] == ["execute completed in 0ms"]
70+
telemetry_client.export_latency_log.assert_not_called()
71+
72+
73+
@pytest.mark.parametrize("debug", [False, True])
74+
def test_enabled_telemetry_exports_latency_even_on_error(
75+
telemetry_client, no_debug, debug, caplog
76+
):
77+
cursor = Cursor(telemetry_enabled=True)
78+
with caplog.at_level(logging.DEBUG if debug else logging.INFO, logger=LOGGER):
79+
assert cursor.execute("ok") == "ok"
80+
with pytest.raises(ValueError, match="boom"):
81+
cursor.fail()
82+
assert telemetry_client.export_latency_log.call_count == 2
83+
kwargs = telemetry_client.export_latency_log.call_args.kwargs
84+
assert kwargs["session_id"] == "session-hex"
85+
assert kwargs["sql_statement_id"] == "statement-id"
86+
assert kwargs["sql_execution_event"].statement_type == StatementType.QUERY
87+
assert len(caplog.records) == (2 if debug else 0)
88+
89+
90+
def test_object_without_connection_is_not_exported(telemetry_client, no_debug):
91+
class Handler:
92+
@log_latency(StatementType.QUERY)
93+
def run(self):
94+
return "done"
95+
96+
assert Handler().run() == "done"
97+
telemetry_client.export_latency_log.assert_not_called()
98+
99+
100+
def test_wrapper_keeps_the_method_metadata():
101+
assert Cursor.execute.__name__ == "execute"
102+
assert Cursor.execute.__wrapped__(Cursor(False), 3) == 3

‎tests/unit/test_row.py‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import pickle
2+
3+
import pytest
4+
5+
from databricks.sql.types import Row, _create_row
6+
7+
8+
def test_row_factory_builds_named_rows():
9+
Person = Row("name", "age")
10+
row = Person("Alice", 11)
11+
assert type(row) is Row
12+
assert row == ("Alice", 11)
13+
assert row.__fields__ is Person
14+
assert row.__dict__ == {"__fields__": Person}
15+
assert row.name == "Alice" and row["age"] == 11 and row[0] == "Alice"
16+
assert row.asDict() == {"name": "Alice", "age": 11}
17+
assert repr(row) == "Row(name='Alice', age=11)"
18+
assert "name" in row and "wrong" not in row
19+
assert row == Row(name="Alice", age=11)
20+
21+
22+
def test_row_factory_accepts_fewer_values_and_rejects_more():
23+
Person = Row("name", "age")
24+
assert Person("Alice") == ("Alice",)
25+
assert Person() == ()
26+
with pytest.raises(ValueError, match="expected 2 values but got"):
27+
Person("Alice", 11, "extra")
28+
29+
30+
def test_rows_stay_read_only():
31+
row = Row("a")(1)
32+
with pytest.raises(RuntimeError, match="read-only"):
33+
row.a = 2
34+
35+
36+
def test_create_row_matches_the_factory():
37+
fields = ["a", "b"]
38+
row = _create_row(fields, [1, 2])
39+
assert type(row) is Row
40+
assert row == (1, 2)
41+
assert row.__fields__ is fields
42+
assert row.asDict() == {"a": 1, "b": 2}
43+
44+
45+
def test_pickle_round_trip():
46+
row = Row("a", "b")(1, None)
47+
copy = pickle.loads(pickle.dumps(row))
48+
assert copy == row and type(copy) is Row
49+
assert copy.asDict() == {"a": 1, "b": None}
50+
assert repr(copy) == repr(row)

0 commit comments

Comments
 (0)