forked from omnigent-ai/omnigent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_databricks_executor.py
More file actions
1784 lines (1442 loc) · 62.6 KB
/
Copy pathtest_databricks_executor.py
File metadata and controls
1784 lines (1442 loc) · 62.6 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
"""Tests for DatabricksExecutor with a mock OpenAI client."""
import asyncio
import json
import sys
import unittest
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
import databricks.sdk.config as _sdk_config_mod
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from omnigent.inner.databricks_executor import (
DatabricksExecutor,
_convert_messages,
_convert_tools_to_openai,
)
from omnigent.inner.executor import (
ExecutorConfig,
ExecutorError,
TextChunk,
ToolCallRequest,
TurnComplete,
)
def _run(coro):
loop = asyncio.new_event_loop()
try:
return loop.run_until_complete(coro)
finally:
loop.run_until_complete(loop.shutdown_asyncgens())
loop.run_until_complete(loop.shutdown_default_executor())
loop.close()
# ---------------------------------------------------------------------------
# Fake streaming response objects (mimicking OpenAI streaming types)
# ---------------------------------------------------------------------------
@dataclass
class FakeFunctionDelta:
name: str | None = None
arguments: str | None = None
@dataclass
class FakeToolCallDelta:
index: int = 0
function: FakeFunctionDelta | None = None
@dataclass
class FakeDelta:
"""
Minimal stream-delta test double for DatabricksExecutor.
:param content: Raw ``delta.content`` payload, e.g. ``"hello"`` or
``[{"type": "reasoning", "summary": [...]}]``.
:param tool_calls: Optional streamed tool-call deltas.
"""
content: Any = None
tool_calls: list[FakeToolCallDelta] | None = None
@dataclass
class FakeStreamChoice:
delta: FakeDelta = field(default_factory=FakeDelta)
index: int = 0
finish_reason: str | None = None
@dataclass
class FakeStreamChunk:
choices: list[FakeStreamChoice] = field(default_factory=list)
def _make_text_stream(text: str) -> list[FakeStreamChunk]:
"""Create a stream that yields text content then stops."""
chunks = []
# Yield text in a single chunk for simplicity
if text:
chunks.append(FakeStreamChunk(choices=[FakeStreamChoice(delta=FakeDelta(content=text))]))
# Final chunk with finish_reason=stop
chunks.append(FakeStreamChunk(choices=[FakeStreamChoice(finish_reason="stop")]))
return chunks
def _make_tool_call_stream(
tool_calls: list[tuple[str, str]],
text: str | None = None,
) -> list[FakeStreamChunk]:
"""Create a stream that yields tool calls.
Args:
tool_calls: list of (name, arguments_json) tuples
text: optional text content to include before tool calls
"""
chunks = []
if text:
chunks.append(FakeStreamChunk(choices=[FakeStreamChoice(delta=FakeDelta(content=text))]))
for idx, (name, args) in enumerate(tool_calls):
chunks.append(
FakeStreamChunk(
choices=[
FakeStreamChoice(
delta=FakeDelta(
tool_calls=[
FakeToolCallDelta(
index=idx,
function=FakeFunctionDelta(name=name, arguments=args),
)
]
)
)
]
)
)
# Final chunk with finish_reason=tool_calls
chunks.append(FakeStreamChunk(choices=[FakeStreamChoice(finish_reason="tool_calls")]))
return chunks
class FakeCompletions:
"""Mimics client.chat.completions."""
def __init__(self, stream_chunks: list[FakeStreamChunk]):
self._chunks = stream_chunks
self.last_kwargs: dict[str, Any] = {}
def create(self, **kwargs) -> list[FakeStreamChunk]:
self.last_kwargs = kwargs
return iter(self._chunks)
class FakeChat:
def __init__(self, completions: FakeCompletions):
self.completions = completions
class FakeClient:
"""Mimics the OpenAI client."""
def __init__(self, stream_chunks: list[FakeStreamChunk]):
self.chat = FakeChat(FakeCompletions(stream_chunks))
def test_kimi_reasoning_content_blocks_are_not_text_chunks() -> None:
"""
Kimi streams reasoning summaries as ``delta.content`` block lists before
the assistant answer; the executor must not hand those lists to
:class:`TextChunk` or append them to the final assistant response.
"""
async def _t() -> None:
"""Drive DatabricksExecutor over a Kimi-shaped stream."""
chunks = [
FakeStreamChunk(
choices=[
FakeStreamChoice(
delta=FakeDelta(
content=[
{
"type": "reasoning",
"summary": [{"type": "summary_text", "text": "Thinking"}],
}
]
)
)
]
),
FakeStreamChunk(choices=[FakeStreamChoice(delta=FakeDelta(content="Hello"))]),
FakeStreamChunk(choices=[FakeStreamChoice(finish_reason="stop")]),
]
executor = DatabricksExecutor(client=FakeClient(chunks))
events = [
e
async for e in executor.run_turn(
messages=[{"role": "user", "content": "hi"}],
tools=[],
system_prompt="Be helpful.",
config=ExecutorConfig(model="databricks-kimi-k2-6"),
)
]
text_events = [e for e in events if isinstance(e, TextChunk)]
turn_events = [e for e in events if isinstance(e, TurnComplete)]
assert [e.text for e in text_events] == ["Hello"]
assert all(isinstance(e.text, str) for e in text_events)
assert len(turn_events) == 1
assert turn_events[0].response == "Hello"
_run(_t())
def test_text_content_block_lists_are_collapsed_to_text_chunks() -> None:
"""
Providers may stream assistant-visible text as content block lists; those
recognized text blocks must still produce normal string
:class:`TextChunk` events and the correct final response.
"""
async def _t() -> None:
"""Drive DatabricksExecutor over text content block deltas."""
chunks = [
FakeStreamChunk(
choices=[
FakeStreamChoice(
delta=FakeDelta(
content=[
{"type": "text", "text": "Hello"},
{"type": "output_text", "text": " world"},
]
)
)
]
),
FakeStreamChunk(choices=[FakeStreamChoice(finish_reason="stop")]),
]
executor = DatabricksExecutor(client=FakeClient(chunks))
events = [
e
async for e in executor.run_turn(
messages=[{"role": "user", "content": "hi"}],
tools=[],
system_prompt="Be helpful.",
config=ExecutorConfig(model="block-list-model"),
)
]
text_events = [e for e in events if isinstance(e, TextChunk)]
turn_events = [e for e in events if isinstance(e, TurnComplete)]
assert [e.text for e in text_events] == ["Hello world"]
assert len(turn_events) == 1
assert turn_events[0].response == "Hello world"
_run(_t())
# ---------------------------------------------------------------------------
# Tests: message and tool conversion helpers
# ---------------------------------------------------------------------------
class TestConvertTools(unittest.TestCase):
def test_basic_tool(self):
tools = [
{
"name": "sql",
"description": "Run SQL",
"parameters": {"type": "object", "properties": {"q": {"type": "string"}}},
}
]
result = _convert_tools_to_openai(tools)
self.assertEqual(len(result), 1)
self.assertEqual(result[0]["type"], "function")
self.assertEqual(result[0]["function"]["name"], "sql")
self.assertIn("properties", result[0]["function"]["parameters"])
def test_tool_without_parameters(self):
tools = [{"name": "ping", "description": "Ping"}]
result = _convert_tools_to_openai(tools)
self.assertEqual(result[0]["function"]["parameters"], {"type": "object", "properties": {}})
def test_preserves_required_args_in_async_tool_schema(self):
tools = [
{
"name": "sys_call_async",
"description": "Async call",
"parameters": {
"type": "object",
"properties": {
"tool": {"type": "string"},
"args": {
"type": "object",
"default": {},
"properties": {
"example_key": {
"anyOf": [{"type": "string"}],
},
},
"additionalProperties": {
"anyOf": [{"type": "string"}],
},
},
},
"required": ["tool", "args"],
},
}
]
result = _convert_tools_to_openai(tools)
self.assertEqual(
result[0]["function"]["parameters"]["required"],
["tool", "args"],
)
self.assertIn(
"example_key",
result[0]["function"]["parameters"]["properties"]["args"]["properties"],
)
def test_preserves_required_args_in_session_send_schema(self):
tools = [
{
"name": "sys_session_send",
"description": "Session send",
"parameters": {
"type": "object",
"properties": {
"tool": {"type": "string"},
"session": {"type": "string"},
"args": {"type": "object", "additionalProperties": True},
},
"required": ["tool", "session", "args"],
},
}
]
result = _convert_tools_to_openai(tools)
self.assertEqual(
result[0]["function"]["parameters"]["required"],
["tool", "session", "args"],
)
def test_empty_tools(self):
self.assertEqual(_convert_tools_to_openai([]), [])
def test_invalid_tool_name_is_normalized_for_provider(self):
tools = [{"name": "sys_runtime_execute", "description": "Run code"}]
result = _convert_tools_to_openai(tools)
self.assertEqual(result[0]["function"]["name"], "sys_runtime_execute")
self.assertEqual(result[0]["function"]["description"], "Run code")
class TestConvertMessages(unittest.TestCase):
def test_system_prompt(self):
result = _convert_messages([], "You are helpful.")
self.assertEqual(len(result), 1)
self.assertEqual(result[0]["role"], "system")
self.assertEqual(result[0]["content"], "You are helpful.")
def test_user_and_assistant(self):
msgs = [
{"role": "user", "content": "Hello"},
{"role": "assistant", "content": "Hi there!"},
]
result = _convert_messages(msgs, "")
self.assertEqual(len(result), 2)
self.assertEqual(result[0]["role"], "user")
self.assertEqual(result[1]["role"], "assistant")
def test_tool_call_and_result_pair(self):
msgs = [
{"role": "user", "content": "Run a query"},
{"role": "tool_call", "content": {"tool": "sql", "args": {"q": "SELECT 1"}}},
{"role": "tool_result", "content": {"rows": [1]}},
]
result = _convert_messages(msgs, "sys")
# system + user + assistant(tool_calls) + tool
self.assertEqual(len(result), 4)
self.assertEqual(result[0]["role"], "system")
self.assertEqual(result[1]["role"], "user")
self.assertEqual(result[2]["role"], "assistant")
def test_invalid_tool_name_is_normalized_in_history_replay(self):
msgs = [
{
"role": "tool_call",
"content": {"tool": "sys_runtime_execute", "args": {"code": "print(1)"}},
},
{"role": "tool_result", "content": {"stdout": "1\n"}},
]
result = _convert_messages(msgs, "")
self.assertEqual(result[0]["tool_calls"][0]["function"]["name"], "sys_runtime_execute")
self.assertEqual(result[1]["role"], "tool")
def test_orphan_tool_result(self):
msgs = [{"role": "tool_result", "content": "some result"}]
result = _convert_messages(msgs, "")
self.assertEqual(len(result), 1)
self.assertIn("tool result", result[0]["content"])
def test_tool_call_content_as_string(self):
"""tool_call content might be a JSON string instead of dict."""
msgs = [
{
"role": "tool_call",
"content": json.dumps({"tool": "search", "args": {"q": "test"}}),
},
{"role": "tool_result", "content": "found it"},
]
result = _convert_messages(msgs, "")
self.assertEqual(result[0]["tool_calls"][0]["function"]["name"], "search")
# ---------------------------------------------------------------------------
# Tests: DatabricksExecutor with fake streaming client
# ---------------------------------------------------------------------------
class TestDatabricksExecutorTextResponse(unittest.TestCase):
def test_simple_text_response(self):
async def _t():
chunks = _make_text_stream("Hello world!")
executor = DatabricksExecutor(client=FakeClient(chunks))
events = [
e
async for e in executor.run_turn(
messages=[{"role": "user", "content": "Hi"}],
tools=[],
system_prompt="Be nice.",
config=ExecutorConfig(model="test-model"),
)
]
# TextChunk + TurnComplete
text_events = [e for e in events if isinstance(e, TextChunk)]
turn_events = [e for e in events if isinstance(e, TurnComplete)]
self.assertEqual(len(text_events), 1)
self.assertEqual(text_events[0].text, "Hello world!")
self.assertEqual(len(turn_events), 1)
self.assertEqual(turn_events[0].response, "Hello world!")
_run(_t())
def test_empty_content(self):
async def _t():
chunks = _make_text_stream("")
executor = DatabricksExecutor(client=FakeClient(chunks))
events = [e async for e in executor.run_turn([], [], "")]
turn_events = [e for e in events if isinstance(e, TurnComplete)]
self.assertEqual(len(turn_events), 1)
self.assertEqual(turn_events[0].response, "")
_run(_t())
class TestDatabricksExecutorToolCalls(unittest.TestCase):
def test_single_tool_call(self):
async def _t():
chunks = _make_tool_call_stream([("sql_query", '{"query": "SELECT 1"}')])
executor = DatabricksExecutor(client=FakeClient(chunks))
events = [
e
async for e in executor.run_turn(
[{"role": "user", "content": "query"}],
[{"name": "sql_query", "description": "Run SQL"}],
"sys",
)
]
tool_events = [e for e in events if isinstance(e, ToolCallRequest)]
self.assertEqual(len(tool_events), 1)
self.assertEqual(tool_events[0].name, "sql_query")
self.assertEqual(tool_events[0].args["query"], "SELECT 1")
_run(_t())
def test_multiple_tool_calls(self):
async def _t():
chunks = _make_tool_call_stream(
[
("tool_a", '{"x": 1}'),
("tool_b", '{"y": 2}'),
]
)
executor = DatabricksExecutor(client=FakeClient(chunks))
events = [e async for e in executor.run_turn([], [], "")]
tool_events = [e for e in events if isinstance(e, ToolCallRequest)]
self.assertEqual(len(tool_events), 2)
self.assertEqual(tool_events[0].name, "tool_a")
self.assertEqual(tool_events[1].name, "tool_b")
_run(_t())
def test_tool_call_with_text(self):
"""Model returns both text and tool calls."""
async def _t():
chunks = _make_tool_call_stream(
[("search", "{}")],
text="Let me search for that.",
)
executor = DatabricksExecutor(client=FakeClient(chunks))
events = [e async for e in executor.run_turn([], [], "")]
names = [type(e).__name__ for e in events]
self.assertIn("ToolCallRequest", names)
self.assertIn("TextChunk", names)
self.assertNotIn("TurnComplete", names)
_run(_t())
def test_malformed_arguments(self):
"""If arguments aren't valid JSON, put them in a 'raw' key."""
async def _t():
chunks = _make_tool_call_stream([("t", "not json")])
executor = DatabricksExecutor(client=FakeClient(chunks))
events = [e async for e in executor.run_turn([], [], "")]
tool_events = [e for e in events if isinstance(e, ToolCallRequest)]
self.assertEqual(len(tool_events), 1)
self.assertEqual(tool_events[0].args["raw"], "not json")
_run(_t())
class TestDatabricksExecutorErrors(unittest.TestCase):
def test_empty_stream(self):
"""Stream with no chunks yields a TurnComplete with empty text."""
async def _t():
executor = DatabricksExecutor(client=FakeClient([]))
events = [e async for e in executor.run_turn([], [], "")]
self.assertEqual(len(events), 1)
self.assertIsInstance(events[0], TurnComplete)
self.assertEqual(events[0].response, "")
_run(_t())
def test_api_exception(self):
async def _t():
class ExplodingClient:
class chat:
class completions:
@staticmethod
def create(**kwargs):
raise RuntimeError("API down")
executor = DatabricksExecutor(client=ExplodingClient())
events = [e async for e in executor.run_turn([], [], "")]
self.assertEqual(len(events), 1)
self.assertIsInstance(events[0], ExecutorError)
self.assertIn("API down", events[0].message)
_run(_t())
class TestDatabricksExecutorConfig(unittest.TestCase):
def test_passes_model_and_params(self):
"""Verify the executor passes model, temperature, max_tokens to the API."""
async def _t():
chunks = _make_text_stream("ok")
client = FakeClient(chunks)
executor = DatabricksExecutor(client=client)
config = ExecutorConfig(
model="claude-sonnet-4",
temperature=0.7,
max_tokens=2048,
)
[
e
async for e in executor.run_turn(
[{"role": "user", "content": "Hi"}],
[],
"system prompt",
config=config,
)
]
kwargs = client.chat.completions.last_kwargs
self.assertEqual(kwargs["model"], "claude-sonnet-4")
self.assertEqual(kwargs["temperature"], 0.7)
self.assertEqual(kwargs["max_tokens"], 2048)
self.assertTrue(kwargs["stream"])
_run(_t())
def test_default_model(self):
"""When no model is specified, falls back to databricks-claude-sonnet-4-6."""
async def _t():
chunks = _make_text_stream("ok")
client = FakeClient(chunks)
executor = DatabricksExecutor(client=client)
[e async for e in executor.run_turn([], [], "", config=ExecutorConfig())]
self.assertEqual(
client.chat.completions.last_kwargs["model"],
"databricks-claude-sonnet-4-6",
)
_run(_t())
def test_tools_passed_in_openai_format(self):
async def _t():
chunks = _make_text_stream("ok")
client = FakeClient(chunks)
executor = DatabricksExecutor(client=client)
tools = [
{
"name": "sql",
"description": "Run SQL",
"parameters": {"type": "object", "properties": {}},
}
]
[e async for e in executor.run_turn([], tools, "")]
passed_tools = client.chat.completions.last_kwargs["tools"]
self.assertEqual(len(passed_tools), 1)
self.assertEqual(passed_tools[0]["type"], "function")
self.assertEqual(passed_tools[0]["function"]["name"], "sql")
_run(_t())
class TestDatabricksExecutorMultiTurn(unittest.TestCase):
"""Test a realistic multi-turn scenario: user asks -> tool call -> tool result -> response."""
def test_tool_call_then_response(self):
async def _t():
# Turn 1: model wants to call a tool
chunks1 = _make_tool_call_stream([("search", '{"q": "test"}')])
client1 = FakeClient(chunks1)
executor = DatabricksExecutor(client=client1)
events1 = [
e
async for e in executor.run_turn(
[{"role": "user", "content": "search for test"}],
[{"name": "search", "description": "Search"}],
"sys",
)
]
tool_events = [e for e in events1 if isinstance(e, ToolCallRequest)]
self.assertEqual(len(tool_events), 1)
self.assertEqual(tool_events[0].name, "search")
# Turn 2: after tool result, model gives final answer
chunks2 = _make_text_stream("Found 3 results.")
executor._client = FakeClient(chunks2)
events2 = [
e
async for e in executor.run_turn(
[
{"role": "user", "content": "search for test"},
{
"role": "tool_call",
"content": {"tool": "search", "args": {"q": "test"}},
},
{"role": "tool_result", "content": {"results": ["a", "b", "c"]}},
],
[{"name": "search", "description": "Search"}],
"sys",
)
]
turn_events = [e for e in events2 if isinstance(e, TurnComplete)]
self.assertEqual(len(turn_events), 1)
self.assertEqual(turn_events[0].response, "Found 3 results.")
_run(_t())
def test_interrupt_session_closes_active_stream(self):
class ClosableStream:
def __init__(self) -> None:
self.closed = False
def close(self) -> None:
self.closed = True
async def _t():
executor = DatabricksExecutor(client=FakeClient([]))
state = executor._get_or_create_session_state("s1")
state.active_stream = ClosableStream()
interrupted = await executor.interrupt_session("s1")
self.assertTrue(interrupted)
self.assertTrue(state.interrupt_requested)
self.assertTrue(state.active_stream.closed)
_run(_t())
# ---------------------------------------------------------------------------
# Credential resolution (_read_databrickscfg) — function-based pytest tests.
#
# These exercise the OAuth bug fix: _read_databrickscfg now delegates to the
# databricks-sdk so OAuth profiles (auth_type: databricks-cli) return a fresh
# minted bearer instead of the stale ``token`` field in ~/.databrickscfg.
# ---------------------------------------------------------------------------
# Imports below are intentionally at the bottom because the pytest-based section
# is appended to the pre-existing unittest module above.
import textwrap # noqa: E402
from pathlib import Path as _Path # noqa: E402
import pytest # noqa: E402
from omnigent.inner.databricks_executor import ( # noqa: E402
DatabricksAuthError,
_DatabricksBearerAuth,
_read_databrickscfg,
_read_databrickscfg_file_fallback,
_read_databrickscfg_host,
)
_AUTH_ENV_VARS: tuple[str, ...] = (
"DATABRICKS_HOST",
"DATABRICKS_TOKEN",
"DATABRICKS_CONFIG_PROFILE",
"DATABRICKS_CONFIG_FILE",
"DATABRICKS_CLIENT_ID",
"DATABRICKS_CLIENT_SECRET",
"DATABRICKS_AUTH_TYPE",
)
@pytest.fixture
def clean_databricks_env(monkeypatch: pytest.MonkeyPatch) -> None:
"""
Clear every DATABRICKS_* env var that affects credential resolution.
The agent harness that runs these tests may have e.g. ``DATABRICKS_TOKEN``
exported for the coding agent itself — which would override profile-based
resolution in the SDK and confuse these tests.
"""
for var in _AUTH_ENV_VARS:
monkeypatch.delenv(var, raising=False)
def _raise_offline_host_metadata(host: str) -> None:
"""Stand-in for ``databricks.sdk.config.get_host_metadata`` that fails fast.
:param host: Workspace URL the SDK would have probed,
e.g. ``"https://example.cloud.databricks.com"``.
:raises ConnectionError: Always — simulates an unreachable host without
the SDK's network retry loop.
"""
raise ConnectionError(f"offline test stub: refusing to probe {host}")
@pytest.fixture
def pat_only_cfg(
tmp_path: _Path, monkeypatch: pytest.MonkeyPatch, clean_databricks_env: None
) -> _Path:
"""
Materialize a temp ``.databrickscfg`` containing a single PAT profile
and point the SDK at it via ``DATABRICKS_CONFIG_FILE``.
A PAT profile makes the SDK's ``authenticate()`` return the token
verbatim without any OAuth exchange. The host is a placeholder, so the
SDK's ``Config.__init__`` host-metadata probe (a real HTTP GET against
``/.well-known/databricks-config``, with retries) is stubbed to fail
fast — ``_resolve_host_metadata`` logs and falls back to the explicit
config, which is exactly the offline behavior these tests need.
"""
monkeypatch.setattr(
"databricks.sdk.config.get_host_metadata",
_raise_offline_host_metadata,
)
contents = textwrap.dedent(
"""
[pat-profile]
host = https://example.cloud.databricks.com
token = dapi-fake-pat-token-for-unit-test
"""
).lstrip()
cfg_path = tmp_path / "databrickscfg"
cfg_path.write_text(contents)
monkeypatch.setenv("DATABRICKS_CONFIG_FILE", str(cfg_path))
return cfg_path
def test_read_databrickscfg_pat_profile_returns_token_verbatim(
pat_only_cfg: _Path,
) -> None:
"""
For a plain ``auth_type=pat`` profile, the SDK should return the PAT
from the file verbatim (no OAuth exchange, no token rewriting). This
confirms we haven't regressed the common PAT-user path.
"""
creds = _read_databrickscfg("pat-profile")
assert creds is not None
assert creds.host == "https://example.cloud.databricks.com"
assert creds.token == "dapi-fake-pat-token-for-unit-test"
def test_read_databrickscfg_missing_profile_falls_back_to_file_reader(
pat_only_cfg: _Path,
) -> None:
"""
Requesting a profile that doesn't exist makes Config raise ValueError;
the wrapper catches that and falls through to the legacy file reader.
The legacy reader's documented resolution order is: explicit profile
-> DATABRICKS_CONFIG_PROFILE env -> DEFAULT section -> first section
with both host+token. So on a config file that contains only
``pat-profile``, an unknown requested profile falls through to
"first section" — i.e. we recover PAT credentials.
"""
creds = _read_databrickscfg("no-such-profile-xyz")
assert creds is not None
assert creds.host == "https://example.cloud.databricks.com"
assert creds.token == "dapi-fake-pat-token-for-unit-test"
def test_read_databrickscfg_empty_config_file_returns_none(
tmp_path: _Path,
monkeypatch: pytest.MonkeyPatch,
clean_databricks_env: None,
) -> None:
"""
With a config file that exists but contains no valid profiles, both
the SDK path and the file fallback should resolve to ``None``.
"""
cfg_path = tmp_path / "databrickscfg"
cfg_path.write_text("# empty\n")
monkeypatch.setenv("DATABRICKS_CONFIG_FILE", str(cfg_path))
assert _read_databrickscfg("missing-profile") is None
def test_read_databrickscfg_host_reads_oauth_profile_without_token(
tmp_path: _Path,
monkeypatch: pytest.MonkeyPatch,
clean_databricks_env: None,
) -> None:
"""
Host-only resolution supports Databricks CLI OAuth profile sections.
Native Codex does not need a static token at startup: it only needs the
workspace host to build the Codex provider base URL, then Codex's
``auth.command`` calls ``databricks auth token --profile`` for live bearer
refresh. A default install without ``databricks-sdk`` must therefore still
accept a present ``auth_type=databricks-cli`` section with no ``token``.
"""
cfg_path = tmp_path / "databrickscfg"
cfg_path.write_text(
textwrap.dedent(
"""
[oauth-profile]
host = https://oauth-host.example.com
auth_type = databricks-cli
"""
).lstrip()
)
monkeypatch.setenv("DATABRICKS_CONFIG_FILE", str(cfg_path))
assert _read_databrickscfg_host("oauth-profile") == "https://oauth-host.example.com"
def test_read_databrickscfg_host_missing_named_profile_does_not_fallback(
tmp_path: _Path,
monkeypatch: pytest.MonkeyPatch,
clean_databricks_env: None,
) -> None:
"""An explicit missing profile must not borrow a different profile's host."""
cfg_path = tmp_path / "databrickscfg"
cfg_path.write_text(
textwrap.dedent(
"""
[other-profile]
host = https://other.example.com
auth_type = databricks-cli
"""
).lstrip()
)
monkeypatch.setenv("DATABRICKS_CONFIG_FILE", str(cfg_path))
assert _read_databrickscfg_host("missing-profile") is None
def test_codex_executor_gateway_uses_host_only_oauth_profile(
tmp_path: _Path,
monkeypatch: pytest.MonkeyPatch,
clean_databricks_env: None,
) -> None:
"""
Wrapped Codex shares the native Codex host-only Databricks profile path.
This covers default installs where the runner can read a
``databricks-cli`` profile's host but cannot mint a bearer snapshot at
construction time.
"""
cfg_path = tmp_path / "databrickscfg"
cfg_path.write_text(
textwrap.dedent(
"""
[oauth-profile]
host = https://oauth-host.example.com
auth_type = databricks-cli
"""
).lstrip()
)
monkeypatch.setenv("DATABRICKS_CONFIG_FILE", str(cfg_path))
monkeypatch.setattr(
"omnigent.inner.codex_executor._read_databrickscfg",
lambda _profile: None,
)
from omnigent.inner.codex_executor import CodexExecutor
executor = CodexExecutor(
codex_path=sys.executable,
gateway=True,
databricks_profile="oauth-profile",
)
overrides = "\n".join(executor._codex_config_overrides)
assert "https://oauth-host.example.com/ai-gateway/codex/v1" in overrides
assert 'databricks auth token --profile \\"oauth-profile\\"' in overrides
def test_read_databrickscfg_no_config_file_returns_none(
tmp_path: _Path,
monkeypatch: pytest.MonkeyPatch,
clean_databricks_env: None,
) -> None:
"""
When ``~/.databrickscfg`` is absent and no env auth is set, both the
SDK path and the file fallback should return ``None``.
"""
monkeypatch.setenv("DATABRICKS_CONFIG_FILE", str(tmp_path / "does-not-exist"))
assert _read_databrickscfg("DEFAULT") is None
def test_file_fallback_reads_token_field_directly(
tmp_path: _Path,
monkeypatch: pytest.MonkeyPatch,
clean_databricks_env: None,
) -> None:
"""
The legacy fallback intentionally reads the ``token`` field as-is
(that is the pre-fix behavior we preserve for exotic setups where
the SDK's Config init raises). Confirm the fallback still works.
"""
cfg_path = tmp_path / "databrickscfg"
cfg_path.write_text(
textwrap.dedent(
"""
[p]
host = https://legacy-host.example.com
token = legacy-pat-value
"""
).lstrip()
)
monkeypatch.setenv("DATABRICKS_CONFIG_FILE", str(cfg_path))
creds = _read_databrickscfg_file_fallback("p")
assert creds is not None
assert creds.host == "https://legacy-host.example.com"
assert creds.token == "legacy-pat-value"
def test_read_databrickscfg_falls_back_when_sdk_raises(
tmp_path: _Path,
monkeypatch: pytest.MonkeyPatch,
clean_databricks_env: None,
) -> None:
"""
Verify the SDK-failure path: if ``databricks.sdk.config.Config`` raises
``ValueError`` during construction, the wrapper silently falls through
to the file reader so plain PAT setups still work.
We simulate this by stubbing the SDK's ``Config`` with a tiny real
class that unconditionally raises on init — no MagicMock.
"""
class _AlwaysFailsConfig:
"""
Test double for ``databricks.sdk.config.Config`` that always
raises ValueError — emulates an exotic setup the SDK can't parse.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
raise ValueError("simulated SDK resolution failure")
cfg_path = tmp_path / "databrickscfg"
cfg_path.write_text(
textwrap.dedent(
"""
[fallback-profile]
host = https://fallback-host.example.com
token = fallback-pat-value
"""
).lstrip()
)
monkeypatch.setenv("DATABRICKS_CONFIG_FILE", str(cfg_path))
monkeypatch.setattr(_sdk_config_mod, "Config", _AlwaysFailsConfig)
creds = _read_databrickscfg("fallback-profile")
assert creds is not None
assert creds.host == "https://fallback-host.example.com"
assert creds.token == "fallback-pat-value"
def test_read_databrickscfg_missing_profile_uses_ambient_credentials(