forked from databricks/databricks-sql-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_kernel_client.py
More file actions
1751 lines (1482 loc) · 64.5 KB
/
Copy pathtest_kernel_client.py
File metadata and controls
1751 lines (1482 loc) · 64.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Unit tests for ``KernelDatabricksClient`` — the error mapping,
state-mapping, async-handle bookkeeping, and method-level guards
that don't require a live kernel session.
The connector's ``databricks.sql.backend.kernel.client`` module
imports the ``databricks_sql_kernel`` extension at import time, so
this test installs a fake module into ``sys.modules`` *before*
importing the client. The fake exposes the minimum surface the
client touches (``Session``, ``KernelError``, ``Statement``,
``ExecutedStatement``, ``ExecutedAsyncStatement``, ``ResultStream``,
``metadata``).
"""
from __future__ import annotations
import sys
import types
from typing import Optional
from unittest.mock import MagicMock
import pytest
# pyarrow is an optional dep; the kernel client's result_set imports
# it eagerly, so the whole module must skip when pyarrow is missing.
pa = pytest.importorskip("pyarrow")
# ---------------------------------------------------------------------------
# Fake databricks_sql_kernel module — installed before client.py imports.
# ---------------------------------------------------------------------------
class _FakeKernelError(Exception):
"""Stand-in for ``databricks_sql_kernel.KernelError``. Carries
the structured attrs the connector forwards onto the re-raised
PEP 249 exception."""
def __init__(
self,
code: str = "Unknown",
message: str = "boom",
sql_state: Optional[str] = None,
query_id: Optional[str] = None,
diagnostic_info: Optional[str] = None,
display_message: Optional[str] = None,
error_details_json: Optional[str] = None,
) -> None:
super().__init__(message)
self.code = code
self.message = message
self.sql_state = sql_state
self.error_code = None
self.vendor_code = None
self.http_status = None
self.retryable = False
self.query_id = query_id
# Extended server status forwarded across the PyO3 boundary
# (kernel #121). Defaults None so existing tests are unaffected.
self.diagnostic_info = diagnostic_info
self.display_message = display_message
self.error_details_json = error_details_json
# These unit tests exercise the connector's error-mapping / wiring logic
# and need a *controllable* fake ``KernelError`` (to simulate arbitrary
# kernel error codes), so they install a fake ``databricks_sql_kernel``
# into ``sys.modules`` unconditionally.
#
# IMPORTANT: this fake is session-global and shadows a real wheel if one
# is installed. Tests that need the REAL wheel (the use_kernel routing
# test in test_session.py, and the e2e suite in
# tests/e2e/test_kernel_backend.py) MUST be run in a SEPARATE pytest
# invocation from this file — never `pytest tests/unit tests/e2e` in one
# session when the real wheel is installed. Both of those real-wheel
# tests detect the shadowing (real wheel present but sys.modules holds a
# stub) and FAIL LOUDLY rather than silently skipping, so a CI job that
# accidentally mixes them will go red instead of falsely green. The
# kernel CI matrix runs the real-wheel tests as their own step.
_fake_kernel_module = types.ModuleType("databricks_sql_kernel")
_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)
# Importing the client now picks up the fake module via
# ``import databricks_sql_kernel as _kernel`` at the top of client.py.
from databricks.sql.auth.authenticators import AccessTokenAuthProvider
from databricks.sql.backend.kernel import client as kernel_client
from databricks.sql.backend.types import CommandId, CommandState
from databricks.sql.exc import (
DatabaseError,
InterfaceError,
NotSupportedError,
OperationalError,
ProgrammingError,
ServerOperationError,
)
# ---------------------------------------------------------------------------
# Error mapping
# ---------------------------------------------------------------------------
@pytest.mark.parametrize(
"code, expected_cls",
[
("InvalidArgument", ProgrammingError),
("Unauthenticated", OperationalError),
("PermissionDenied", OperationalError),
("NotFound", ProgrammingError),
("ResourceExhausted", OperationalError),
("Unavailable", OperationalError),
("Timeout", OperationalError),
("Cancelled", OperationalError),
("DataLoss", DatabaseError),
("Internal", DatabaseError),
("InvalidStatementHandle", ProgrammingError),
("NetworkError", OperationalError),
# `SqlError` is the kernel's slug for server-side query
# failures (syntax error, missing object, etc.) — exactly the
# case Thrift's backend surfaces as ``ServerOperationError``.
# Match Thrift so user code that catches the specific class
# works equivalently. ``ServerOperationError`` is itself a
# ``DatabaseError`` subclass, so existing catches of the base
# class are unaffected.
("SqlError", ServerOperationError),
("Unknown", DatabaseError),
],
)
def test_code_to_exception_mapping(code, expected_cls):
"""Every entry in ``_CODE_TO_EXCEPTION`` maps to the documented
PEP 249 class. Cause chaining happens at the ``raise ... from exc``
call site, not inside ``_reraise_kernel_error`` — verified
separately by ``test_kernel_error_chains_through_wrap``."""
err = _FakeKernelError(code=code, message=f"{code} boom")
out = kernel_client._reraise_kernel_error(err)
assert isinstance(out, expected_cls)
assert "boom" in str(out)
def test_unknown_code_falls_back_to_database_error():
err = _FakeKernelError(code="SomethingNew", message="…")
out = kernel_client._reraise_kernel_error(err)
assert isinstance(out, DatabaseError)
def test_reraise_forwards_structured_attributes():
err = _FakeKernelError(
code="SqlError",
message="table not found",
sql_state="42P01",
query_id="q-123",
)
out = kernel_client._reraise_kernel_error(err)
assert out.code == "SqlError"
assert out.sql_state == "42P01"
assert out.query_id == "q-123"
# Optional fields default to None on the source exception and
# come through verbatim on the re-raised side.
for attr in ("error_code", "vendor_code", "http_status"):
assert getattr(out, attr) is None
assert out.retryable is False
def test_reraise_forwards_extended_status_attributes():
"""display_message / diagnostic_info / error_details_json now cross
the PyO3 boundary (kernel #121) and must be forwarded onto the
re-raised exception so callers can read them."""
err = _FakeKernelError(
code="SqlError",
message="boom",
diagnostic_info="org.apache.spark...stack",
display_message="user-facing msg",
error_details_json='{"k":1}',
)
out = kernel_client._reraise_kernel_error(err)
assert out.diagnostic_info == "org.apache.spark...stack"
assert out.display_message == "user-facing msg"
assert out.error_details_json == '{"k":1}'
def test_server_operation_error_populates_context_like_thrift():
"""A SqlError maps to ServerOperationError; its ``context`` must
carry ``diagnostic-info`` (the Spark stack trace) and
``operation-id``, matching the Thrift backend so callers reading
``err.context["diagnostic-info"]`` work identically on use_kernel."""
err = _FakeKernelError(
code="SqlError",
message="table not found",
query_id="q-123",
diagnostic_info="org.apache.spark...stack",
)
out = kernel_client._reraise_kernel_error(err)
assert isinstance(out, ServerOperationError)
assert out.context["diagnostic-info"] == "org.apache.spark...stack"
assert out.context["operation-id"] == "q-123"
def test_kernel_error_chains_through_wrap():
"""``raise wrap_kernel_exception(...) from exc`` is the call-site
pattern; ``__cause__`` must be set to the original ``KernelError``
so users can dig out the structured fields via ``e.__cause__``."""
src = _FakeKernelError(code="SqlError", message="boom", sql_state="42P01")
try:
try:
raise src
except Exception as exc:
from databricks.sql.backend.kernel._errors import wrap_kernel_exception
raise wrap_kernel_exception("test_site", exc) from exc
except DatabaseError as out:
assert out.__cause__ is src
assert getattr(out, "sql_state", None) == "42P01"
else:
raise AssertionError("expected DatabaseError")
# ---------------------------------------------------------------------------
# State mapping
# ---------------------------------------------------------------------------
@pytest.mark.parametrize(
"kernel_state, expected",
[
("Pending", CommandState.PENDING),
("Running", CommandState.RUNNING),
("Succeeded", CommandState.SUCCEEDED),
("Failed", CommandState.FAILED),
("Cancelled", CommandState.CANCELLED),
("Closed", CommandState.CLOSED),
],
)
def test_state_to_command_state_mapping(kernel_state, expected):
assert kernel_client._STATE_TO_COMMAND_STATE[kernel_state] == expected
# ---------------------------------------------------------------------------
# Client lifecycle / guards (no live session)
# ---------------------------------------------------------------------------
def _make_client() -> kernel_client.KernelDatabricksClient:
"""Build a client with a PAT auth provider; the kernel ``Session``
isn't opened until ``open_session`` runs."""
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 test_no_open_session_guards_raise_interface_error():
"""Every method that depends on an open kernel session must
raise ``InterfaceError`` before any kernel call."""
c = _make_client()
cursor = MagicMock()
cursor.arraysize = 100
cursor.buffer_size_bytes = 1024
with pytest.raises(InterfaceError, match="open session"):
c.execute_command(
operation="SELECT 1",
session_id=MagicMock(),
max_rows=1,
max_bytes=1,
lz4_compression=False,
cursor=cursor,
use_cloud_fetch=False,
parameters=[],
async_op=False,
enforce_embedded_schema_correctness=False,
)
for method, kwargs in [
("get_catalogs", {}),
("get_schemas", {}),
("get_tables", {}),
("get_columns", {"catalog_name": "main"}),
]:
with pytest.raises(InterfaceError):
getattr(c, method)(
session_id=MagicMock(),
max_rows=1,
max_bytes=1,
cursor=cursor,
**kwargs,
)
# The async-state methods attach to the kernel session by id; they
# must also guard a closed/absent session before the kernel call.
cid = CommandId.from_sea_statement_id("any-id")
with pytest.raises(InterfaceError):
c.get_query_state(cid)
with pytest.raises(InterfaceError):
c.get_execution_result(cid, cursor=cursor)
def test_open_session_rejects_double_open(monkeypatch):
"""Two ``open_session`` calls on the same client must fail —
the kernel session is bound to a single open call."""
c = _make_client()
c._kernel_session = MagicMock() # pretend already open
with pytest.raises(InterfaceError, match="already has an open session"):
c.open_session(session_configuration=None, catalog=None, schema=None)
@pytest.mark.parametrize(
"kwargs, expected_flag",
[
({}, False), # default → arrow-native → kernel JSON off
({"_use_arrow_native_complex_types": True}, False),
({"_use_arrow_native_complex_types": False}, True),
],
)
def test_open_session_passes_complex_types_as_json_to_kernel(
monkeypatch, kwargs, expected_flag
):
"""``_use_arrow_native_complex_types=False`` flips the kernel's
``complex_types_as_json`` post-processor on; the default and
explicit ``True`` both leave it off. The flag is inverted at the
boundary because the connector's option is "native Arrow"-shaped
and the kernel's is "rewrite to JSON strings"-shaped."""
captured = {}
def fake_session(**kw):
captured.update(kw)
sess = MagicMock()
sess.session_id = "sess-id"
return sess
monkeypatch.setattr(kernel_client._kernel, "Session", fake_session)
c = kernel_client.KernelDatabricksClient(
server_hostname="example.cloud.databricks.com",
http_path="/sql/1.0/warehouses/abc",
auth_provider=AccessTokenAuthProvider("dapi-test"),
ssl_options=None,
**kwargs,
)
c.open_session(session_configuration=None, catalog=None, schema=None)
assert captured.get("complex_types_as_json") is expected_flag
def test_execute_command_forwards_parameters_to_bind_param():
"""``execute_command(parameters=[...])`` routes each parameter
through ``bind_tspark_params`` onto the kernel statement before
``execute()`` is called. Replaces the prior ``NotSupportedError``
rejection now that the kernel-side ``Statement.bind_param`` is
live (kernel PR #18)."""
from databricks.sql.thrift_api.TCLIService import ttypes
c = _make_client()
c._kernel_session = MagicMock()
cursor = MagicMock()
cursor.arraysize = 100
cursor.buffer_size_bytes = 1024
# Stub the statement chain so we can observe bind_param calls
# without exercising the full ExecutedStatement → arrow_schema()
# path (that's covered elsewhere).
stmt = MagicMock()
stmt.bind_param = MagicMock()
stmt.execute.return_value = MagicMock(
statement_id="stmt-id",
arrow_schema=MagicMock(return_value=pa.schema([("x", pa.int64())])),
)
c._kernel_session.statement.return_value = stmt
p1 = ttypes.TSparkParameter(ordinal=True, name=None, type="INT")
p1.value = ttypes.TSparkParameterValue(stringValue="42")
p2 = ttypes.TSparkParameter(ordinal=True, name=None, type="STRING")
p2.value = ttypes.TSparkParameterValue(stringValue="hello")
c.execute_command(
operation="SELECT ?, ?",
session_id=MagicMock(),
max_rows=1,
max_bytes=1,
lz4_compression=False,
cursor=cursor,
use_cloud_fetch=False,
parameters=[p1, p2],
async_op=False,
enforce_embedded_schema_correctness=False,
)
# bind_param was called once per TSparkParameter, in order, with
# 1-based ordinals.
assert stmt.bind_param.call_args_list == [
((1, "42", "INT"), {}),
((2, "hello", "STRING"), {}),
]
# …and execute fired after binding.
assert stmt.execute.called
def test_execute_command_forwards_query_tags():
"""Statement-level query_tags are forwarded to the kernel statement
via set_query_tags (the kernel serialises them into the SEA
query_tags conf). Previously rejected with NotSupportedError; now
wired (kernel PR adding Statement.set_query_tags)."""
c = _make_client()
c._kernel_session = MagicMock()
cursor = MagicMock()
cursor.arraysize = 100
cursor.buffer_size_bytes = 1024
stmt = MagicMock()
stmt.set_sql = MagicMock()
stmt.set_query_tags = MagicMock()
stmt.execute.return_value = MagicMock(
statement_id="stmt-id",
arrow_schema=MagicMock(return_value=pa.schema([("x", pa.int64())])),
)
c._kernel_session.statement.return_value = stmt
tags = {"team": "platform", "production": None}
c.execute_command(
operation="SELECT 1",
session_id=MagicMock(),
max_rows=1,
max_bytes=1,
lz4_compression=False,
cursor=cursor,
use_cloud_fetch=False,
parameters=[],
async_op=False,
enforce_embedded_schema_correctness=False,
query_tags=tags,
)
stmt.set_query_tags.assert_called_once_with(tags)
assert stmt.execute.called
# ---------------------------------------------------------------------------
# Staging / volume operations — fail loud (not silently no-op)
# ---------------------------------------------------------------------------
@pytest.mark.parametrize(
"operation",
[
"PUT '/local/f.csv' INTO '/Volumes/c/s/v/f.csv'",
" put '/local/f' into '/Volumes/...'", # leading ws + lowercase
"GET '/Volumes/c/s/v/f' TO '/local/f'",
"REMOVE '/Volumes/c/s/v/f'",
],
)
def test_staging_operation_raises_not_supported(operation):
"""Volume/staging PUT/GET/REMOVE must FAIL LOUD on the kernel path
(the kernel can't perform the presigned-URL transfer; silently
no-opping would make ETL ingest stale/missing data)."""
c = _make_client()
c._kernel_session = MagicMock()
cursor = MagicMock()
cursor.arraysize = 100
cursor.buffer_size_bytes = 1024
with pytest.raises(NotSupportedError, match="staging"):
c.execute_command(
operation=operation,
session_id=MagicMock(),
max_rows=1,
max_bytes=1,
lz4_compression=False,
cursor=cursor,
use_cloud_fetch=False,
parameters=[],
async_op=False,
enforce_embedded_schema_correctness=False,
)
@pytest.mark.parametrize(
"operation, is_staging",
[
("PUT '/f' INTO '/v'", True),
("get '/v' to '/f'", True),
("REMOVE '/v'", True),
# Comment-prefixed staging ops MUST still be caught — otherwise
# they slip into the silent-no-op bug this guard exists to close
# (regression: review #1 on PR #825). ETL scripts commonly
# prefix statements with comments.
("-- upload the file\nPUT '/f' INTO '/v'", True),
("/* staging */ PUT '/f' INTO '/v'", True),
("/* c1 */\n -- c2\n get '/v' to '/f'", True), # mixed, multiple
(" \n\t PUT '/f' INTO '/v'", True), # leading whitespace only
("SELECT 'GET' AS x", False), # word appears but not leading verb
("SELECT * FROM puts", False),
("-- PUT in a comment\nSELECT 1", False), # verb only in comment
("/* PUT */ SELECT 1", False),
("INSERT INTO t VALUES (1)", False),
("", False),
("-- just a comment", False), # comment only, no statement
],
)
def test_is_staging_statement(operation, is_staging):
assert kernel_client._is_staging_statement(operation) is is_staging
# ---------------------------------------------------------------------------
# Sync cancel wiring (cursor.cancel() during a blocking execute())
# ---------------------------------------------------------------------------
def test_cancel_running_cursor_fires_registered_canceller():
"""A canceller registered for a cursor (as execute_command does
before the blocking call) is fired by cancel_running_cursor, which
returns True."""
c = _make_client()
cursor = MagicMock()
canceller = MagicMock()
with c._sync_cancellers_lock:
c._sync_cancellers[id(cursor)] = canceller
assert c.cancel_running_cursor(cursor) is True
canceller.cancel.assert_called_once_with()
def test_cancel_running_cursor_returns_false_when_none_registered():
"""No in-flight sync statement for this cursor -> False so the
Cursor can emit its 'no executing command' warning."""
c = _make_client()
assert c.cancel_running_cursor(MagicMock()) is False
def test_cancel_running_cursor_swallows_cancel_errors():
"""cursor.cancel() is best-effort (PEP-249); a failing canceller
(e.g. an early cancel before the statement id is observed, or a
transport hiccup on the cancel RPC) must NOT propagate out of
cancel(). It's swallowed+logged, and we still return True so the
Cursor doesn't emit the misleading 'no executing command' warning
(regression: review #2 on PR #825)."""
c = _make_client()
cursor = MagicMock()
canceller = MagicMock()
canceller.cancel.side_effect = RuntimeError("cancel RPC failed")
with c._sync_cancellers_lock:
c._sync_cancellers[id(cursor)] = canceller
# Does not raise, returns True (a canceller was present + attempted).
assert c.cancel_running_cursor(cursor) is True
canceller.cancel.assert_called_once_with()
def test_execute_command_registers_and_clears_sync_canceller():
"""The sync execute() path registers a StatementCanceller keyed by
the cursor before blocking, and clears it in the finally — so a
concurrent cancel can reach it mid-flight, and it doesn't leak."""
c = _make_client()
c._kernel_session = MagicMock()
cursor = MagicMock()
cursor.arraysize = 100
cursor.buffer_size_bytes = 1024
canceller = MagicMock()
stmt = MagicMock()
stmt.canceller.return_value = canceller
seen_during_execute = {}
def fake_execute():
# The canceller is registered *during* the blocking execute.
with c._sync_cancellers_lock:
seen_during_execute["registered"] = (
c._sync_cancellers.get(id(cursor)) is canceller
)
return MagicMock(
statement_id="stmt-id",
arrow_schema=MagicMock(return_value=pa.schema([("x", pa.int64())])),
)
stmt.execute.side_effect = fake_execute
c._kernel_session.statement.return_value = stmt
c.execute_command(
operation="SELECT 1",
session_id=MagicMock(),
max_rows=1,
max_bytes=1,
lz4_compression=False,
cursor=cursor,
use_cloud_fetch=False,
parameters=[],
async_op=False,
enforce_embedded_schema_correctness=False,
)
assert seen_during_execute["registered"] is True
# Cleared after execute returns — no leak.
with c._sync_cancellers_lock:
assert id(cursor) not in c._sync_cancellers
def test_sync_execute_does_not_close_statement_on_success():
"""On a successful sync execute(), the connector must NOT close the
parent kernel Statement — the kernel now auto-closes the server
statement when the result stream drains (with the executed handle's
Drop as backstop). A premature close() here broke lazy CloudFetch
chunk-link fetches for large paginated-link results."""
c = _make_client()
c._kernel_session = MagicMock()
cursor = MagicMock()
cursor.arraysize = 100
cursor.buffer_size_bytes = 1024
stmt = MagicMock()
stmt.execute.return_value = MagicMock(
statement_id="stmt-id",
arrow_schema=MagicMock(return_value=pa.schema([("x", pa.int64())])),
)
c._kernel_session.statement.return_value = stmt
c.execute_command(
operation="SELECT 1",
session_id=MagicMock(),
max_rows=1,
max_bytes=1,
lz4_compression=False,
cursor=cursor,
use_cloud_fetch=False,
parameters=[],
async_op=False,
enforce_embedded_schema_correctness=False,
)
# The kernel owns the statement lifecycle post-execute; connector
# leaves it alone (kernel auto-close-on-drain + Drop backstop).
stmt.close.assert_not_called()
def test_sync_execute_closes_statement_on_failure():
"""On the error path (execute raised, no executed handle / result
set produced), the connector still closes the parent Statement so
it isn't leaked."""
c = _make_client()
c._kernel_session = MagicMock()
cursor = MagicMock()
cursor.arraysize = 100
cursor.buffer_size_bytes = 1024
stmt = MagicMock()
stmt.execute.side_effect = RuntimeError("boom")
c._kernel_session.statement.return_value = stmt
with pytest.raises(Exception):
c.execute_command(
operation="SELECT 1",
session_id=MagicMock(),
max_rows=1,
max_bytes=1,
lz4_compression=False,
cursor=cursor,
use_cloud_fetch=False,
parameters=[],
async_op=False,
enforce_embedded_schema_correctness=False,
)
stmt.close.assert_called_once_with()
def test_get_columns_accepts_none_catalog():
"""The kernel's `list_columns` honours `catalog=None` by issuing
`SHOW COLUMNS IN ALL CATALOGS` server-side. The connector should
pass `None` through rather than rejecting it, matching the Thrift
backend's `getColumns(null, …)` behaviour."""
c = _make_client()
c._kernel_session = MagicMock()
cursor = MagicMock()
cursor.arraysize = 100
cursor.buffer_size_bytes = 1024
cursor.connection = MagicMock()
# `list_columns` returns a stream the result-set wrapper will try
# to call `arrow_schema()` on; give it a minimal fake.
fake_stream = MagicMock()
fake_stream.arrow_schema.return_value = MagicMock(__iter__=lambda self: iter([]))
c._kernel_session.metadata.return_value.list_columns.return_value = fake_stream
c.get_columns(
session_id=MagicMock(),
max_rows=1,
max_bytes=1,
cursor=cursor,
catalog_name=None,
)
# `list_columns` should be called with catalog=None, not rejected.
c._kernel_session.metadata.return_value.list_columns.assert_called_once_with(
catalog=None,
schema_pattern=None,
table_pattern=None,
column_pattern=None,
)
# ---------------------------------------------------------------------------
# Async handle bookkeeping
# ---------------------------------------------------------------------------
def test_cancel_command_tolerant_when_handle_missing():
"""``cancel_command`` is documented to be a no-op when there's
no tracked async handle (matches Thrift's tolerance)."""
c = _make_client()
fake_command_id = CommandId.from_sea_statement_id("not-tracked")
c.cancel_command(fake_command_id) # must not raise
def test_close_command_tolerant_when_handle_missing():
c = _make_client()
fake_command_id = CommandId.from_sea_statement_id("not-tracked")
c.close_command(fake_command_id) # must not raise
def _attach_returns(c, *, status=None, status_error=None, await_result=None):
"""Wire ``_kernel_session.attach_async_statement`` to return a fake
handle. ``status`` is a ``(state, failure)`` tuple for ``handle.status()``;
``status_error`` makes ``attach`` itself raise (e.g. NotFound);
``await_result`` sets ``handle.await_result()`` return value."""
c._kernel_session = MagicMock()
if status_error is not None:
c._kernel_session.attach_async_statement.side_effect = status_error
return None
handle = MagicMock()
if status is not None:
handle.status.return_value = status
if await_result is not None:
handle.await_result.return_value = await_result
c._kernel_session.attach_async_statement.return_value = handle
return handle
def test_get_query_state_returns_succeeded_when_server_404s():
"""An id the server doesn't recognise (sync command whose id was
never a standalone server statement, or an async command closed and
aged out of the result TTL) surfaces as a NotFound KernelError from
``attach``; the client maps that to SUCCEEDED so the cursor's
polling loop terminates cleanly."""
c = _make_client()
_attach_returns(c, status_error=_FakeKernelError(code="NotFound"))
cid = CommandId.from_sea_statement_id("sync-only")
assert c.get_query_state(cid) == CommandState.SUCCEEDED
def test_get_query_state_returns_closed_from_server():
"""A closed-but-not-yet-GC'd async command: the server still answers
GetStatementStatus with state=CLOSED (200), which flows through the
state map to ``CommandState.CLOSED`` — no connector-side
closed-state bookkeeping."""
c = _make_client()
_attach_returns(c, status=("Closed", None))
cid = CommandId.from_sea_statement_id("closed-async")
assert c.get_query_state(cid) == CommandState.CLOSED
def test_get_query_state_propagates_non_not_found_error():
"""A transient/other error from ``attach`` (NOT NotFound) must not be
silently swallowed as a terminal state — it propagates as a mapped
PEP 249 exception so the caller can retry / surface it."""
c = _make_client()
_attach_returns(c, status_error=_FakeKernelError(code="Unavailable"))
cid = CommandId.from_sea_statement_id("flaky")
with pytest.raises(DatabaseError):
c.get_query_state(cid)
def test_get_execution_result_attaches_by_id():
"""``get_execution_result`` re-attaches to the statement by id and
awaits its result — no connector-side handle lookup."""
c = _make_client()
fake_stream = MagicMock()
fake_stream.arrow_schema.return_value = pa.schema([("n", pa.int64())])
handle = _attach_returns(c, await_result=fake_stream)
cursor = MagicMock()
cursor.arraysize = 100
cursor.buffer_size_bytes = 1024
cid = CommandId.from_sea_statement_id("async-1")
rs = c.get_execution_result(cid, cursor=cursor)
assert rs is not None
c._kernel_session.attach_async_statement.assert_called_with("async-1")
handle.await_result.assert_called_once_with()
def test_get_execution_result_maps_not_found_to_programming_error():
"""An unknown / aged-out id surfaces the kernel's NotFound as a
mapped PEP 249 exception rather than a raw error."""
c = _make_client()
_attach_returns(c, status_error=_FakeKernelError(code="NotFound"))
cid = CommandId.from_sea_statement_id("gone")
with pytest.raises(DatabaseError):
c.get_execution_result(cid, cursor=MagicMock())
def test_cancel_command_reraises_kernel_error():
c = _make_client()
fake_handle = MagicMock()
fake_handle.cancel.side_effect = _FakeKernelError(code="Unavailable")
cid = CommandId.from_sea_statement_id("abc")
c._async_handles[cid.guid] = fake_handle
with pytest.raises(OperationalError):
c.cancel_command(cid)
def test_close_command_reraises_kernel_error():
c = _make_client()
fake_handle = MagicMock()
fake_handle.close.side_effect = _FakeKernelError(code="Internal")
cid = CommandId.from_sea_statement_id("abc")
c._async_handles[cid.guid] = fake_handle
with pytest.raises(DatabaseError):
c.close_command(cid)
# The handle is popped before the kernel call, so a subsequent
# close_command is tolerantly a no-op.
c.close_command(cid)
def test_get_query_state_raises_on_failed_state_with_failure():
c = _make_client()
_attach_returns(
c, status=("Failed", _FakeKernelError(code="SqlError", message="bad"))
)
cid = CommandId.from_sea_statement_id("abc")
with pytest.raises(DatabaseError, match="bad"):
c.get_query_state(cid)
def test_get_query_state_handles_non_baseexception_failure():
"""If the kernel's status() ever returns a ``failure`` that isn't
a real ``KernelError`` (struct, dict, custom type — kernel API
drift), ``get_query_state`` must still surface a mapped PEP 249
exception. The naive ``raise ... from failure`` would raise
``TypeError: exception causes must derive from BaseException``;
the wrap helper deals with it."""
c = _make_client()
# ``failure`` is a plain dict (not BaseException) — simulates a
# kernel binding that exposes the failure as a structured value.
_attach_returns(c, status=("Failed", {"code": "Internal", "msg": "weird"}))
cid = CommandId.from_sea_statement_id("xyz")
# Must surface as a PEP 249 exception (OperationalError via the
# wrap helper's fallback path), not TypeError.
with pytest.raises(OperationalError):
c.get_query_state(cid)
def test_get_query_state_returns_state_when_no_failure():
c = _make_client()
_attach_returns(c, status=("Running", None))
cid = CommandId.from_sea_statement_id("abc")
assert c.get_query_state(cid) == CommandState.RUNNING
# ---------------------------------------------------------------------------
# Misc
# ---------------------------------------------------------------------------
def test_max_download_threads_is_nonzero():
"""Property is consulted by Thrift code paths that don't run for
``use_kernel=True``; a non-zero default avoids divide-by-zero."""
c = _make_client()
assert c.max_download_threads > 0
def test_synthetic_command_id_is_uuid_shaped():
"""Synthetic metadata command IDs are plain hex UUIDs (no
``metadata-`` prefix) so anything reading ``cursor.query_id``
downstream sees a parseable shape."""
c = _make_client()
cid = c._synthetic_command_id()
# 32-char lowercase hex
assert len(cid.guid) == 32
int(cid.guid, 16) # raises if non-hex
def test_close_session_clears_async_handles_even_if_close_fails():
"""Per-handle close errors are logged but don't prevent the
rest of the close-session sweep from completing, and the dict
is cleared either way."""
c = _make_client()
good = MagicMock()
bad = MagicMock()
bad.close.side_effect = _FakeKernelError(code="Unavailable")
c._async_handles["a"] = good
c._async_handles["b"] = bad
c._kernel_session = MagicMock()
c.close_session(MagicMock())
assert c._async_handles == {}
assert good.close.called
assert bad.close.called
def test_close_session_closes_and_drops_swept_handles():
"""Close-session closes every tracked async handle (firing its
server-side CloseStatement) and drops it from the keep-alive map.
There is no connector-side closed-state bookkeeping — a subsequent
``get_query_state`` re-attaches by id and reads CLOSED from the
server."""
c = _make_client()
handle = MagicMock()
cid = CommandId.from_sea_statement_id("xyz")
c._async_handles[cid.guid] = handle
c._kernel_session = MagicMock()
c.close_session(MagicMock())
assert handle.close.called
assert c._async_handles == {}
# ---------------------------------------------------------------------------
# CLOSED command-state comes from the server (re-attach by id)
# ---------------------------------------------------------------------------
def test_get_query_state_returns_closed_after_close_command():
"""After ``close_command`` fires the server-side CloseStatement, a
subsequent ``get_query_state`` re-attaches by id and the server
reports CLOSED (200 state=CLOSED until the result TTL elapses). No
connector-side closed-state tracking — the server is the source of
truth."""
c = _make_client()
c._kernel_session = MagicMock()
handle = MagicMock()
cid = CommandId.from_sea_statement_id("async-1")
c._async_handles[cid.guid] = handle
c.close_command(cid)
assert handle.close.called
# Re-attach now reports CLOSED from the server.
attached = MagicMock()
attached.status.return_value = ("Closed", None)
c._kernel_session.attach_async_statement.return_value = attached
assert c.get_query_state(cid) == CommandState.CLOSED
# ---------------------------------------------------------------------------
# PyO3 native exceptions (M2) — non-KernelError wrapping
# ---------------------------------------------------------------------------
def test_pyo3_native_exception_wrapped_as_operational_error():
"""A PyO3 boundary error that is *not* a ``KernelError`` (e.g.
``TypeError`` from argument conversion) must surface as a PEP
249 exception, not propagate raw to connector callers."""
c = _make_client()
c._kernel_session = MagicMock()
cursor = MagicMock()
cursor.arraysize = 100
cursor.buffer_size_bytes = 1024
# Statement chain succeeds, but ``execute`` raises a raw
# ``TypeError`` (simulating PyO3 argument-conversion failure).
stmt = MagicMock()
stmt.execute.side_effect = TypeError("argument 'foo' must be str, not int")
c._kernel_session.statement.return_value = stmt
with pytest.raises(
OperationalError, match="Unexpected error from databricks_sql_kernel"
):
c.execute_command(
operation="SELECT 1",
session_id=MagicMock(),
max_rows=1,
max_bytes=1,
lz4_compression=False,
cursor=cursor,
use_cloud_fetch=False,
parameters=[],
async_op=False,
enforce_embedded_schema_correctness=False,
)
def test_pyo3_native_exception_wrapped_for_metadata_calls():
"""Same wrapping for every metadata method."""
c = _make_client()
c._kernel_session = MagicMock()
md = c._kernel_session.metadata.return_value
md.list_catalogs.side_effect = ValueError("bad PyO3 arg")
cursor = MagicMock()
cursor.arraysize = 100
cursor.buffer_size_bytes = 1024
with pytest.raises(OperationalError):
c.get_catalogs(session_id=MagicMock(), max_rows=1, max_bytes=1, cursor=cursor)
# ---------------------------------------------------------------------------
# Schema-on-construct race (M3) — KernelError during arrow_schema()
# ---------------------------------------------------------------------------
def test_kernel_error_during_result_set_construction_is_mapped():
"""``KernelResultSet.__init__`` calls
``kernel_handle.arrow_schema()`` which can itself raise a
``KernelError``. The connector must catch that and surface a
mapped PEP 249 exception, not let the raw ``KernelError``
escape."""
c = _make_client()
c._kernel_session = MagicMock()