okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Trial2 merge f-0291-gh2-app (0dfa2d9b1)2e8fb221c

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