okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
1be32e9c7
main
1"""serve/test_prometheus.py - GET /metrics in the Prometheus text format (vLLM's names), against the mock engine. 2 3python -m unittest serve.test_prometheus -v 4""" 5from __future__import annotations 6 7import json 8import re 9import sys 10import threading 11import time 12import unittest 13import urllib .request 14from pathlib import Path 15 16sys .path .insert (0 ,str (Path (__file__ ).resolve ().parents [1 ])) 17from serve .frontend import ChatTemplate # noqa: E402 18from serve .prometheus import BUCKETS ,Latencies ,render ,wants_prometheus # noqa: E402 19from serve .server import ByteTokenizer ,MockEngine ,Service ,serve # noqa: E402 20 21ROOT = Path (__file__ ).resolve ().parents [1 ] 22 23 24def parse (text ): 25"""{(name, labels): value} for every sample line; checks each family has HELP and TYPE first.""" 26out ,typed = {},set () 27for line in text .splitlines (): 28if line .startswith ("# TYPE " ): 29assert line .split ()[2 ]not in typed ,f"two # TYPE lines for { line . split ()[ 2 ] } " 30typed .add (line .split ()[2 ]) 31continue 32if line .startswith ("#" )or not line : 33continue 34m = re .fullmatch (r'([a-z0-9_:]+)\{([^}]*)\} (\S+)' ,line ) 35assert m ,f"not a sample line: { line !r } " 36name ,labels ,value = m .groups () 37family = re .sub (r"_(bucket|sum|count)$" ,"" ,name ) 38assert name in typed or family in typed ,f" { name } has no # TYPE" 39out [(name ,labels )]= float (value ) 40return out 41 42 43class Units (unittest .TestCase ): 44def test_who_gets_the_text (self ): 45self .assertTrue (wants_prometheus ("text/plain;version=0.0.4" ,"" )) 46self .assertTrue (wants_prometheus ("application/openmetrics-text;version=1.0.0" ,"" )) 47self .assertTrue (wants_prometheus ("" ,"format=prometheus" )) 48self .assertFalse (wants_prometheus ("application/json" ,"" )) 49self .assertFalse (wants_prometheus ("*/*" ,"requests=all" )) 50 51def test_histograms_are_cumulative (self ): 52lat = Latencies () 53lat .observe (0.3 ,11 ,1.0 ,1.5 )# 10 gaps of 0.1 s 54lat .observe (None ,1 ,0.0 ,0.2 )# no first token, one token: no gap 55s = lat .snapshot () 56counts ,total ,n = s ["itl" ] 57self .assertEqual (n ,10 ) 58self .assertAlmostEqual (total ,1.0 ) 59self .assertEqual (counts [BUCKETS .index (0.1 )],10 ) 60self .assertEqual (counts [BUCKETS .index (0.08 )],0 ) 61self .assertEqual (s ["ttft" ][2 ],1 ) 62self .assertEqual (s ["e2e" ][2 ],2 ) 63self .assertEqual (counts ,sorted (counts )) 64 65def test_render_reads_the_server_record (self ): 66m = {"engine" : {"model" :'a "b"' ,"max_context" :1000 }, 67"live" : {"state" :"generating" ,"queued" :2 ,"prompt_tokens" :400 ,"generated" :100 }, 68"totals" : {"requests" :3 ,"prompt_tokens" :900 ,"reused" :600 ,"output_tokens" :50 , 69"drafts_offered" :40 ,"drafts_accepted" :30 }} 70got = parse (render (m ,Latencies ().snapshot ())) 71lab = 'model_name="a \\"b\\""' 72self .assertEqual (got [("vllm:num_requests_running" ,lab )],1 ) 73self .assertEqual (got [("vllm:num_requests_waiting" ,lab )],2 ) 74self .assertEqual (got [("vllm:kv_cache_usage_perc" ,lab )],0.5 ) 75self .assertEqual (got [("vllm:prefix_cache_hits_total" ,lab )],600 ) 76self .assertEqual (got [("vllm:spec_decode_num_accepted_tokens_total" ,lab )],30 ) 77self .assertEqual (got [("vllm:time_to_first_token_seconds_count" ,lab )],0 ) 78 79def test_strata_names_follow_the_json (self ): 80m = {"engine" : {"model" :"m" ,"max_context" :1000 }, 81"live" : {"state" :"reading" ,"queued" :0 ,"prompt_read" :300 ,"prefill_tok_s_mean" :2500.0 }, 82"totals" : {"requests" :1 ,"prompt_ms" :1500.0 ,"decode_ms" :2000.0 }, 83"requests" : [{"hit_rate" :0.97 ,"decode_tok_s" :101.5 }], 84"hardware" : {"gpu_util" :40.0 ,"gpus" : [{"index" :0 ,"util" :30.0 ,"mem_used" :1 << 30 ,"temp" :60 }, 85 {"index" :1 ,"util" :50.0 ,"mem_used" :2 << 30 ,"temp" :65 }], 86"cpu" :12.5 ,"ram_used" :8 << 30 ,"ram_total" :64 << 30 }} 87got = parse (render (m ,Latencies ().snapshot ())) 88lab = 'model_name="m"' 89self .assertEqual (got [("strata:live_state" ,lab + ',state="reading"' )],1 ) 90self .assertEqual (got [("strata:live_state" ,lab + ',state="generating"' )],0 ) 91self .assertEqual (got [("strata:live_prompt_read" ,lab )],300 ) 92self .assertEqual (got [("strata:totals_decode_seconds_total" ,lab )],2.0 ) 93self .assertEqual (got [("strata:last_hit_rate" ,lab )],0.97 ) 94self .assertEqual (got [("strata:gpu_util" ,lab + ',gpu="1"' )],50 ) 95self .assertEqual (got [("strata:gpu_mem_used_bytes" ,lab + ',gpu="0"' )],1 << 30 ) 96self .assertNotIn (("strata:gpu_power_watts" ,lab + ',gpu="0"' ),got )# not measured: no sample 97self .assertEqual (got [("strata:ram_total_bytes" ,lab )],64 << 30 ) 98 99 100class Endpoint (unittest .TestCase ): 101@classmethod 102def setUpClass (cls ): 103tok = ByteTokenizer () 104cls .svc = Service (MockEngine (tok ,"</think>\n\nhello there" ,max_context = 4096 ),tok , 105ChatTemplate (ROOT / "serve/chat_template.jinja" )) 106cls .httpd = serve (cls .svc ,port = 0 ) 107cls .base = f"http://127.0.0.1: { cls . httpd . server_address [ 1 ] } " 108 109@classmethod 110def tearDownClass (cls ): 111cls .httpd .shutdown () 112cls .httpd .server_close () 113 114def get (self ,path ,accept ): 115req = urllib .request .Request (self .base + path ,headers = {"Accept" :accept }) 116with urllib .request .urlopen (req ,timeout = 30 )as r : 117return r .headers .get ("Content-Type" ),r .read ().decode () 118 119def test_a_request_shows_in_both_formats (self ): 120body = json .dumps ({"model" :"m" ,"messages" : [{"role" :"user" ,"content" :"hi" }],"max_tokens" :32 }).encode () 121req = urllib .request .Request (self .base + "/v1/chat/completions" ,data = body , 122headers = {"Content-Type" :"application/json" }) 123with urllib .request .urlopen (req ,timeout = 30 )as r : 124usage = json .loads (r .read ())["usage" ] 125ctype ,text = self .get ("/metrics" ,"text/plain" ) 126self .assertTrue (ctype .startswith ("text/plain" )) 127got = {k [0 ]:v for k ,v in parse (text ).items ()} 128self .assertGreaterEqual (got ["vllm:request_success_total" ],1 ) 129self .assertGreaterEqual (got ["vllm:generation_tokens_total" ],usage ["completion_tokens" ]) 130self .assertGreaterEqual (got ["vllm:e2e_request_latency_seconds_count" ],1 ) 131ctype ,text = self .get ("/metrics" ,"application/json" ) 132self .assertTrue (ctype .startswith ("application/json" )) 133self .assertGreaterEqual (json .loads (text )["totals" ]["requests" ],1 ) 134ctype ,_ = self .get ("/metrics?format=prometheus" ,"*/*" ) 135self .assertTrue (ctype .startswith ("text/plain" )) 136 137 138class BatchEngine (MockEngine ): 139"""--batch as the server sees it: several requests generate at once, none waits for the control lines.""" 140batch ,waiting = 4 ,0 141 142 143class Batched (unittest .TestCase ): 144def test_every_concurrent_request_is_counted (self ): 145tok = ByteTokenizer () 146svc = Service (BatchEngine (tok ,"</think>\n\n" + "y" * 40 ,max_context = 4096 ,delay_s = 0.02 ),tok , 147ChatTemplate (ROOT / "serve/chat_template.jinja" )) 148httpd = serve (svc ,port = 0 ) 149base = f"http://127.0.0.1: { httpd . server_address [ 1 ] } " 150try : 151body = json .dumps ({"model" :"m" ,"messages" : [{"role" :"user" ,"content" :"hi" }], 152"max_tokens" :64 }).encode () 153 154def ask (): 155req = urllib .request .Request (base + "/v1/chat/completions" ,data = body , 156headers = {"Content-Type" :"application/json" }) 157with urllib .request .urlopen (req ,timeout = 60 )as r : 158r .read () 159 160threads = [threading .Thread (target = ask )for _ in range (3 )] 161 [t .start ()for t in threads ] 162time .sleep (0.4 )# the three are generating 163req = urllib .request .Request (base + "/metrics" ,headers = {"Accept" :"text/plain" }) 164with urllib .request .urlopen (req ,timeout = 30 )as r : 165during = {k [0 ]:v for k ,v in parse (r .read ().decode ()).items ()} 166 [t .join ()for t in threads ] 167with urllib .request .urlopen (req ,timeout = 30 )as r : 168after = {k [0 ]:v for k ,v in parse (r .read ().decode ()).items ()} 169finally : 170httpd .shutdown () 171httpd .server_close () 172self .assertEqual (during ["vllm:num_requests_running" ],3 ) 173self .assertEqual (after ["vllm:num_requests_running" ],0 ) 174self .assertEqual (after ["vllm:request_success_total" ],3 )# each one, not only the last to finish 175self .assertEqual (after ["vllm:e2e_request_latency_seconds_count" ],3 ) 176self .assertEqual (after ["vllm:time_to_first_token_seconds_count" ],3 ) 177self .assertEqual (svc .metrics ()["totals" ]["requests" ],3 )# the JSON agrees 178 179 180if __name__ == "__main__" : 181unittest .main ()