import concurrent.futures import importlib.util import json import http.client from pathlib import Path import threading import time import urllib.error import urllib.request from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import pytest def gateway(): path = Path(__file__).parents[1] / 'admin/qwen_gateway.py' assert path.exists(), 'on-demand gateway has not been implemented' spec = importlib.util.spec_from_file_location('qwen_gateway_under_test', path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module class Admission: def __init__(self): self.calls = [] def acquire(self): self.calls.append('acquire') def release(self, **kwargs): self.calls.append('release') def needs_verification(self): return False class Engine: def __init__(self): self.calls = [] self.loading = threading.Event() self.allow_load = threading.Event() self.allow_load.set() self.stopping = threading.Event() self.allow_stop = threading.Event() self.allow_stop.set() self.fail = False def start(self): self.calls.append('start') self.loading.set() assert self.allow_load.wait(3) if self.fail: raise RuntimeError('failed load') def stop(self): self.calls.append('stop') self.stopping.set() assert self.allow_stop.wait(3) def running(self): return False def wait_until(predicate): deadline = time.monotonic() + 3 while not predicate() and time.monotonic() < deadline: time.sleep(.005) assert predicate() def test_concurrent_calls_share_start_and_stop_only_after_last_release(): module = gateway() engine, admission = Engine(), Admission() lifecycle = module.ModelLifecycle(engine, admission) engine.allow_load.clear() with concurrent.futures.ThreadPoolExecutor(2) as pool: a = pool.submit(lifecycle.acquire) assert engine.loading.wait(2) b = pool.submit(lifecycle.acquire) wait_until(lambda: lifecycle.snapshot()['active_requests'] == 2) engine.allow_load.set() a.result(2) b.result(2) assert engine.calls == ['start'] lifecycle.release() assert engine.calls == ['start'] lifecycle.release() assert engine.calls == ['start', 'stop'] assert admission.calls == ['acquire', 'release'] assert lifecycle.snapshot()['state'] == 'stopped' def test_arrival_while_stopping_waits_for_new_residency(): module = gateway() engine, admission = Engine(), Admission() lifecycle = module.ModelLifecycle(engine, admission) lifecycle.acquire() engine.allow_stop.clear() with concurrent.futures.ThreadPoolExecutor(2) as pool: stopping = pool.submit(lifecycle.release) assert engine.stopping.wait(2) arriving = pool.submit(lifecycle.acquire) time.sleep(.03) assert not arriving.done() engine.allow_stop.set() stopping.result(2) arriving.result(2) lifecycle.release() assert engine.calls == ['start', 'stop', 'start', 'stop'] def test_failed_loading_cleans_up_and_later_call_can_retry(): module = gateway() engine, admission = Engine(), Admission() engine.fail = True lifecycle = module.ModelLifecycle(engine, admission) with pytest.raises(RuntimeError, match='failed load'): lifecycle.acquire() assert engine.calls == ['start', 'stop'] assert admission.calls == ['acquire', 'release'] assert lifecycle.snapshot()['active_requests'] == 0 engine.fail = False lifecycle.acquire() lifecycle.release() assert lifecycle.snapshot()['state'] == 'stopped' def test_stop_failure_retains_hold_and_blocks_new_loading(): module = gateway() engine, admission = Engine(), Admission() lifecycle = module.ModelLifecycle(engine, admission) lifecycle.acquire() def fail(): raise RuntimeError('cannot prove stopped') engine.stop = fail with pytest.raises(RuntimeError): lifecycle.release() assert admission.calls == ['acquire'] assert lifecycle.snapshot()['state'] == 'blocked' with pytest.raises(RuntimeError): lifecycle.acquire() def test_cold_probes_rejections_json_and_sse_use_real_http(): module = gateway() engine, admission = Engine(), Admission() lifecycle = module.ModelLifecycle(engine, admission) seen = [] class Upstream(BaseHTTPRequestHandler): def log_message(self, *_): pass def do_POST(self): body = json.loads(self.rfile.read(int(self.headers['Content-Length']))) seen.append(body) stream = body.get('stream', False) blob = b'data: {"text":"first"}\n\ndata: [DONE]\n\n' if stream else b'{"choices":[{"message":{"content":"2"}}]}' self.send_response(200) self.send_header('Content-Type', 'text/event-stream' if stream else 'application/json') self.send_header('Content-Length', str(len(blob))) self.end_headers() self.wfile.write(blob) upstream = ThreadingHTTPServer(('127.0.0.1', 0), Upstream) server = module.make_server(('127.0.0.1', 0), lifecycle, upstream_port=upstream.server_port, model='example', api_key='test-secret') servers = [upstream, server] for s in servers: threading.Thread(target=s.serve_forever, daemon=True).start() base = f'http://127.0.0.1:{server.server_port}' def request(path, value=None, auth=True): headers = {'Content-Type': 'application/json'} if auth: headers['Authorization'] = 'Bearer test-secret' return urllib.request.urlopen(urllib.request.Request(base + path, data=None if value is None else json.dumps(value).encode(), headers=headers), timeout=5) try: with request('/health', auth=False) as response: assert response.status == 200 with request('/v1/models') as response: assert json.load(response)['data'][0]['id'] == 'example' for value, auth in [({'model': 'wrong', 'messages': []}, True), ({'model': 'example', 'messages': []}, True), ({'model': 'example', 'messages': [{'role':'invalid-role','content':42}]}, True), ({'model': 'example', 'messages': [{'role':'user','content':'x'}]}, False)]: with pytest.raises(urllib.error.HTTPError): request('/v1/chat/completions', value, auth) for route, value in [('/generate', {'text':None}), ('/v1/completions', {'prompt':{'invalid':'object'}})]: with pytest.raises(urllib.error.HTTPError) as error: request(route, value) assert error.value.code == 400 assert engine.calls == [] body = {'model': 'example', 'messages': [{'role':'user','content':'1+1'}]} with request('/v1/chat/completions', body) as response: assert json.load(response)['choices'][0]['message']['content'] == '2' wait_until(lambda: lifecycle.snapshot()['state'] == 'stopped') with request('/v1/chat/completions', {**body, 'stream': True}) as response: assert response.read() == b'data: {"text":"first"}\n\ndata: [DONE]\n\n' wait_until(lambda: lifecycle.snapshot()['state'] == 'stopped') assert len(seen) == 2 assert engine.calls == ['start', 'stop', 'start', 'stop'] finally: for s in reversed(servers): s.shutdown() s.server_close() def test_disconnected_stream_stays_counted_until_upstream_drains_with_peer_call(): module = gateway() engine, admission = Engine(), Admission() lifecycle = module.ModelLifecycle(engine, admission) finish_stream = threading.Event() class Upstream(BaseHTTPRequestHandler): def log_message(self, *_): pass def do_POST(self): body = json.loads(self.rfile.read(int(self.headers['Content-Length']))) self.send_response(200) self.end_headers() if body.get('stream'): self.wfile.write(b'data: first\n\n') self.wfile.flush() assert finish_stream.wait(3) self.wfile.write(b'data: [DONE]\n\n') else: self.wfile.write(b'{"answer":2}') upstream = ThreadingHTTPServer(('127.0.0.1', 0), Upstream) server = module.make_server(('127.0.0.1', 0), lifecycle, upstream_port=upstream.server_port, model='example') for s in [upstream, server]: threading.Thread(target=s.serve_forever, daemon=True).start() client = http.client.HTTPConnection('127.0.0.1', server.server_port, timeout=3) body = {'model': 'example', 'messages': [{'role':'user','content':'x'}]} try: client.request('POST', '/v1/chat/completions', json.dumps({**body, 'stream': True}), {'Content-Type': 'application/json'}) response = client.getresponse() assert response.read1() == b'data: first\n\n' response.close() client.close() with urllib.request.urlopen(urllib.request.Request( f'http://127.0.0.1:{server.server_port}/v1/chat/completions', data=json.dumps(body).encode(), headers={'Content-Type':'application/json'}), timeout=3) as peer: assert json.load(peer) == {'answer': 2} assert lifecycle.snapshot()['active_requests'] == 1 assert engine.calls == ['start'] finish_stream.set() wait_until(lambda: lifecycle.snapshot()['state'] == 'stopped') assert engine.calls == ['start', 'stop'] finally: finish_stream.set() client.close() for s in [server, upstream]: s.shutdown() s.server_close() def test_host_handoff_rejects_stale_ack_and_inconsistent_gpu_sample(tmp_path): module = gateway() gpu_uuid = 'GPU-9efe0d3d-f341-f19a-da75-fcb985e6b96d' scheduler, gpu = tmp_path/'scheduler.json', tmp_path/'gpu.json' admission = module.HostAdmission(reservation_path=tmp_path/'hold.json', scheduler_path=scheduler, gpu_status_path=gpu, queue_db_path=tmp_path/'jobs.db', gpu_uuid=gpu_uuid) admission.token = 'a' * 32 ack = {'updated_at': time.time(), 'state': 'idle', 'active_jobs': [], 'qwen_reservation': {'enabled': True, 'hold': True, 'token': admission.token, 'gpu_uuid': gpu_uuid, 'quiesced': True}} scheduler.write_text(json.dumps(ack)) assert admission._acknowledged() scheduler.write_text(json.dumps({**ack, 'updated_at': time.time() - 4})) assert not admission._acknowledged() ack['qwen_reservation']['token'] = 'b' * 32 scheduler.write_text(json.dumps(ack)) assert not admission._acknowledged() sample = {'schema_version': 1, 'error': None, 'generated_at': time.time(), 'sample_started_at': time.time() - .1, 'gpus': [{'uuid':gpu_uuid, 'free_gib':79, 'idle_since': time.time() - 30, 'external_pids':[], 'own_pids':[]}]} gpu.write_text(json.dumps(sample)) assert admission._gpu_idle() gpu.write_text(json.dumps({**sample, 'sample_started_at': sample['generated_at'] + .1})) assert not admission._gpu_idle(), 'a sample cannot start after it was published' gpu.write_text(json.dumps({**sample, 'error': 'NVML unavailable'})) assert not admission._gpu_idle() def test_restart_reconciliation_stops_engine_before_clearing_reservation(): module = gateway() assert hasattr(module, 'reconcile'), 'restart must reconcile an old engine before admitting requests' engine, admission = Engine(), Admission() module.reconcile(engine, admission) assert engine.calls == ['stop'] assert admission.calls == ['release'] engine.stop = lambda: (_ for _ in ()).throw(RuntimeError('cannot stop')) with pytest.raises(RuntimeError): module.reconcile(engine, admission) assert admission.calls == ['release'] def test_restart_does_not_clear_unverified_hold_just_because_container_stopped(): module = gateway() engine, admission = Engine(), Admission() admission.needs_verification = lambda: True checks = [] admission.release = lambda **kwargs: checks.append(kwargs['engine_was_started']) module.reconcile(engine, admission) assert checks == [True], 'an old held reservation still requires a fresh GPU release observation' def test_handoff_is_durably_sealed_and_reacknowledged_before_loading(tmp_path, monkeypatch): import sqlite3 module = gateway() db_path = tmp_path/'jobs.db' with sqlite3.connect(db_path) as db: db.execute('CREATE TABLE jobs(queue_seq INTEGER)') db.execute('INSERT INTO jobs VALUES (1)') hold_path, scheduler_path = tmp_path/'hold.json', tmp_path/'scheduler.json' gpu_uuid = 'GPU-9efe0d3d-f341-f19a-da75-fcb985e6b96d' admission = module.HostAdmission(reservation_path=hold_path, scheduler_path=scheduler_path, gpu_status_path=tmp_path/'gpu.json', queue_db_path=db_path, gpu_uuid=gpu_uuid, wait_seconds=2) samples = [] monkeypatch.setattr(admission, '_gpu_idle', lambda **kwargs: samples.append(kwargs) or True) with concurrent.futures.ThreadPoolExecutor(1) as pool: future = pool.submit(admission.acquire) wait_until(hold_path.exists) value = json.loads(hold_path.read_text()) ack = {'updated_at':time.time(), 'state':'idle', 'active_jobs':[], 'qwen_reservation': { 'enabled':True, 'hold':True, 'token':value['token'], 'gpu_uuid':gpu_uuid, 'quiesced':True, 'queue_seq_cutoff':1}} module.atomic_json(scheduler_path, ack) deadline = time.monotonic() + 1 while not future.done() and time.monotonic() < deadline: if json.loads(hold_path.read_text())['queue_seq_cutoff'] == 0: break time.sleep(.01) sealed = json.loads(hold_path.read_text()) assert sealed['queue_seq_cutoff'] == 0, 'first ack must seal root-owned admission before model start' assert not future.done(), 'old ack cannot authorize the sealed handoff' ack['qwen_reservation']['queue_seq_cutoff'] = 0 ack['updated_at'] = time.time() module.atomic_json(scheduler_path, ack) future.result(2) assert samples[-1]['after'] > 0