"""Synthetic HTTP/GUI-manager contracts. No model, GPU or production connection.""" import base64 import hashlib import http.client import json import threading import time import unittest from http.server import BaseHTTPRequestHandler from types import SimpleNamespace from typing import Any import test_endpoint as endpoint_fixtures import test_chat_test as chat_fixtures from api_compat import normalize_chat,CompatibilityError from basalt_worker import BasaltWorker from chat_control import ControlError from responses_compat import translate,ResponsesError def data_url(mime,raw):return 'data:'+mime+';base64,'+base64.b64encode(raw).decode() class FeatureWorker(endpoint_fixtures.FakeWorker): http:Any def capabilities(self,p): return dict(installed=True,loaded=bool(self.name),version='0.3.3',available=['documents','video','logprobs','answer_now'],capabilities=['documents','video','logprobs','answer_now'] if self.name else [],session_affinity=True) def ensure(self,p): super().ensure(p);self.profile=p;self.state='ready';self.generation='synthetic-generation';self.backend_info={'capabilities':['answer_now']};self.process=SimpleNamespace(poll=lambda:None);self.lock=threading.RLock();self.port=self.http.server_port;self.key='internal-test-only' def status(self):return {**super().status(),'runtime':'basalt','generation':getattr(self,'generation',None)} answer_now=BasaltWorker.answer_now class FeatureUpstream(BaseHTTPRequestHandler): def log_message(self,format,*args):pass def send(self,value,status=200): raw=json.dumps(value).encode();self.send_response(status);self.send_header('Content-Length',str(len(raw)));self.end_headers();self.wfile.write(raw) def do_POST(self): w:Any=getattr(self.server,'worker');body=json.loads(self.rfile.read(int(self.headers['Content-Length']))) if self.path=='/v1/answer_now': w.controls.append(body) if body.get('request_id')!=w.client_id:return self.send({'error':{'code':'unknown_request'}},404) if getattr(w,'control_status',200)!=200:return self.send({'error':{'code':'not_thinking'}},w.control_status) w.block.set();return self.send({'object':'answer_now','request_id':'native-fixture','state':'thinking'}) w.requests.append(body);w.forwarded_headers=dict(self.headers);w.client_id=self.headers.get('X-Client-Request-Id') if body.get('stream'): self.send_response(200);self.send_header('Content-Type','text/event-stream');self.send_header('X-Request-Id','native-fixture');self.end_headers() self.wfile.write(b'data: {"choices":[{"delta":{"reasoning_content":"Synthetic reasoning"}}]}\n\n');self.wfile.flush();w.entered.set();w.block.wait(4) self.wfile.write(b'data: {"choices":[{"delta":{"content":"Synthetic answer"},"finish_reason":"stop"}]}\n\ndata: [DONE]\n\n');self.wfile.flush() else: self.send({'id':'native-fixture','model':body['model'],'choices':[{'message':{'role':'assistant','content':'Synthetic answer'},'finish_reason':'stop','logprobs':{'content':[{'token':'Synthetic','logprob':-.1,'bytes':[83],'top_logprobs':[]}]}}]}) class HTTPFeatureTests(unittest.TestCase): def setUp(self): self.f:Any=endpoint_fixtures.EndpointTests();self.f.setUp();self.addCleanup(self.f.tearDown) self.w:Any=self.f.worker;self.w.__class__=FeatureWorker;self.w.controls=[];self.w.entered=threading.Event();self.w.http.RequestHandlerClass=FeatureUpstream self.f.rows[0]['parameters'].update(chat_runtime='basalt',vision_projector='synthetic',context=262144) self.f.enable('alpha') def request(self,path,body=None,headers=None)->tuple[int,dict[str,str],Any]: c=http.client.HTTPConnection('127.0.0.1',self.f.port,timeout=5) c.request('GET' if body is None else 'POST',path,json.dumps(body) if body is not None else None,{'Content-Type':'application/json','Authorization':'Bearer '+'A'*32,**(headers or {})}) r=c.getresponse();raw=r.read();result=(r.status,dict(r.headers),raw if (body or {}).get('stream') else json.loads(raw));c.close();return result def chat(self,**kw):return dict(model='alpha',messages=[dict(role='user',content='Synthetic question')],**kw) def stream(self,responses=False): self.w.block.clear();out={};body=dict(model='alpha',input='Synthetic question',stream=True) if responses else self.chat(stream=True) if responses:self.f.ep.config['responses_compat']=True thread=threading.Thread(target=lambda:out.setdefault('value',self.request('/v1/responses' if responses else '/v1/chat/completions',body,{'X-Client-Request-Id':'synthetic-client','X-Session-Id':'synthetic-session'})),daemon=True);thread.start();self.assertTrue(self.w.entered.wait(3));return thread,out def test_properties_are_versioned_and_do_not_load(self): code,_,props=self.request('/props?model=alpha');self.assertEqual(code,200);self.assertEqual(props['basalt']['version'],'0.3.3');self.assertFalse(props['basalt']['loaded']);self.assertEqual(props['basalt']['capabilities'],[]);self.assertIn('documents',props['basalt']['available_capabilities']);self.assertEqual(self.w.started,[]) _,_,caps=self.request('/v1/capabilities');self.assertEqual(caps['controls']['scope'],'same_principal');self.assertEqual(caps['media_limits']['attachments'],8) def test_document_video_defaults_and_session_scope_reach_worker(self): parts=[dict(type='file',file=dict(filename='note.txt',file_data=data_url('text/plain',b'Synthetic source'))),dict(type='video_url',video_url=dict(url=data_url('video/mp4',b'Synthetic fixture, not a decodable video')))] body=self.chat(session_id='raw-session');body['messages'][0]['content']=parts code,headers,_=self.request('/v1/chat/completions',body);self.assertEqual(code,200);self.assertEqual(headers['X-Request-Id'],'native-fixture') sent=self.w.requests[-1];self.assertEqual(sent['messages'][0]['content'][1]['max_frames'],128);self.assertEqual(sent['messages'][0]['content'][1]['fps'],2);self.assertNotEqual(sent['session_id'],'raw-session');self.assertEqual(sent['session_id'],self.w.forwarded_headers['x-session-id']) self.assertNotIn('max_frames',body['messages'][0]['content'][1]) def test_control_uses_separate_connection_and_finishes_same_stream(self): th,out=self.stream();code,_,result=self.request('/v1/answer_now',{'request_id':'synthetic-client'});self.assertEqual((code,result['state']),(200,'thinking'));th.join(4);self.assertFalse(th.is_alive());self.assertIn(b'Synthetic answer',out['value'][2]);self.assertEqual(self.w.controls,[{'request_id':self.w.client_id}]);self.assertEqual(self.w.started,['alpha']) self.assertEqual(self.request('/v1/answer_now',{'request_id':'native-fixture'})[0],409) def test_rotated_principal_cannot_control_old_request(self): th,_=self.stream();self.f.record['api_token_hash']=hashlib.sha256(b'B'*32).hexdigest() self.assertEqual(self.request('/v1/answer_now',{'request_id':'native-fixture'})[0],401) code,_,_=self.request('/v1/answer_now',{'request_id':'native-fixture'},{'Authorization':'Bearer '+'B'*32});self.assertEqual(code,404);self.assertEqual(self.w.controls,[]) self.w.block.set();th.join(4) def test_control_remains_admitted_when_data_slots_are_saturated(self): th,_=self.stream();semaphore=self.f.ep.http.data_admission;held=0 try: while semaphore.acquire(blocking=False):held+=1 self.assertEqual(self.request('/v1/models')[0],429) self.assertEqual(self.request('/v1/answer_now',{'session_id':'synthetic-session'})[0],200) finally: for _ in range(held):semaphore.release() self.w.block.set();th.join(4) def test_queued_control_does_not_load_or_interrupt_current_owner(self): out={} with self.f.ep.scheduler.lease(('other-owner',)): th=threading.Thread(target=lambda:out.setdefault('value',self.request('/v1/chat/completions',self.chat(),{'X-Client-Request-Id':'queued-fixture'})),daemon=True);th.start() deadline=time.monotonic()+3 while not self.f.ep.chat_controls.records and time.monotonic()