-
Notifications
You must be signed in to change notification settings - Fork 220
Expand file tree
/
Copy pathtest_lifecycle_server.py
More file actions
3661 lines (2952 loc) · 127 KB
/
Copy pathtest_lifecycle_server.py
File metadata and controls
3661 lines (2952 loc) · 127 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
# SPDX-License-Identifier: Apache-2.0
"""Server integration tests for lifecycle / residency behavior."""
from __future__ import annotations
import asyncio
import time
from contextlib import suppress
from types import SimpleNamespace
import pytest
async def _wait_for_resident_state(manager, model_key: str, state: str) -> None:
"""Poll until a resident reaches the expected state."""
while manager.get_status(model_key)["state"] != state:
await asyncio.sleep(0)
@pytest.fixture(autouse=True)
def restore_server_globals():
"""Restore mutated server module globals between lifecycle tests."""
import vllm_mlx.server as srv
sentinel = object()
global_names = (
"_engine",
"_model_name",
"_model_path",
"_default_model_key",
"_default_max_tokens",
"_default_timeout",
"_default_temperature",
"_default_top_p",
"_force_mllm_model",
"_auto_unload_idle_seconds",
"_lazy_load_model",
"_residency_manager",
"_lifecycle_task",
"_lifespan_active",
"_mcp_manager",
"_mcp_executor",
"_embedding_engine",
"_embedding_model_locked",
"_api_key",
"_auth_warning_logged",
"_rate_limiter",
"_reasoning_parser",
"_enable_auto_tool_choice",
"_tool_call_parser",
"_tool_parser_instance",
"_idle_unload_enabled",
)
snapshot = {name: getattr(srv, name, sentinel) for name in global_names}
yield
leaked_task = getattr(srv, "_lifecycle_task", None)
original_task = snapshot["_lifecycle_task"]
if (
leaked_task is not sentinel
and leaked_task is not None
and leaked_task is not original_task
and not leaked_task.done()
):
leaked_task.cancel()
for name, value in snapshot.items():
if value is sentinel:
if hasattr(srv, name):
delattr(srv, name)
else:
setattr(srv, name, value)
# _idle_unload_enabled is a lazily-created asyncio.Event bound to whatever
# event loop was running when _get_idle_unload_event() was first called.
# Reset to None so the next test gets a fresh Event on its own loop.
srv._idle_unload_enabled = None
class TestLifecycleStatusEndpoints:
"""Lock in residency metadata surfaced by server status endpoints."""
@pytest.mark.anyio
async def test_status_reports_unloaded_resident_metadata(self, monkeypatch):
"""Status should surface residency details even when model is unloaded."""
import vllm_mlx.server as srv
fake_manager = SimpleNamespace(
get_status=lambda model_key: {
"model_key": model_key,
"state": "unloaded",
"active_requests": 0,
"last_used_at": 1710200000.0,
"loaded_at": None,
"auto_unload_idle_seconds": 300,
}
)
monkeypatch.setattr(srv, "_engine", None)
monkeypatch.setattr(
srv, "_model_name", "mlx-community/Qwen3-0.6B-8bit", raising=False
)
monkeypatch.setattr(srv, "_default_model_key", "default", raising=False)
monkeypatch.setattr(srv, "_residency_manager", fake_manager, raising=False)
payload = await srv.status()
assert payload["status"] == "not_loaded"
assert payload["model"] == "mlx-community/Qwen3-0.6B-8bit"
assert payload["residency"]["model_key"] == "default"
assert payload["residency"]["state"] == "unloaded"
assert payload["residency"]["active_requests"] == 0
assert payload["residency"]["last_used_at"] == 1710200000.0
assert payload["residency"]["loaded_at"] is None
assert payload["residency"]["auto_unload_idle_seconds"] == 300
assert payload["requests"] == []
@pytest.mark.anyio
async def test_health_exposes_residency_state_for_unloaded_model(self, monkeypatch):
"""Health should report lifecycle state, not only a loaded bool."""
import vllm_mlx.server as srv
fake_manager = SimpleNamespace(
get_status=lambda model_key: {
"model_key": model_key,
"state": "unloaded",
"active_requests": 0,
"last_used_at": 1710200000.0,
"loaded_at": None,
"auto_unload_idle_seconds": 120,
}
)
monkeypatch.setattr(srv, "_engine", None)
monkeypatch.setattr(
srv,
"_model_name",
"mlx-community/Llama-3.2-3B-Instruct-4bit",
raising=False,
)
monkeypatch.setattr(srv, "_default_model_key", "default", raising=False)
monkeypatch.setattr(srv, "_residency_manager", fake_manager, raising=False)
monkeypatch.setattr(srv, "_mcp_manager", None)
payload = await srv.health()
assert payload["status"] == "healthy"
assert payload["model_loaded"] is False
assert payload["model_name"] == "mlx-community/Llama-3.2-3B-Instruct-4bit"
assert payload["residency_state"] == "unloaded"
assert payload["active_requests"] == 0
assert payload["last_used_at"] == 1710200000.0
assert payload["loaded_at"] is None
assert payload["auto_unload_idle_seconds"] == 120
@pytest.mark.anyio
async def test_failed_resident_surfaces_as_unhealthy_and_failed(self, monkeypatch):
"""Public status should not leak backend model identity or raw errors."""
import vllm_mlx.server as srv
fake_manager = SimpleNamespace(
get_status=lambda model_key: {
"model_key": model_key,
"model_name": "/tmp/private-local-model",
"state": "failed",
"active_requests": 0,
"last_used_at": 1710200000.0,
"loaded_at": None,
"last_error": "reload boom",
"auto_unload_idle_seconds": 120,
}
)
monkeypatch.setattr(srv, "_engine", None)
monkeypatch.setattr(
srv,
"_model_name",
"friendly-model",
raising=False,
)
monkeypatch.setattr(
srv,
"_model_path",
"/tmp/private-local-model",
raising=False,
)
monkeypatch.setattr(srv, "_default_model_key", "default", raising=False)
monkeypatch.setattr(srv, "_residency_manager", fake_manager, raising=False)
monkeypatch.setattr(srv, "_mcp_manager", None)
health_payload = await srv.health()
status_payload = await srv.status()
assert health_payload["status"] == "unhealthy"
assert health_payload["model_loaded"] is False
assert health_payload["residency_state"] == "failed"
# /health surfaces a sanitized error category for failed residents
assert health_payload["last_error"] == "model_load_failed"
assert status_payload["status"] == "not_loaded"
assert status_payload["model"] == "friendly-model"
assert status_payload["residency"]["state"] == "failed"
assert status_payload["residency"]["model_name"] == "friendly-model"
# /v1/status surfaces a generic error indicator, not raw exception text
assert status_payload["residency"]["last_error"] == "model_load_failed"
assert status_payload["requests"] == []
@pytest.mark.anyio
async def test_health_preserves_mllm_type_when_resident_is_unloaded(
self, monkeypatch
):
"""Unloaded multimodal residents should still report model_type=mllm."""
import vllm_mlx.server as srv
fake_manager = SimpleNamespace(
get_status=lambda model_key: {
"model_key": model_key,
"state": "unloaded",
"active_requests": 0,
"last_used_at": 1710200000.0,
"loaded_at": None,
"auto_unload_idle_seconds": 120,
}
)
monkeypatch.setattr(srv, "_engine", None)
monkeypatch.setattr(
srv,
"_model_name",
"mlx-community/gemma-3-4b-it-4bit",
raising=False,
)
monkeypatch.setattr(srv, "_default_model_key", "default", raising=False)
monkeypatch.setattr(srv, "_residency_manager", fake_manager, raising=False)
monkeypatch.setattr(srv, "_mcp_manager", None)
payload = await srv.health()
assert payload["model_type"] == "mllm"
@pytest.mark.anyio
async def test_health_uses_model_path_for_unloaded_served_alias_mllm(
self, monkeypatch
):
"""Served aliases should not hide unloaded multimodal model type."""
import vllm_mlx.server as srv
fake_manager = SimpleNamespace(
get_status=lambda model_key: {
"model_key": model_key,
"model_name": "mlx-community/gemma-3-4b-it-4bit",
"state": "unloaded",
"active_requests": 0,
"last_used_at": 1710200000.0,
"loaded_at": None,
"auto_unload_idle_seconds": 120,
}
)
monkeypatch.setattr(srv, "_engine", None)
monkeypatch.setattr(srv, "_model_name", "prod-chat", raising=False)
monkeypatch.setattr(
srv,
"_model_path",
"mlx-community/gemma-3-4b-it-4bit",
raising=False,
)
monkeypatch.setattr(srv, "_default_model_key", "default", raising=False)
monkeypatch.setattr(srv, "_residency_manager", fake_manager, raising=False)
monkeypatch.setattr(srv, "_mcp_manager", None)
payload = await srv.health()
assert payload["model_type"] == "mllm"
@pytest.mark.anyio
async def test_health_uses_force_mllm_for_unloaded_local_model(self, monkeypatch):
"""force_mllm should survive the unloaded-resident health fallback."""
import vllm_mlx.server as srv
monkeypatch.setattr(srv, "_mcp_manager", None)
monkeypatch.setattr(srv, "_residency_manager", None, raising=False)
monkeypatch.setattr(srv, "_default_model_key", None, raising=False)
srv.load_model(
"/tmp/local-model",
force_mllm=True,
auto_unload_idle_seconds=60,
)
monkeypatch.setattr(srv, "_engine", None)
payload = await srv.health()
assert payload["model_type"] == "mllm"
class TestCompletionStreamingRelease:
"""Verify the completion endpoint releases residency on all paths."""
@pytest.mark.anyio
async def test_completion_nonstreaming_error_releases_active_request(
self, monkeypatch
):
"""Non-streaming completion errors must still release the active request."""
import vllm_mlx.server as srv
releases = {"count": 0}
acquires = {"count": 0}
class FakeEngine:
preserve_native_tool_format = False
is_mllm = False
async def start(self):
pass
async def stop(self):
pass
async def generate(self, **kwargs):
raise RuntimeError("generation failed")
async def fake_acquire(
raw_request, *, total_timeout=None, deadline=None, count_activity=True
):
acquires["count"] += 1
return FakeEngine()
async def fake_release(*, count_activity=True):
releases["count"] += 1
monkeypatch.setattr(srv, "_acquire_default_engine_for_request", fake_acquire)
monkeypatch.setattr(srv, "_release_default_engine", fake_release)
monkeypatch.setattr(srv, "_model_name", "test-model")
class FakeRequest:
async def is_disconnected(self):
return False
request = SimpleNamespace(
model="test-model",
prompt="hello",
stream=False,
max_tokens=10,
temperature=None,
top_p=None,
top_k=None,
min_p=None,
presence_penalty=None,
repetition_penalty=None,
specprefill=None,
specprefill_keep_pct=None,
stop=None,
timeout=60.0,
)
with pytest.raises(RuntimeError, match="generation failed"):
await srv.create_completion(request, FakeRequest())
assert acquires["count"] == 1
assert (
releases["count"] == 1
), "Non-streaming completion must release residency on generation errors"
@pytest.mark.anyio
async def test_completion_streaming_release_matches_chat_pattern(self, monkeypatch):
"""Streaming completion should use try/finally like chat completion does."""
import vllm_mlx.server as srv
# The chat completion endpoint uses a release_on_exit flag with try/finally.
# The completion endpoint should follow the same pattern for consistency
# and safety. This test verifies that the streaming path eventually
# calls release via the cleanup callback.
releases = {"count": 0}
class FakeEngine:
preserve_native_tool_format = False
is_mllm = False
async def start(self):
pass
async def stop(self):
pass
async def stream_generate(self, **kwargs):
yield SimpleNamespace(
text="done",
new_text="done",
finish_reason="stop",
completion_tokens=1,
prompt_tokens=1,
finished=True,
)
async def fake_acquire(
raw_request, *, total_timeout=None, deadline=None, count_activity=True
):
return FakeEngine()
async def fake_release(*, count_activity=True):
releases["count"] += 1
monkeypatch.setattr(srv, "_acquire_default_engine_for_request", fake_acquire)
monkeypatch.setattr(srv, "_release_default_engine", fake_release)
monkeypatch.setattr(srv, "_model_name", "test-model")
class FakeRequest:
async def is_disconnected(self):
return False
request = SimpleNamespace(
model="test-model",
prompt="hello",
stream=True,
max_tokens=10,
temperature=None,
top_p=None,
top_k=None,
min_p=None,
presence_penalty=None,
repetition_penalty=None,
specprefill=None,
specprefill_keep_pct=None,
stop=None,
timeout=None,
)
response = await srv.create_completion(request, FakeRequest())
# Iterate to completion
async for _ in response.body_iterator:
pass
assert (
releases["count"] == 1
), "Streaming completion must release residency via cleanup callback"
class TestStatusEndpointEngineRace:
"""Verify status/health endpoints handle engine being None."""
@pytest.mark.anyio
async def test_status_endpoint_returns_not_loaded_when_engine_is_none(
self, monkeypatch
):
"""/v1/status should not 500 if engine is unloaded between check and use."""
import vllm_mlx.server as srv
call_count = {"n": 0}
class DisappearingEngine:
"""Engine that disappears after the null check."""
def get_stats(self):
call_count["n"] += 1
return {
"running": True,
"uptime_seconds": 10,
"steps_executed": 0,
"num_running": 0,
"num_waiting": 0,
"num_requests_processed": 0,
"total_prompt_tokens": 0,
"total_completion_tokens": 0,
"metal_active_memory_gb": 0,
"metal_peak_memory_gb": 0,
"metal_cache_memory_gb": 0,
"requests": [],
}
# Set engine to a real object, then unload it mid-call by patching
engine = DisappearingEngine()
monkeypatch.setattr(srv, "_engine", engine)
monkeypatch.setattr(srv, "_model_name", "test")
monkeypatch.setattr(srv, "_residency_manager", None)
monkeypatch.setattr(srv, "_default_model_key", None)
# Normal case: should work
result = await srv.status()
assert result["status"] == "running"
# Now simulate the race: engine becomes None after the check
monkeypatch.setattr(srv, "_engine", None)
result = await srv.status()
assert result["status"] == "not_loaded"
@pytest.mark.anyio
async def test_health_endpoint_handles_engine_none(self, monkeypatch):
"""/health should not 500 when engine is None."""
import vllm_mlx.server as srv
monkeypatch.setattr(srv, "_engine", None)
monkeypatch.setattr(srv, "_model_name", "test")
monkeypatch.setattr(srv, "_model_path", None)
monkeypatch.setattr(srv, "_force_mllm_model", False)
monkeypatch.setattr(srv, "_mcp_manager", None)
monkeypatch.setattr(srv, "_residency_manager", None)
monkeypatch.setattr(srv, "_default_model_key", None)
result = await srv.health()
assert result["status"] == "healthy"
assert result["model_loaded"] is False
@pytest.mark.anyio
async def test_status_endpoint_returns_disabled_mtp_object_when_absent(
self, monkeypatch
):
"""/v1/status should keep the mtp field object-shaped when MTP is off."""
import vllm_mlx.server as srv
class EngineWithoutMTPStats:
def get_stats(self):
return {
"running": True,
"uptime_seconds": 10,
"steps_executed": 1,
"num_running": 0,
"num_waiting": 0,
"num_requests_processed": 0,
"total_prompt_tokens": 0,
"total_completion_tokens": 0,
"metal_active_memory_gb": 0,
"metal_peak_memory_gb": 0,
"metal_cache_memory_gb": 0,
"requests": [],
}
monkeypatch.setattr(srv, "_engine", EngineWithoutMTPStats())
monkeypatch.setattr(srv, "_model_name", "test")
monkeypatch.setattr(srv, "_residency_manager", None)
monkeypatch.setattr(srv, "_default_model_key", None)
result = await srv.status()
assert result["mtp"] == {"enabled": False}
class TestToolParserUsesLocalEngine:
"""Tool parser should initialize from the request-local engine."""
@pytest.mark.anyio
async def test_chat_completion_initializes_parser_from_acquired_engine(
self, monkeypatch
):
"""Chat completion should seed parser state from the acquired engine."""
from vllm_mlx.engine.base import GenerationOutput
import vllm_mlx.server as srv
parser_tokenizers = []
class FakeParser:
def __init__(self, tokenizer=None):
parser_tokenizers.append(tokenizer)
def reset(self):
return None
def extract_tool_calls(self, output_text, request_dict=None):
return SimpleNamespace(
tools_called=False,
tool_calls=[],
content=output_text,
)
class FakeEngine:
preserve_native_tool_format = False
is_mllm = False
def __init__(self, tokenizer):
self.tokenizer = tokenizer
async def chat(self, **kwargs):
return GenerationOutput(
text="hello",
completion_tokens=1,
prompt_tokens=1,
)
local_engine = FakeEngine("tok-local")
async def fake_acquire(
raw_request, *, total_timeout=None, deadline=None, count_activity=True
):
return local_engine
async def fake_release(*, count_activity=True):
return None
monkeypatch.setattr(srv, "_validate_model_name", lambda _m: None)
monkeypatch.setattr(srv, "_acquire_default_engine_for_request", fake_acquire)
monkeypatch.setattr(srv, "_release_default_engine", fake_release)
monkeypatch.setattr(srv, "_model_name", "served-model")
monkeypatch.setattr(srv, "_default_max_tokens", 32)
monkeypatch.setattr(srv, "_engine", None)
monkeypatch.setattr(srv, "_reasoning_parser", None)
monkeypatch.setattr(srv, "_enable_auto_tool_choice", True)
monkeypatch.setattr(srv, "_tool_call_parser", "fake")
monkeypatch.setattr(srv, "_tool_parser_instance", None)
monkeypatch.setattr(
srv.ToolParserManager,
"get_tool_parser",
lambda name: FakeParser,
)
class FakeRawRequest:
async def is_disconnected(self):
return False
request = srv.ChatCompletionRequest(
model="user-sent-model-name",
messages=[{"role": "user", "content": "hi"}],
stream=False,
tool_choice="auto",
tools=[
{
"type": "function",
"function": {
"name": "lookup_weather",
"parameters": {"type": "object", "properties": {}},
},
}
],
)
await srv.create_chat_completion(request, FakeRawRequest())
assert parser_tokenizers == ["tok-local"], (
"Parser init should use the request-local engine acquired for "
"this request, not the stale global _engine"
)
class TestLifecycleFailureHandling:
"""Regression coverage for lifecycle failure paths."""
@pytest.mark.anyio
async def test_anthropic_validation_error_does_not_acquire_resident(
self, monkeypatch
):
"""Malformed Anthropic payloads should not touch residency at all."""
from pydantic import ValidationError
import vllm_mlx.server as srv
calls = {"acquires": 0, "releases": 0}
class FakeRequest:
async def json(self):
return {}
class FakeEngine:
preserve_native_tool_format = False
async def fake_acquire(
raw_request, *, total_timeout=None, deadline=None, count_activity=True
):
calls["acquires"] += 1
return FakeEngine()
async def fake_release(*, count_activity=True):
calls["releases"] += 1
monkeypatch.setattr(srv, "_acquire_default_engine_for_request", fake_acquire)
monkeypatch.setattr(srv, "_release_default_engine", fake_release)
with pytest.raises(ValidationError):
await srv.create_anthropic_message(FakeRequest())
assert calls["acquires"] == 0
assert calls["releases"] == 0
@pytest.mark.anyio
async def test_chat_completion_prep_error_releases_resident(self, monkeypatch):
"""Prep failures after acquire should still release chat residency."""
import vllm_mlx.server as srv
calls = {"acquires": 0, "releases": 0}
class FakeEngine:
is_mllm = False
preserve_native_tool_format = False
async def fake_acquire(
raw_request, *, total_timeout=None, deadline=None, count_activity=True
):
calls["acquires"] += 1
return FakeEngine()
async def fake_release(*, count_activity=True):
calls["releases"] += 1
def fake_extract(messages, preserve_native_format):
return ([{"role": "user", "content": "hi"}], [], [], [])
def fake_convert_tools(_tools):
raise RuntimeError("boom")
monkeypatch.setattr(srv, "_acquire_default_engine_for_request", fake_acquire)
monkeypatch.setattr(srv, "_release_default_engine", fake_release)
monkeypatch.setattr(srv, "extract_multimodal_content", fake_extract)
monkeypatch.setattr(srv, "convert_tools_for_template", fake_convert_tools)
request = SimpleNamespace(
stream=False,
messages=[SimpleNamespace(role="user", content="hi")],
model="mlx-community/Qwen3-0.6B-8bit",
max_tokens=None,
temperature=None,
top_p=None,
top_k=None,
min_p=None,
presence_penalty=None,
repetition_penalty=None,
response_format=None,
tools=[{"type": "function"}],
tool_choice=None,
enable_thinking=None,
video_fps=None,
video_max_frames=None,
specprefill=None,
specprefill_keep_pct=None,
chat_template_kwargs=None,
stop=None,
timeout=None,
)
with pytest.raises(RuntimeError, match="boom"):
await srv.create_chat_completion(request, SimpleNamespace())
assert calls["acquires"] == 1
assert calls["releases"] == 1
@pytest.mark.anyio
async def test_request_acquire_helper_disconnect_covers_final_lease(
self, monkeypatch
):
"""Disconnects should abort even if residency is stalled in final acquire()."""
import vllm_mlx.server as srv
acquire_cancelled = asyncio.Event()
lease_gate = asyncio.Event()
class FakeEngine:
preserve_native_tool_format = False
class FakeRequest:
async def is_disconnected(self):
return True
async def fake_acquire(model_key):
try:
await lease_gate.wait()
except asyncio.CancelledError:
acquire_cancelled.set()
raise
return FakeEngine()
fake_manager = SimpleNamespace(acquire=fake_acquire)
monkeypatch.setattr(srv, "_engine", None, raising=False)
monkeypatch.setattr(srv, "_residency_manager", fake_manager, raising=False)
monkeypatch.setattr(srv, "_default_model_key", "default", raising=False)
total_timeout, deadline = srv._start_request_budget(60.0)
result = await srv._acquire_default_engine_for_request(
FakeRequest(),
total_timeout=total_timeout,
deadline=deadline,
)
assert result is None
await asyncio.wait_for(acquire_cancelled.wait(), timeout=1.0)
@pytest.mark.anyio
async def test_wait_with_disconnect_reports_total_request_timeout(self):
"""Timeout details should reflect the configured request budget, not the sub-step."""
from fastapi import HTTPException
import vllm_mlx.server as srv
class FakeRawRequest:
async def json(self):
return {
"model": "mlx-community/Qwen3-0.6B-8bit",
"messages": [{"role": "user", "content": "hi"}],
"stream": False,
"max_tokens": 16,
}
async def is_disconnected(self):
return False
with pytest.raises(HTTPException, match="10.0 seconds"):
await srv._wait_with_disconnect(
asyncio.sleep(0.05),
FakeRawRequest(),
timeout=0.01,
timeout_detail_seconds=10.0,
poll_interval=0.001,
)
@pytest.mark.anyio
async def test_lifespan_startup_failure_cleans_up_loaded_resident_and_loop(
self, monkeypatch
):
"""Startup failures before yield should not leak lifecycle tasks or loaded residents."""
import vllm_mlx.server as srv
stopped = {"count": 0}
class FakeEngine:
preserve_native_tool_format = False
async def start(self):
return None
async def stop(self):
stopped["count"] += 1
class FakeRawRequest:
async def json(self):
return {
"model": "mlx-community/Qwen3-0.6B-8bit",
"messages": [{"role": "user", "content": "hi"}],
"stream": False,
"max_tokens": 16,
}
async def is_disconnected(self):
return False
async def fake_engine_factory(spec):
return FakeEngine()
async def fake_init_mcp(config_path):
raise RuntimeError("mcp boom")
monkeypatch.setattr(srv, "_engine_factory", fake_engine_factory)
monkeypatch.setattr(srv, "init_mcp", fake_init_mcp)
monkeypatch.setattr(srv, "_engine", None, raising=False)
monkeypatch.setattr(srv, "_residency_manager", None, raising=False)
monkeypatch.setattr(srv, "_default_model_key", None, raising=False)
monkeypatch.setattr(srv, "_mcp_manager", None, raising=False)
monkeypatch.setattr(srv, "_lifecycle_task", None, raising=False)
monkeypatch.setattr(srv, "_lifespan_active", False, raising=False)
monkeypatch.setenv("VLLM_MLX_MCP_CONFIG", "/tmp/fake-mcp.json")
srv.load_model(
"mlx-community/Qwen3-0.6B-8bit",
auto_unload_idle_seconds=60.0,
lazy_load_model=False,
)
lifespan = srv.lifespan(srv.app)
try:
with pytest.raises(RuntimeError, match="mcp boom"):
await lifespan.__anext__()
status = srv._get_lifecycle_status()
assert srv._lifecycle_task is None
assert srv._engine is None
assert status is not None
assert status["state"] == "unloaded"
assert stopped["count"] == 1
finally:
if srv._lifecycle_task is not None:
srv._lifecycle_task.cancel()
with suppress(asyncio.CancelledError):
await srv._lifecycle_task
srv._lifecycle_task = None
if srv._residency_manager is not None:
with suppress(Exception):
await srv._residency_manager.shutdown()
srv._sync_engine_from_residency()
with suppress(Exception):
await lifespan.aclose()
@pytest.mark.anyio
async def test_lifespan_startup_failure_preserves_original_exception(
self, monkeypatch, caplog
):
"""Cleanup failures should not replace the original startup exception."""
import vllm_mlx.server as srv
class FakeEngine:
preserve_native_tool_format = False
async def start(self):
return None
async def stop(self):
raise RuntimeError("stop boom")
async def fake_engine_factory(spec):
return FakeEngine()
async def fake_init_mcp(config_path):
raise RuntimeError("mcp boom")
monkeypatch.setattr(srv, "_engine_factory", fake_engine_factory)
monkeypatch.setattr(srv, "init_mcp", fake_init_mcp)
monkeypatch.setattr(srv, "_engine", None, raising=False)
monkeypatch.setattr(srv, "_residency_manager", None, raising=False)
monkeypatch.setattr(srv, "_default_model_key", None, raising=False)
monkeypatch.setattr(srv, "_mcp_manager", None, raising=False)
monkeypatch.setattr(srv, "_lifecycle_task", None, raising=False)
monkeypatch.setattr(srv, "_lifespan_active", False, raising=False)
monkeypatch.setenv("VLLM_MLX_MCP_CONFIG", "/tmp/fake-mcp.json")
srv.load_model(
"mlx-community/Qwen3-0.6B-8bit",
auto_unload_idle_seconds=60.0,
lazy_load_model=False,
)
lifespan = srv.lifespan(srv.app)
try:
caplog.clear()
with pytest.raises(RuntimeError, match="mcp boom") as excinfo:
await lifespan.__anext__()
assert excinfo.value.__cause__ is None
assert (
"Lifecycle cleanup failed while preserving the original exception"
in caplog.text
)
assert "stop boom" in caplog.text
finally:
if srv._lifecycle_task is not None:
srv._lifecycle_task.cancel()
with suppress(asyncio.CancelledError):
await srv._lifecycle_task
srv._lifecycle_task = None
if srv._residency_manager is not None:
with suppress(Exception):
await srv._residency_manager.shutdown()
srv._sync_engine_from_residency()
with suppress(Exception):
await lifespan.aclose()
@pytest.mark.anyio
async def test_lifespan_startup_failure_keeps_live_runtime_guarded_if_cleanup_fails(
self, monkeypatch
):
"""Startup failures should not orphan a live runtime when cleanup also fails."""
import vllm_mlx.server as srv
class FakeEngine:
preserve_native_tool_format = False
async def start(self):
return None
async def stop(self):
raise RuntimeError("stop boom")
async def fake_engine_factory(spec):
return FakeEngine()
async def fake_init_mcp(config_path):
raise RuntimeError("mcp boom")
monkeypatch.setattr(srv, "_engine_factory", fake_engine_factory)
monkeypatch.setattr(srv, "init_mcp", fake_init_mcp)
monkeypatch.setattr(srv, "_engine", None, raising=False)
monkeypatch.setattr(srv, "_residency_manager", None, raising=False)
monkeypatch.setattr(srv, "_default_model_key", None, raising=False)
monkeypatch.setattr(srv, "_mcp_manager", None, raising=False)
monkeypatch.setattr(srv, "_lifecycle_task", None, raising=False)
monkeypatch.setattr(srv, "_lifespan_active", False, raising=False)
monkeypatch.setenv("VLLM_MLX_MCP_CONFIG", "/tmp/fake-mcp.json")
srv.load_model(
"mlx-community/Qwen3-0.6B-8bit",
auto_unload_idle_seconds=60.0,
lazy_load_model=False,
)
lifespan = srv.lifespan(srv.app)
try:
with pytest.raises(RuntimeError, match="mcp boom"):
await lifespan.__anext__()
status = srv._get_lifecycle_status()
assert srv._engine is not None
assert status is not None
assert status["state"] == "loaded"
with pytest.raises(RuntimeError, match="existing residency manager"):
srv.load_model(
"mlx-community/Qwen3-0.6B-8bit",
auto_unload_idle_seconds=60.0,
)
finally:
if srv._lifecycle_task is not None:
srv._lifecycle_task.cancel()
with suppress(asyncio.CancelledError):
await srv._lifecycle_task
srv._lifecycle_task = None
if srv._residency_manager is not None:
with suppress(Exception):
await srv._residency_manager.shutdown()