okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cc500be1c
main
1"""Bounded, local API verification for a managed server instance. 2 3The ready file is only a hint that a port was bound. This module asks that 4same instance for telemetry, then performs one one-token generation when the 5model is loaded. Credentials stay in memory and no response text is saved. 6""" 7 8from __future__import annotations 9 10import http .client 11import hmac 12import ipaddress 13import json 14import os 15import re 16import socket 17import time 18 19 20class ReadinessError (Exception ): 21pass 22 23 24def _address (ready :dict ,expected_host :str )-> tuple [str ,int ]: 25host = ready .get ("bound_host" ) 26port = ready .get ("bound_port" ) 27if host != expected_host or type (port )is not int or not 1 <= port <= 65535 : 28raise ReadinessError ("ready_endpoint_mismatch" ) 29if host in ("" ,"0.0.0.0" ): 30return "127.0.0.1" ,port 31if host == "::" : 32return "::1" ,port 33if host == "localhost" : 34return host ,port 35try : 36ipaddress .ip_address (host ) 37except ValueError : 38raise ReadinessError ("ready_endpoint_not_numeric" )from None 39return host ,port 40 41 42def _credential (source_bytes :bytes )-> str | None : 43from serve .server import api_key_of ,key_list 44 45cfg = json .loads (source_bytes .decode ("utf-8-sig" )) 46if not isinstance (cfg ,dict ): 47raise ValueError ("run config must be an object" ) 48raw = os .environ .get ("STRATA_API_KEY" )or cfg .get ("api_key" ,"" ) 49if str (raw ).strip ().lower ()== "none" :# "api_key": "none" = served without a key on purpose 50return None 51keys = key_list (api_key_of (raw )) 52return keys [0 ]if keys else None 53 54 55def _request (host :str ,port :int ,method :str ,path :str ,key :str | None , 56timeout :float ,body :dict | None = None )-> dict : 57payload = json .dumps (body ,ensure_ascii = False ).encode ()if body is not None else None 58headers = {"Accept" :"application/json" } 59if payload is not None : 60headers ["Content-Type" ]= "application/json" 61if key is not None : 62headers ["Authorization" ]= "Bearer " + key 63connection = http .client .HTTPConnection (host ,port ,timeout = max (0.1 ,timeout )) 64try : 65connection .request (method ,path ,body = payload ,headers = headers ) 66response = connection .getresponse () 67raw = response .read (512 * 1024 + 1 ) 68if len (raw )> 512 * 1024 : 69raise ReadinessError ("probe_response_too_large" ) 70if response .status != 200 : 71raise ReadinessError (f"probe_http_ { response . status } " ) 72result = json .loads (raw ) 73if not isinstance (result ,dict ): 74raise ReadinessError ("probe_invalid_response" ) 75return result 76except (OSError ,socket .timeout ,http .client .HTTPException ): 77raise ReadinessError ("probe_transport_failed" )from None 78except (UnicodeError ,ValueError ): 79raise ReadinessError ("probe_invalid_response" )from None 80finally : 81connection .close () 82 83 84def verify (ready :dict ,source_bytes :bytes ,* ,expected_host :str , 85expected_instance :str ,expected_attestation :str , 86timeout :float ,force_load :bool = False )-> dict : 87if not isinstance (expected_attestation ,str )or not re .fullmatch (r"[0-9a-f]{64}" ,expected_attestation ): 88raise ReadinessError ("probe_launch_attestation_unavailable" ) 89host ,port = _address (ready ,expected_host ) 90display_host = f"[ { host } ]" if ":" in host else host 91api_url = f"http:// { display_host } : { port } " 92deadline = time .monotonic ()+ timeout 93try : 94cfg = json .loads (source_bytes .decode ("utf-8-sig" )) 95key = _credential (source_bytes ) 96except (UnicodeError ,ValueError ,TypeError ): 97raise ReadinessError ("probe_credential_invalid" )from None 98if not isinstance (cfg ,dict )or not isinstance (ready .get ("model_id" ),str )or \ 99 (cfg .get ("model_name" )is not None and ready ["model_id" ]!= cfg ["model_name" ]): 100raise ReadinessError ("probe_model_mismatch" ) 101telemetry = _request (host ,port ,"GET" ,"/v1/telemetry" ,key , 102max (0.1 ,deadline - time .monotonic ())) 103instance = telemetry .get ("instance" ) 104model = telemetry .get ("model" ) 105if not isinstance (instance ,dict )or instance .get ("id" )!= expected_instance : 106raise ReadinessError ("probe_instance_mismatch" ) 107reported_attestation = instance .get ("launch_attestation" ) 108if not isinstance (reported_attestation ,str )or not hmac .compare_digest ( 109reported_attestation ,expected_attestation ): 110raise ReadinessError ("probe_launch_attestation_mismatch" ) 111if not isinstance (model ,dict )or model .get ("id" )!= ready .get ("model_id" ): 112raise ReadinessError ("probe_model_mismatch" ) 113if ready .get ("model_state" )not in ("ready" ,"unloaded" ): 114raise ReadinessError ("probe_model_state_invalid" ) 115loaded = model .get ("loaded" ) 116if type (loaded )is not bool : 117raise ReadinessError ("probe_model_state_unavailable" ) 118if not loaded and not force_load : 119return {"api_identity_verified" :True ,"launch_attested" :True ,"generation_ready" :False , 120"readiness_state" :"unloaded" ,"model_state" :"unloaded" ,"api_url" :api_url } 121probe = {"model" :ready .get ("model_id" ),"messages" : [{"role" :"user" ,"content" :"hi" }], 122"max_tokens" :1 ,"temperature" :0 ,"stream" :False } 123while True : 124try : 125result = _request (host ,port ,"POST" ,"/v1/chat/completions" ,key , 126max (0.1 ,deadline - time .monotonic ()),probe ) 127break 128except ReadinessError as exc : 129if str (exc )not in ("probe_http_409" ,"probe_http_429" ,"probe_http_503" )or \ 130time .monotonic ()+ 0.25 >= deadline : 131raise 132time .sleep (0.25 ) 133choices = result .get ("choices" ) 134if not isinstance (choices ,list )or len (choices )!= 1 or not isinstance (choices [0 ],dict )or \ 135not isinstance (choices [0 ].get ("message" ),dict )or \ 136not isinstance (choices [0 ].get ("finish_reason" ),str ): 137raise ReadinessError ("probe_generation_invalid_response" ) 138usage = result .get ("usage" ) 139if not isinstance (usage ,dict )or type (usage .get ("completion_tokens" ))is not int or \ 140usage ["completion_tokens" ]< 1 : 141raise ReadinessError ("probe_generation_no_tokens" ) 142return {"api_identity_verified" :True ,"launch_attested" :True ,"generation_ready" :True , 143"readiness_state" :"generation_ready" ,"model_state" :"ready" ,"api_url" :api_url }