okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
2e8fb221c
main
1"""#1615: recognizable context-overflow errors over HTTP, without a GPU or model pack. 2 3python -m unittest serve.test_context_overflow -v 4""" 5import http .client 6import json 7import unittest 8from pathlib import Path 9from unittest import mock 10 11from serve .frontend import ChatTemplate 12from serve .server import CTX_SLACK ,ByteTokenizer ,MockEngine ,Service ,serve 13 14ROOT = Path (__file__ ).resolve ().parents [1 ] 15CTX = 131072 16APIS = (("/v1/chat/completions" ,"max_tokens" ), 17 ("/v1/messages" ,"max_tokens" ), 18 ("/v1/responses" ,"max_output_tokens" )) 19 20 21class ContextOverflow (unittest .TestCase ): 22@classmethod 23def setUpClass (cls ): 24tok = ByteTokenizer () 25cls .engine = MockEngine (tok ,"ok" ,max_context = CTX ) 26cls .svc = Service (cls .engine ,tok ,ChatTemplate (ROOT / "serve/chat_template.jinja" )) 27cls .httpd = serve (cls .svc ,port = 0 ) 28cls .port = cls .httpd .server_address [1 ] 29 30@classmethod 31def tearDownClass (cls ): 32cls .httpd .shutdown () 33cls .httpd .server_close () 34 35def setUp (self ): 36self .svc .fit_max_tokens = False 37 38def post (self ,path ,budget_key ,prompt_tokens ,max_tokens = None ,stream = False ): 39body = {"input" :"hi" }if path == "/v1/responses" else { 40"messages" : [{"role" :"user" ,"content" :"hi" }]} 41body ["stream" ]= stream 42if max_tokens is not None : 43body [budget_key ]= max_tokens 44c = http .client .HTTPConnection ("127.0.0.1" ,self .port ,timeout = 10 ) 45try : 46with mock .patch .object (self .svc ,"encode_prompt" ,return_value = [ord ("x" )]* prompt_tokens ): 47c .request ("POST" ,path ,json .dumps (body ), {"Content-Type" :"application/json" }) 48r = c .getresponse () 49return r .status ,r .getheader ("Content-Type" ),json .loads (r .read ()) 50finally : 51c .close () 52 53def test_both_overflow_errors_are_recognizable_before_streaming (self ): 54# The full prompt case reproduces #1615. fit_max_tokens cannot rescue it. 55cases = ((150722 ,None ,False ,"no room to answer" ), 56 (150722 ,16 ,True ,"no room to answer" ), 57 (150722 ,16 ,False ,"+ max tokens (16)" ), 58 (1024 ,CTX ,False ,f"+ max tokens ( { CTX } )" )) 59for path ,key in APIS : 60for stream in (False ,True ): 61for prompt ,budget ,fit ,detail in cases : 62with self .subTest (path = path ,stream = stream ,prompt = prompt ,budget = budget ,fit = fit ): 63self .svc .fit_max_tokens = fit 64with mock .patch .object (self .engine ,"generate" )as generate : 65status ,content_type ,body = self .post (path ,key ,prompt ,budget ,stream ) 66generate .assert_not_called () 67self .assertEqual (status ,400 ,body ) 68self .assertIn ("application/json" ,content_type ) 69error = body ["error" ] 70self .assertEqual (error ["type" ],"invalid_request_error" ) 71message = error ["message" ] 72# OpenAI's established wording, recognized by client overflow classifiers. 73self .assertIn ("exceeds the context window" ,message ) 74self .assertIn (f"prompt ( { prompt } tokens)" ,message ) 75self .assertIn (detail ,message ) 76self .assertIn (f"( { CTX } )" ,message ) 77self .assertIn ("requests are never truncated" ,message ) 78if "+ max tokens" in detail : 79room = max (0 ,CTX - CTX_SLACK - prompt ) 80self .assertIn (f"max_tokens (at most { room } here)" ,message ) 81self .assertIn ('"fit_max_tokens": true' ,message ) 82if path == "/v1/responses" : 83self .assertEqual (error ["code" ],"context_length_exceeded" ) 84self .assertEqual (error ["param" ],"input" ) 85else : 86self .assertEqual (set (error ), {"type" ,"message" }) 87 88def test_the_anthropic_route_says_it_the_way_anthropic_does_and_keeps_strata_s_sentence (self ): 89# #4838: Claude Code decides from the words of a 400: "prompt is too long" makes it compact, "input length and `max_tokens` exceed 90# context limit" makes it shorten max_tokens. Strata's own sentence stays after it, so the other clients' phrase is still in the message. 91for stream in (False ,True ): 92with self .subTest (stream = stream ,case = "prompt alone" ): 93status ,_ ,body = self .post ("/v1/messages" ,"max_tokens" ,150722 ,16 ,stream ) 94self .assertEqual (status ,400 ,body ) 95message = body ["error" ]["message" ] 96self .assertTrue (message .startswith (f"prompt is too long: 150722 tokens > { CTX - CTX_SLACK - 1 } maximum; " ),message ) 97self .assertIn ("request exceeds the context window" ,message ) 98self .assertEqual (body ["error" ]["type" ],"invalid_request_error" ) 99with self .subTest (stream = stream ,case = "prompt plus max_tokens" ): 100status ,_ ,body = self .post ("/v1/messages" ,"max_tokens" ,1024 ,CTX ,stream ) 101self .assertEqual (status ,400 ,body ) 102message = body ["error" ]["message" ] 103self .assertTrue (message .startswith (f"input length and `max_tokens` exceed context limit: 1024 + { CTX } > { CTX - CTX_SLACK } ; " ),message ) 104self .assertIn ("request exceeds the context window" ,message ) 105for path ,key in (("/v1/chat/completions" ,"max_tokens" ), ("/v1/responses" ,"max_output_tokens" )): 106with self .subTest (path = path ): 107status ,_ ,body = self .post (path ,key ,150722 ,16 ) 108self .assertEqual (status ,400 ,body ) 109self .assertTrue (body ["error" ]["message" ].startswith ("request exceeds the context window" ),body )# the other dialects are unchanged 110 111def test_default_service_shortens_an_overshooting_budget_in_every_dialect (self ): 112# the Service default (fit_max_tokens on): a prompt that fits is answered, streaming or not; the prompt that 113# alone leaves no room is the 400 of the strict test above 114self .assertTrue (Service (self .engine ,ByteTokenizer (),self .svc .template ).fit_max_tokens ) 115self .svc .fit_max_tokens = True 116for path ,key in APIS : 117for stream in (False ,True ): 118with self .subTest (path = path ,stream = stream ): 119if not stream :# (a 200 stream is SSE, not the JSON post() reads) 120with mock .patch .object (self .engine ,"generate" ,wraps = self .engine .generate )as generate : 121status ,_ ,body = self .post (path ,key ,1024 ,CTX ,stream ) 122self .assertEqual (status ,200 ,body ) 123self .assertEqual (generate .call_args .args [1 ],CTX - CTX_SLACK - 1024 ) 124status ,_ ,body = self .post (path ,key ,CTX - CTX_SLACK ,CTX ,stream ) 125self .assertEqual (status ,400 ,body ) 126self .assertIn ("no room to answer" ,body ["error" ]["message" ]) 127 128def test_one_token_of_room_still_answers_but_zero_is_rejected (self ): 129for path ,key in APIS : 130for fit in (False ,True ): 131with self .subTest (path = path ,fit = fit ): 132self .svc .fit_max_tokens = fit 133status ,_ ,body = self .post (path ,key ,CTX - CTX_SLACK - 1 ,1 ) 134self .assertEqual (status ,200 ,body ) 135status ,_ ,body = self .post (path ,key ,CTX - CTX_SLACK ,1 ) 136self .assertEqual (status ,400 ,body ) 137self .assertIn ("exceeds the context window" ,body ["error" ]["message" ]) 138 139def test_prepare_preserves_prompt_and_budget_limits (self ): 140ids = [ord ("x" )]* 1024 141room = CTX - CTX_SLACK - len (ids ) 142for fit in (False ,True ): 143self .svc .fit_max_tokens = fit 144for budget in (None ,0 ,- 1 ,1 ,room ,room + 1 ): 145with self .subTest (fit = fit ,budget = budget ), \ 146mock .patch .object (self .svc ,"encode_prompt" ,return_value = ids ): 147if budget == room + 1 and not fit : 148with self .assertRaises (ValueError ): 149self .svc .prepare ([],None , {},budget ) 150else : 151prepared ,_ ,maximum = self .svc .prepare ([],None , {},budget ) 152self .assertEqual (prepared ,ids ) 153self .assertEqual (maximum ,1 if budget == 1 else room ) 154 155 156if __name__ == "__main__" : 157unittest .main ()