okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
53623e56f
main
1#!/usr/bin/env python3 2"""#1012 на живом сервере: запрос ждёт движок, движок умирает во время чтения промпта. 3 4Что проверяем (из релиза v0.1.40.1): раньше запрос, дожидавшийся перезапуска мёртвого движка, 5висел навсегда или падал с `list.remove(x)`, а длинный промпт, который читался в момент смерти 6движка, завершался через ~300 с. Теперь тот же запрос либо продолжается с новым движком, либо 7заканчивается сразу с 503 («не отправлен» -> клиент может повторить). 8 9Ход: отправить длинный запрос -> через N секунд убить процесс движка -> смотреть, чем и когда 10закончится запрос. Сервер поднимает движок сам. 11 12usage: probe_restart_waiters.py [--kill-after 15] [--out results_restart.json] 13""" 14import json 15import pathlib 16import subprocess 17import threading 18import time 19import urllib .error 20import urllib .request 21 22REPO = "/home/dgbox/Strata" 23CFG = REPO + "/strata-200k.json" 24BASE = "http://127.0.0.1:8080" 25cfg = json .load (open (CFG ,encoding = "utf-8" )) 26KEY ,MODEL = cfg ["api_key" ],cfg .get ("model_name" ,"strata" ) 27 28FILLER = ("Разбирается модуль разбора конфигурации: он читает список секций, проверяет обязательные поля и " 29"собирает структуру настроек, которую дальше использует планировщик. Сбой на одной секции не должен " 30"останавливать остальные, поэтому парсер собирает список замечаний. " ) 31 32 33def big_prompt (tokens :int )-> str : 34# ~0.28 токена на символ для русского текста 35return (FILLER * (int (tokens / 0.28 / len (FILLER ))+ 1 ))[:int (tokens / 0.28 )] 36 37 38def send (rec ,label ,tokens ): 39payload = json .dumps ({"model" :MODEL ,"messages" : [{"role" :"user" , 40"content" :big_prompt (tokens )+ "\n\nОтветь одним словом." }], 41"max_tokens" :32 ,"stream" :True ,"reasoning_effort" :"none" }).encode () 42req = urllib .request .Request (BASE + "/v1/chat/completions" ,data = payload , 43headers = {"Content-Type" :"application/json" , 44"Authorization" :f"Bearer { KEY } " }) 45t0 = time .time () 46out = {"label" :label ,"prompt_tokens_asked" :tokens ,"started_at" :round (t0 ,3 ), 47"first_delta_s" :None ,"end_s" :None ,"http_status" :None ,"outcome" :None , 48"deltas" :0 } 49try : 50with urllib .request .urlopen (req ,timeout = 600 )as r : 51out ["http_status" ]= r .status 52for line in r : 53s = line .decode (errors = "replace" ).strip () 54if not s .startswith ("data:" ): 55continue 56data = s [5 :].strip () 57if data == "[DONE]" : 58break 59try : 60obj = json .loads (data ) 61except json .JSONDecodeError : 62continue 63for ch in obj .get ("choices" , []): 64if (ch .get ("delta" )or {}).get ("content" ): 65out ["deltas" ]+= 1 66if out ["first_delta_s" ]is None : 67out ["first_delta_s" ]= round (time .time ()- t0 ,2 ) 68out ["outcome" ]= "done" 69except urllib .error .HTTPError as e : 70out ["outcome" ]= f"HTTPError { e . code } " 71out ["http_status" ]= e .code 72try : 73out ["error_body" ]= e .read ().decode ()[:300 ] 74except Exception :# noqa: BLE001 75pass 76except Exception as e :# noqa: BLE001 77out ["outcome" ]= repr (e )[:200 ] 78out ["end_s" ]= round (time .time ()- t0 ,2 ) 79f"[ { label } ] status= { out [ 'http_status' ] } outcome= { out [ 'outcome' ] } " 80f"first_delta= { out [ 'first_delta_s' ] } end= { out [ 'end_s' ] } deltas= { out [ 'deltas' ] } " ) 81rec .append (out ) 82 83 84def main (): 85import argparse 86ap = argparse .ArgumentParser () 87ap .add_argument ("--kill-after" ,type = float ,default = 15.0 ) 88ap .add_argument ("--out" ,default = str (pathlib .Path (__file__ ).parent / "results_restart.json" )) 89a = ap .parse_args () 90 91before = subprocess .run (["pgrep" ,"-f" ,REPO + "/engine/strata" ],capture_output = True ,text = True ).stdout .split () 92recs = [] 93threads = [threading .Thread (target = send ,args = (recs ,f"waiter- { i } " ,60000 ))for i in range (1 ,4 )] 94for t in threads : 95t .start () 96time .sleep (a .kill_after ) 97killed = subprocess .run (["pkill" ,"-f" ,REPO + "/engine/strata" ],capture_output = True ,text = True ) 98kill_at = round (time .time (),3 ) 99f"движок убит через { a . kill_after } с: pkill rc= { killed . returncode } (pid до: { before } )" ) 100for t in threads : 101t .join (timeout = 420 ) 102 103health = None 104for _ in range (80 ): 105try : 106with urllib .request .urlopen (urllib .request .Request (BASE + "/health" ),timeout = 5 )as r : 107h = json .loads (r .read ().decode ()) 108if h .get ("loaded" ): 109health = {"recovered_after_kill_s" :round (time .time ()- kill_at ,1 ),"health" :h } 110break 111except Exception :# noqa: BLE001 112pass 113time .sleep (3 ) 114 115out = {"kill_after_s" :a .kill_after ,"engine_pids_before" :before ,"killed_at" :kill_at , 116"requests" :recs ,"server_recovered" :health , 117"log_tail" :subprocess .run (["bash" ,"-c" , 118f"tail -n 200 { REPO } /strata-200k.log | grep -iE 'engine|restart|503|died|wait' | tail -15" ], 119capture_output = True ,text = True ).stdout } 120pathlib .Path (a .out ).write_text (json .dumps (out ,ensure_ascii = False ,indent = 1 ),encoding = "utf-8" ) 121"записано:" ,a .out ) 122 123 124if __name__ == "__main__" : 125main ()