okami.mom/strata

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

Niko1221Merge f-clean-1c (3c32937a2): launcher speed settings become engine defaults (parallel stack, GDN stack, gfx12 chunked scan, HC_Q8 on UD files, Metal fp16 for resident IQ3_S/Q2_0, hipBLASLt table on gfx1151 only); row 8 held (cleanup step 1c)ddbfa1d5c

main
59.4 KiB1126 linesraw
1"""#465: "parallel": N - several requests decode together in the engine's batch slots (--batch N).
2
3A fake engine (a Python script speaking the engine's GEN / BGEN / BT / BDONE / BADM / BSTOP lines) runs behind the
4real StrataEngine and Service, so the server's side is tested without a GPU: requests up to N run at once, more
5wait for a slot, /metrics shows the slots, each request's history row is its own, and a conversation's next turn
6goes back to the slot that holds it."""
7import json
8import sys
9import tempfile
10import threading
11import time
12import unittest
13import urllib.error
14import urllib.request
15from pathlib import Path
16from unittest import mock
17
18from serve.frontend import ChatTemplate
19from serve import server
20from serve.server import ByteTokenizer, Service, StrataEngine, engine_args, parallel_args, serve
21from strata_cli import bench
22from strata_cli.client import Endpoint
23
24# The fake engine: one token every STEP seconds per active slot (a "window" serves every active slot at once);
25# GEN (solo) streams T lines; BGEN reads the prompt (one T line, DONE), answers BADM and continues in the slot.
26# Every reply is the bytes of "ok, done." then <|im_end|> (ByteTokenizer: 257).
27FAKE_BATCH = r'''import queue, sys, threading, time
28args = sys.argv[1:]
29slots = int(args[args.index("--batch") + 1]) if "--batch" in args else 0
30fit = int(args[args.index("--fit") + 1]) if "--fit" in args else slots
31fail = "--fail-window" in args
32groups = int(args[args.index("--says-groups") + 1]) if "--says-groups" in args else 0   # INFO batch_groups=G (--batch-groups auto)        # #997: the first window over two slots fails
33STEP = 0.02
34CH = 32
35BDONE_MS = " 0.0" if "--zero-bdone-ms" in args else " 1.0"
36lines, stop = queue.Queue(), threading.Event()
37def reader():
38    for l in sys.stdin:
39        l = l.strip()
40        if l == "STOP":
41            stop.set()
42        else:
43            lines.put(l)
44    lines.put(None)
45threading.Thread(target=reader, daemon=True).start()
46print("INFO engine=0.1.39" + (f" batch_slots={fit}" if fit >= 2 else "") +
47      (" slot_cache=1" if "--slotcache" in args else "") + (f" batch_groups={groups}" if groups > 1 else ""), flush=True)
48if "--fake-stage-plan" in args:
49    print("strata serve: layer split: layers 0-11 (CUDA0), 12-23 (CUDA1), 24-35 (CUDA2), "
50          "36-47 (CUDA3), one hand-off per window", file=sys.stderr, flush=True)
51print("READY 4096 stop", flush=True)
52LONG = list(b"LONGREPLY")
53def continued(ids):        # (the whole reply, how much of it the prompt already ends with: a request continued)
54    ids = [int(x) for x in ids]
55    long_one = any(ids[i:i + len(LONG)] == LONG for i in range(len(ids))) or \
56        b"Cancellation benchmark:" in bytes(int(x) & 255 for x in ids)
57    R = list(b"ok, " + b"la " * 15 + b"done." if long_one else b"ok, done.") + [257]
58    return R, max(k for k in range(len(R)) if k == 0 or ids[-k:] == R[:k])
59def reply(ids):            # the rest of the reply after what the prompt already ends with
60    R, k = continued(ids)
61    return R[k:]
62active = {}          # slot -> [tokens left, max_new, produced]
63stopped = set()      # BSTOPped slots: they end "cancel"
64# #879: a prompt with NFSOLO / NFADMIT ends its first GEN / BGEN with DONE ... nonfinite (nothing emitted); one with
65# NFSLOT ends its slot with BDONE ... nonfinite after its second token
66fired, nf_slots = set(), set()
67def window():        # one batch window: every active slot one token
68    if fail and len(active) >= 2:     # as the engine: the reason on stdout, then exit code 1
69        print("ERR verify batch: layer 34 never rang (graph finished)", flush=True)
70        sys.exit(1)
71    processed = len(active)
72    for b in sorted(active):
73        left, max_new, produced = active[b]
74        if b in nf_slots and produced >= 2:
75            nf_slots.discard(b)
76            print(f"BDONE {b} {produced} nonfinite{BDONE_MS}", flush=True)
77            del active[b]
78            continue
79        t = left.pop(0) if left else 257
80        produced += 1
81        print(f"BT {b} {t}", flush=True)
82        if t == 257 or produced >= max_new:
83            fin = 'stop' if t == 257 else 'cancel' if b in stopped else 'length'
84            stopped.discard(b)
85            print(f"BDONE {b} {produced} {fin}{BDONE_MS}", flush=True)
86            del active[b]
87        else:
88            active[b] = [left, max_new, produced]
89    if "--fake-batch-sample" in args and processed and not active:
90        print(f"BSTAT 1 {processed} {processed} 20", flush=True)
91    if "--fake-stage-sample" in args and processed and not active:
92        print("PSTAT 4 20000 16000 14000 12000 10000", flush=True)
93log = open(args[args.index("--log") + 1], "a") if "--log" in args else None
94PPK = int(args[args.index("--pp-every") + 1]) if "--pp-every" in args else 1
95READF = "--readfield" in args   # DONE's 15th field: the prompt tokens the engine read (a continued prompt: the 1 it copies)
96REUSE = "--reuse" in args     # DONE's reused field as the engine gives it: a continued prompt is all held but its last
97def reused(ids):              # token (the request's own output included), a fresh one the first 3 tokens
98    return 0 if not REUSE else len(ids) - 1 if continued(ids)[1] else 3
99while True:
100    try:
101        line = lines.get(timeout=STEP if active else None)
102    except queue.Empty:
103        line = ""
104    if line is None or line == "QUIT":
105        break
106    if line.startswith("BYIELD "):
107        continue                              # too late: the read it was for has ended
108    if line.startswith("BSTOP "):
109        b = int(line.split()[1])
110        if b in active:
111            active[b][1] = 0
112            stopped.add(b)
113        continue
114    if line.startswith(("GEN ", "BGEN ")):
115        f = line.split()
116        slot = int(f[1]) if f[0] == "BGEN" else None
117        max_new = int(f[2] if f[0] == "BGEN" else f[1])
118        ids = f[-1].split(",")
119        if bytes(int(x) & 255 for x in ids).find(b"REFUSEME") >= 0:   # #1059: refused up front, then idle (no DONE)
120            print("ERR refused: images are not enabled", flush=True)
121            continue
122        # #1994: the engine's own view of its slots differs: BUSYSLOT is refused once, BUSYALL always
123        pbx = bytes(int(x) & 255 for x in ids)
124        if slot is not None and (b"BUSYALL" in pbx or (b"BUSYSLOT" in pbx and "busyslot" not in fired)):
125            fired.add("busyslot")
126            print(f"ERR BGEN: no such free slot (--batch {slots}) or a bad max_new", flush=True)
127            if log:
128                log.write(f"REFUSED {slot}\n"); log.flush()
129            continue
130        if log:
131            log.write(f"{f[0]} {slot} {len(ids)} {max(len(active), 0)}\n"); log.flush()
132        pb = bytes(int(x) & 255 for x in ids)
133        mark = b"NFSOLO" if f[0] == "GEN" else b"NFADMIT"
134        if mark in pb and mark not in fired:
135            fired.add(mark)
136            print(f"DONE 0 {len(ids)} 5.0 0.0 nonfinite 0 0 0", flush=True)
137            if slot is not None:
138                print(f"BADM {slot} 0", flush=True)
139            continue
140        if slot is not None and b"NFSLOT" in pb:
141            nf_slots.add(slot)
142        toks = reply(ids)
143        stop.clear()
144        # the prompt read: CH tokens a chunk, a PP line each; a BYIELD <s> gives way at a chunk boundary
145        given = None
146        for q in range(CH, len(ids) - 1, CH):
147            time.sleep(STEP / 2)
148            if (q // CH) % PPK:   # --pp-every K: a PP line and a boundary every K chunks (the pipelined groups' pieces)
149                continue
150            print(f"PP {q} {len(ids)} 1 1", flush=True)
151            held = []
152            while True:
153                try:
154                    l2 = lines.get_nowait()
155                except queue.Empty:
156                    break
157                if l2 and l2.startswith("BYIELD "):
158                    ys = int(l2.split()[1])
159                    if len(ids) - 1 - q > CH and (slot is None or ys == slot) and given is None:
160                        given = (ys, q)
161                elif l2 == "STOP":
162                    stop.set()
163                else:
164                    held.append(l2)
165            for l2 in held:
166                lines.put(l2)
167            if given:
168                break
169            if stop.is_set():
170                break
171            if active and (q // CH) % 4 == 0:     # the slots decode between the prompt's chunks (as the engine)
172                window()
173        if given:
174            if log:
175                log.write(f"YIELD {given[0]} {given[1]}\n"); log.flush()
176            print(f"YIELDED {given[0]} {given[1]}", flush=True)
177            print(f"DONE 0 {len(ids)} 5.0 0.0 cancel 0 0 {reused(ids)}", flush=True)
178            if slot is not None:
179                print(f"BADM {slot} 0", flush=True)
180            continue
181        n = 1 if slot is not None else max_new
182        out = 0
183        for t in toks[:n]:
184            if stop.is_set():
185                break
186            print(f"T {t}", flush=True)
187            out += 1
188            time.sleep(STEP)
189        fin = "stop" if out and toks[out - 1] == 257 else ("cancel" if stop.is_set() else "length")
190        print(f"DONE {out} {len(ids)} 5.0 {out * STEP * 1000:.1f} {fin} 0 0 {reused(ids)}" +
191              (f" 0 0 0 0 0.0 {len(ids) - reused(ids)}" if READF else ""), flush=True)
192        if slot is not None:
193            cont = fin == "length" and max_new > 1
194            if cont:
195                active[slot] = [toks[1:], max_new, 1]
196            print(f"BADM {slot} {1 if cont else 0}", flush=True)
197        continue
198    if line:
199        print("ERR unknown " + line[:20], flush=True)
200        continue
201    window()
202'''
203
204
205class ParallelArgs(unittest.TestCase):
206    def test_parallel_config_key(self):
207        self.assertEqual(parallel_args({"parallel": 4}, []), ["--batch", "4"])
208        self.assertEqual(parallel_args({"parallel": 1}, []), [])
209        self.assertEqual(parallel_args({}, []), [])
210        self.assertEqual(parallel_args({"parallel": 2}, ["--batch", "3"]), [])       # the args' own value wins
211        self.assertEqual(parallel_args({"parallel": "4"}, []), [])                   # said and ignored
212        self.assertEqual(parallel_args({"parallel": True}, []), [])
213        self.assertEqual(parallel_args({"parallel": 12}, []), ["--batch", "12"])     # the engine warns and caps
214    def test_parallel_above_the_window_says_so_unless_batch_mtp(self):
215        import contextlib, io, os
216        def said(args, env):
217            buf = io.StringIO()
218            old = os.environ.get("STRATA_BATCH_MTP")
219            if env is None:
220                os.environ.pop("STRATA_BATCH_MTP", None)
221            else:
222                os.environ["STRATA_BATCH_MTP"] = env
223            try:
224                with contextlib.redirect_stdout(buf):
225                    r = parallel_args({"parallel": 12}, args)
226            finally:
227                if old is None:
228                    os.environ.pop("STRATA_BATCH_MTP", None)
229                else:
230                    os.environ["STRATA_BATCH_MTP"] = old
231            self.assertEqual(r, ["--batch", "12"])
232            return "at most" in buf.getvalue()
233        self.assertTrue(said([], None))                  # 0.1.39: the window holds 8 rows
234        self.assertTrue(said([], "0"))
235        self.assertFalse(said(["--batch-mtp"], None))    # --batch-mtp waves more through the window
236        self.assertFalse(said([], "1"))
237
238        args = engine_args({"args": ["--pack", "p"], "parallel": 2})
239        self.assertEqual(args[-2:], ["--batch", "2"])
240
241
242class DFlash2ChosenWithRequests(unittest.TestCase):
243    """Owner 2026-11-03: the person's own choice wins. DFlash2 chosen by name + a number of requests = `--draft dflash2 --draft-fallback none --batch N` (the engine runs a
244    drafter per request); DFlash2 alone = one request; Auto and the MTP are as they were. Nothing is started: the arguments the server builds."""
245
246    BASE = ["--pack", "/d/packs/x", "--native", "/m/x.gguf", "--mtp", "/d/mtp/rt", "--spec", "4", "--spec-min-p", "0.5", "--batch-mtp"]
247
248    def build(self, **cfg):
249        import contextlib
250        import io
251        from strata_control import drafting
252        shaped = {"model_name": "qwen3.8-flash-next-gyro-gyro-s", "args": list(self.BASE), **cfg}
253        patches = (mock.patch.object(drafting, "detect_hardware", return_value=("cuda", ["sm_120"])), mock.patch.object(drafting, "pack_ready", return_value=True),
254                   mock.patch.object(drafting, "vocab_path", return_value=Path("/d/draft_vocab.bin")), mock.patch.object(drafting, "mtp_ready", return_value=True),
255                   mock.patch("serve.server.drafting_vram_mib", return_value=None), contextlib.redirect_stdout(io.StringIO()))
256        with contextlib.ExitStack() as stack:
257            for patch in patches:
258                stack.enter_context(patch)
259            args = engine_args(shaped, None)
260        return args, drafting.take_note()
261
262    def value(self, args, flag):
263        return args[args.index(flag) + 1] if flag in args else None
264
265    def test_dflash2_by_name_with_a_number_of_requests_runs_dflash2_with_that_many(self):
266        for n in (2, 4, 8):
267            args, note = self.build(drafting="dflash2", parallel=n)
268            self.assertEqual((self.value(args, "--draft"), self.value(args, "--draft-fallback"), self.value(args, "--batch")), ("dflash2", "none", str(n)), n)
269            self.assertNotIn("--mtp", args)
270            self.assertNotIn("--batch-mtp", args)
271            self.assertEqual(note, "", "no 'isn't available in this mode' line where DFlash2 now runs")
272
273    def test_the_number_in_the_saved_arguments_is_the_same_word(self):
274        args, note = self.build(drafting="dflash2", args=[*self.BASE, "--batch", "4"])
275        self.assertEqual((self.value(args, "--draft"), self.value(args, "--batch"), args.count("--batch")), ("dflash2", "4", 1))
276        self.assertEqual(note, "")
277
278    def test_dflash2_by_name_without_a_number_is_one_request(self):
279        for extra in ({}, {"parallel": 1}):
280            args, note = self.build(drafting="dflash2", **extra)
281            self.assertEqual(self.value(args, "--draft"), "dflash2", extra)
282            self.assertNotIn("--batch", args)
283            self.assertEqual(note, "")
284
285    def test_auto_with_several_requests_keeps_the_mtp(self):
286        args, note = self.build(parallel=4)
287        self.assertNotIn("--draft", args)
288        self.assertEqual((self.value(args, "--mtp"), self.value(args, "--batch")), ("/d/mtp/rt", "4"))
289        self.assertEqual(note, "DFlash2 isn't available in this mode")
290        args, note = self.build(drafting="auto", parallel=4)
291        self.assertNotIn("--draft", args)
292
293    def test_the_mtp_by_name_is_unchanged(self):
294        args, note = self.build(drafting="mtp", parallel=4)
295        self.assertNotIn("--draft", args)
296        self.assertEqual((self.value(args, "--mtp"), self.value(args, "--batch"), note), ("/d/mtp/rt", "4", ""))
297
298    def test_a_layer_split_runs_it_too(self):
299        args, note = self.build(drafting="dflash2", parallel=4, gpu=[0, 1])
300        self.assertEqual((self.value(args, "--draft"), self.value(args, "--batch"), "--layer-split" in args, note), ("dflash2", "4", True, ""))
301        args, note = self.build(parallel=4, gpu=[0, 1])
302        self.assertNotIn("--draft", args)                    # Auto: still the MTP for several requests
303
304    def test_the_all_cards_split_engine_run_config_keeps_its_dflash2_flags_and_the_persons_lanes(self):
305        split = ["--native", "/m/x.gguf", "--draft", "dflash2", "--draft-model", "/d/p.pack", "--draft-vocab", "/e/draft_vocab_en.bin", "--max-context", "131072",
306                 "--spec", "6", "--lookup", "15", "--conversation-cache-mib", "4096", "--batch", "6"]
307        args, note = self.build(args=list(split), drafting="dflash2", split_engine_note="Using the all-cards split engine on 2 cards.", gpu=[0, 1], parallel=3)
308        self.assertEqual(args[:len(split) - 2], split[:-2], "nothing added or taken out")
309        self.assertEqual((self.value(args, "--batch"), "--mtp" in args, "--draft-fallback" in args, note), ("3", False, False, ""))
310        args, _ = self.build(args=list(split), drafting="dflash2", split_engine_note="x", gpu=[0, 1])
311        self.assertEqual(self.value(args, "--batch"), "6")
312
313
314class PickSlot(unittest.TestCase):
315    def engine(self, n):
316        e = StrataEngine("missing-executable", [], lazy=True)
317        e.batch = n
318        e.slot_order = list(range(n))
319        e.slot_busy = [False] * n
320        e.slot_held = [[] for _ in range(n)]
321        e.slot_used = [0.0] * n
322        e.slot_live = [None] * n
323        e.slot_group = [0] * n
324        return e
325
326    def test_the_slot_that_holds_the_conversation(self):
327        e = self.engine(3)
328        e.slot_held = [[1, 2, 3], [], [1, 2, 3, 4, 5]]
329        e.slot_used = [5.0, 0.0, 9.0]
330        self.assertEqual(e.pick_slot([1, 2, 3, 4, 5, 6]), 2)       # the longest held start
331        self.assertEqual(e.pick_slot([1, 2, 3, 9]), 0)
332        self.assertEqual(e.pick_slot([7, 8]), 1)                    # no match: the empty slot first
333        e.slot_busy[1] = True
334        self.assertEqual(e.pick_slot([7, 8]), 0)                    # then the one used longest ago
335        e.slot_busy = [True] * 3
336        self.assertIsNone(e.pick_slot([7, 8]))
337        e.slot_busy = [False] * 3
338        self.assertEqual(e.pick_slot([1, 2, 3]), 1)                 # a held prompt is never the WHOLE prompt
339
340    def test_a_rewritten_next_turn_goes_to_the_slot_of_its_chat(self):
341        # #2518: two chats in two slots; each next turn renders the history again but not the reply it decoded or the
342        # assistant header, so the held stream (prompt + reply) is no start of it.  The engine's turn checkpoint sits at
343        # the last <|im_start|> of the old prompt: the prompt that agrees up to there belongs to that slot.  Before, both
344        # went to the least recently used slot in turn, and the first one overwrote the other chat's cache.
345        T = StrataEngine.TURN_ID
346        hist_a, hist_b = list(range(1000, 1600)), list(range(2000, 2600))
347        held_a = hist_a + [T, 7, 8, 9] + [50, 51, 52]                  # prompt (ends with the assistant header) + reply
348        held_b = hist_b + [T, 7, 8, 9] + [60, 61]
349        e = self.engine(2)
350        e.slot_held = [held_a, held_b]
351        e.slot_used = [10.0, 20.0]                                      # slot 0 was used longer ago
352        next_a = hist_a + [T, 5, 6, 7, 8, 9] + list(range(3000, 3100))  # the history again, then new turns
353        next_b = hist_b + [T, 5, 6, 7, 8, 9] + list(range(3000, 3100))
354        self.assertEqual(e.pick_slot(next_b), 1)                        # the LRU slot 0 holds the other chat
355        self.assertEqual(e.pick_slot(next_a), 0)
356        e.slot_busy[0] = True                                           # a busy slot is never picked
357        self.assertEqual(e.pick_slot(next_a), 1)
358        e.slot_busy[0] = False
359        # a chat that agrees with neither (a new one, or one that rewrote its history) keeps the old order
360        self.assertEqual(e.pick_slot(list(range(5000, 5200))), 0)
361        self.assertEqual(e.pick_slot(hist_a[:300] + [T, 5, 6] + list(range(3000, 3100))), 0)
362        e.slot_held[0] = []                                             # an empty slot still comes before evicting one
363        self.assertEqual(e.pick_slot(list(range(5000, 5200))), 0)
364        # the whole held stream continued is still the longer match
365        e.slot_held = [held_a, held_b + [T, 1, 2]]
366        self.assertEqual(e.pick_slot(held_b + [T, 1, 2, 3, 4]), 1)
367
368    # ---- #2518: a branching follow-up (same history, the last question replaced) belongs to the slot of its chat
369    @staticmethod
370    def chat(base, turns=12, per=800):
371        """A chat history of `turns` messages of `per` tokens each (every one opens with the turn marker), token ids
372        distinct from any other chat's; ~9600 tokens, so its earlier message boundaries are past 8192."""
373        T = StrataEngine.TURN_ID
374        out = []
375        for m in range(turns):
376            out += [T] + list(range(base + m * per, base + m * per + per - 1))
377        return out
378
379    def held_of(self, hist, q, reply):
380        """what a slot holds after a request: the prompt (history, the question, the assistant header) and the reply"""
381        T = StrataEngine.TURN_ID
382        return hist + [T] + q + [T, 7, 8, 9] + reply
383
384    def branch_of(self, hist, q):
385        T = StrataEngine.TURN_ID
386        return hist + [T] + q + [T, 7, 8, 9]
387
388    def test_a_branch_goes_to_its_earlier_message_boundary(self):
389        T = StrataEngine.TURN_ID
390        hists = [self.chat(100000 * (i + 1)) for i in range(4)]
391        e = self.engine(4)
392        e.slot_held = [self.held_of(h, [31, 32, 33], [50, 51]) for h in hists]
393        e.slot_used = [1.0, 2.0, 3.0, 4.0]                              # slot 0 is the least recently used
394        for owner in (1, 2, 3, 0):
395            branch = self.branch_of(hists[owner], [61, 62, 63, 64])    # another final question, the same history
396            self.assertEqual(e.pick_slot(branch), owner, owner)
397        # a pure append of the held stream and the engine's own turn rule are unchanged
398        self.assertEqual(e.pick_slot(e.slot_held[2] + [T, 1, 2, 3]), 2)
399        self.assertEqual(e.pick_slot(self.branch_of(hists[1], [31, 32, 33])), 1)
400
401    def test_a_branch_never_takes_a_busy_owner(self):
402        hists = [self.chat(100000 * (i + 1)) for i in range(3)]
403        e = self.engine(3)
404        e.slot_held = [self.held_of(h, [31], [50]) for h in hists]
405        e.slot_used = [1.0, 2.0, 3.0]
406        e.slot_busy[1] = True                                           # the owner is still working
407        self.assertEqual(e.pick_slot(self.branch_of(hists[1], [61, 62])), 0)    # the old order: the least recent free slot
408        e.slot_busy = [True, False, True]
409        self.assertEqual(e.pick_slot(self.branch_of(hists[1], [61, 62])), 1)
410
411    def test_a_boundary_every_chat_shares_is_no_owner(self):
412        # one client's chats share a long system prompt: its end is a boundary every slot agrees on, so it names
413        # nobody; a new chat keeps the empty slot, then the least recent one
414        T = StrataEngine.TURN_ID
415        root = self.chat(500000, turns=11)                              # ~8800 shared tokens
416        e = self.engine(4)
417        e.slot_held = [self.held_of(root + self.chat(100000 * (i + 1), turns=1), [31], [50]) for i in range(3)] + [[]]
418        e.slot_used = [5.0, 6.0, 7.0, 0.0]
419        new_chat = root + [T] + list(range(900000, 900100)) + [T, 7, 8, 9]
420        self.assertEqual(e.pick_slot(new_chat), 3)                      # the empty slot
421        e.slot_held[3] = self.held_of(root + self.chat(400000, turns=1), [31], [50])
422        e.slot_used[3] = 8.0
423        self.assertEqual(e.pick_slot(new_chat), 0)                      # then the least recently used
424
425    def test_interleaved_branches_keep_their_prefixes(self):
426        # four chats in four slots, then three rounds of branching follow-ups in an interleaved order; the engine finds
427        # the best source among ALL slots (copying it into the slot pick_slot chose, overwriting that one), so a
428        # follow-up keeps its prefix only while its chat's slot was not overwritten.  Measured: the tokens reused.
429        def old_pick(e, prompt):
430            T = StrataEngine.TURN_ID
431            free = [b for b in e.slot_order if not e.slot_busy[b]]
432            def hp(b):
433                h = e.slot_held[b]
434                if not h:
435                    return 0
436                if len(h) < len(prompt) and prompt[:len(h)] == h:
437                    return len(h)
438                k = len(h) - 1 - h[::-1].index(T) if T in h else 0
439                return k if 0 < k < len(prompt) and prompt[:k] == h[:k] else 0
440            best = max(free, key=hp)
441            if hp(best) >= 1:
442                return best
443            return min(free, key=lambda b: (bool(e.slot_held[b]), e.slot_used[b]))
444
445        def run(pick):
446            T = StrataEngine.TURN_ID
447            hists = [self.chat(100000 * (i + 1)) for i in range(4)]
448            e = self.engine(4)
449            clock = [0.0]
450            def serve(prompt, reply):
451                b = pick(e, prompt)
452                # the engine's own source search: the longest message boundary any slot holds of this prompt
453                reused = 0
454                for h in e.slot_held:
455                    k = max((i for i in range(len(h)) if h[i] == T and i < len(prompt) and prompt[:i] == h[:i]), default=0)
456                    reused = max(reused, k)
457                e.slot_held[b] = prompt + reply
458                clock[0] += 1.0
459                e.slot_used[b] = clock[0]
460                return reused
461            for i, h in enumerate(hists):                               # the first request of every chat
462                serve(self.branch_of(h, [31, 32]), [50, 51])
463            total = 0
464            for rnd in range(3):
465                for owner in (2, 0, 3, 1):                             # interleaved
466                    total += serve(self.branch_of(hists[owner], [600 + rnd, 61, 62 + owner]), [50, 51])
467            return total
468
469        old, new = run(old_pick), run(lambda e, p: e.pick_slot(p))
470        print(f"#2518 retained prefix over 12 branching follow-ups: before {old} tokens, after {new} tokens", file=sys.stderr)
471        self.assertGreater(new, old)
472        self.assertEqual(new, 12 * (len(self.chat(1)) + 0))             # every follow-up resumed at its history's end
473
474    def test_batch_groups_spread_requests_over_the_groups(self):
475        # #1249: with --batch-groups 2 over 4 slots (groups {0,1} and {2,3}) a second request goes to the other group,
476        # and a short held prefix does not pull it back into the busy one
477        e = self.engine(4)
478        e.slot_groups = 2
479        e.slot_group = [0, 0, 1, 1]
480        e.slot_busy[0] = True
481        e.slot_held[1] = [1, 2, 3]
482        self.assertEqual(e.pick_slot([1, 2, 3, 4, 5]), 2)
483        e.slot_held[1] = list(range(1, 601))                       # a long prefix is worth the unbalanced group
484        self.assertEqual(e.pick_slot(list(range(1, 700))), 1)
485        e.slot_groups, e.slot_group = 1, [0] * 4                   # without groups: any held prefix, as before
486        e.slot_held[1] = [1, 2, 3]
487        self.assertEqual(e.pick_slot([1, 2, 3, 4, 5]), 1)
488
489    def test_slots_view(self):
490        e = self.engine(2)
491        e.slot_held[1] = [1, 2]
492        e.slot_live[0] = {"slot": 0, "state": "decoding", "prompt_tokens": 9, "generated": 4,
493                          "started": time.time() - 2, "first_token": time.time() - 1}
494        v = e.slots_view()
495        self.assertEqual(v[0]["state"], "decoding")
496        self.assertEqual(v[0]["generated"], 4)
497        self.assertEqual(v[1], {"slot": 1, "state": "idle", "held_tokens": 2})
498
499
500class FakeEngineCase(unittest.TestCase):
501    """The real StrataEngine and Service over HTTP, the fake engine behind them."""
502
503    def start(self, slots, fit=None, slot_cache=False, fail=False, reuse=False, says_groups=0,
504              more=(), stage_plan=False, batch_sample=False, stage_sample=False):
505        import serve.server as server
506        self.tmp = tempfile.TemporaryDirectory()
507        script = Path(self.tmp.name) / "fake_strata.py"
508        script.write_text(FAKE_BATCH, encoding="utf-8")
509        self.log = Path(self.tmp.name) / "requests.log"
510        real = server.subprocess.Popen
511        extra = ["--batch", str(slots)] + (["--fit", str(fit)] if fit is not None else []) + ["--log", str(self.log)]
512        extra += ["--slotcache"] if slot_cache else []
513        extra += ["--fail-window"] if fail else []
514        extra += ["--reuse"] if reuse else []
515        extra += ["--says-groups", str(says_groups)] if says_groups else []
516        extra += ["--fake-stage-plan"] if stage_plan else []
517        extra += ["--fake-batch-sample"] if batch_sample else []
518        extra += ["--fake-stage-sample"] if stage_sample else []
519        extra += list(more)
520        with mock.patch.object(server.subprocess, "Popen",
521                               lambda cmd, **kw: real([sys.executable, str(script), *cmd[1:]], **kw)):
522            self.engine = StrataEngine("strata", extra, log=str(Path(self.tmp.name) / "engine.log") if stage_plan else None)
523        tok = ByteTokenizer()
524        self.svc = Service(self.engine, tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja"))
525        self.httpd = serve(self.svc, port=0)
526        self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}"
527
528    def tearDown(self):
529        if getattr(self, "httpd", None):
530            self.httpd.shutdown()
531            self.httpd.server_close()
532        if getattr(self, "engine", None):
533            self.engine.unload()
534        if getattr(self, "tmp", None):
535            self.tmp.cleanup()
536
537    def chat(self, text, max_tokens=64):
538        body = {"messages": [{"role": "user", "content": text}], "max_tokens": max_tokens, "reasoning_effort": "none"}
539        req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(),
540                                     headers={"Content-Type": "application/json"})
541        with urllib.request.urlopen(req, timeout=60) as r:
542            return json.loads(r.read().decode())
543
544    def message(self, text, max_tokens=64):
545        body = {"model": "m", "messages": [{"role": "user", "content": text}], "max_tokens": max_tokens}
546        req = urllib.request.Request(self.base + "/v1/messages", data=json.dumps(body).encode(),
547                                     headers={"Content-Type": "application/json", "anthropic-version": "2023-06-01"})
548        with urllib.request.urlopen(req, timeout=60) as r:
549            return json.loads(r.read().decode())
550
551    def get(self, path):
552        with urllib.request.urlopen(self.base + path, timeout=10) as r:
553            return json.loads(r.read().decode())
554
555    def _two_at_once(self, text_b):
556        """A long request first, then one that has to go to a batch slot (the engine is busy with the first)."""
557        out = {}
558        def go(k, text):
559            try:
560                out[k] = ("ok", self.chat(text, max_tokens=64))
561            except urllib.error.HTTPError as e:
562                out[k] = ("http", e.code, e.read().decode(), dict(e.headers))
563        ta = threading.Thread(target=go, args=("a", "LONGREPLY please"))
564        ta.start()
565        time.sleep(0.15)
566        tb = threading.Thread(target=go, args=("b", text_b))
567        tb.start()
568        ta.join(30); tb.join(30)
569        return out
570
571    def race(self, first, second, delay=0.15, max_tokens=64):
572        """`first` sent, `second` after `delay` seconds; -> {text: (reply, seconds it took)}"""
573        res = {}
574
575        def go(t):
576            t0 = time.time()
577            r = self.chat(t, max_tokens=max_tokens)
578            res[t] = (r["choices"][0]["message"]["content"], time.time() - t0)
579        a = threading.Thread(target=go, args=(first,))
580        a.start()
581        time.sleep(delay)
582        go(second)
583        a.join(30)
584        return res
585
586
587class BatchLegAccounting(FakeEngineCase):
588    """The admission's DONE times one token; BDONE counts that token but times only the slot."""
589
590    def queued_chats(self, texts=("first", "second"), max_tokens=10, stop=None):
591        replies, errors = {}, []
592
593        def request(text):
594            body = {"messages": [{"role": "user", "content": text}], "max_tokens": max_tokens,
595                    "reasoning_effort": "none", **({"stop": [stop]} if stop else {})}
596            req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(),
597                                         headers={"Content-Type": "application/json"})
598            try:
599                with urllib.request.urlopen(req, timeout=15) as response:
600                    replies[text] = json.loads(response.read())
601            except Exception as error:
602                errors.append(repr(error))
603
604        workers = [threading.Thread(target=request, args=(text,)) for text in texts]
605        # Both requests must be waiting before either takes control: the first cannot take the solo shortcut.
606        with self.engine.ctl:
607            for worker in workers:
608                worker.start()
609            deadline = time.monotonic() + 3
610            while self.engine.waiting < 2 and time.monotonic() < deadline:
611                time.sleep(0.01)
612            self.assertEqual(self.engine.waiting, 2)
613        for worker in workers:
614            worker.join(15)
615            self.assertFalse(worker.is_alive())
616        self.assertEqual(errors, [])
617        self.assertEqual(len(replies), 2)
618        self.assertEqual([line.split()[0] for line in self.log.read_text().splitlines()][:2], ["BGEN", "BGEN"])
619        return replies
620
621    def test_eos_adds_admission_time_without_counting_its_token_twice(self):
622        self.start(2)
623        with mock.patch.object(server, "EOS_IDS", {257}):
624            replies = self.queued_chats()
625        for reply in replies.values():
626            timings = reply["timings"]
627            self.assertEqual((timings["predicted_n"], timings["predicted_ms"]), (10, 21.0))
628            self.assertEqual(timings["predicted_per_second"], 476.2)
629        metrics = self.get("/metrics")
630        self.assertEqual([(row["engine_generated"], row["decode_ms"]) for row in metrics["requests"]],
631                         [(10, 21.0), (10, 21.0)])
632        self.assertEqual(metrics["totals"]["decode_ms"], 42.0)
633
634    def test_length_finish_also_adds_admission_time(self):
635        self.start(2)
636        for reply in self.queued_chats(max_tokens=8).values():
637            self.assertEqual((reply["timings"]["predicted_n"], reply["timings"]["predicted_ms"]), (8, 21.0))
638
639    def test_zero_slot_time_is_known_and_still_includes_admission(self):
640        self.start(2, more=("--zero-bdone-ms",))
641        with mock.patch.object(server, "EOS_IDS", {257}):
642            replies = self.queued_chats()
643        for reply in replies.values():
644            self.assertEqual(reply["timings"]["predicted_ms"], 20.0)
645
646    def assert_incomplete_after_stop(self, stop):
647        self.start(2)
648        replies = self.queued_chats(stop=stop)
649        for reply in replies.values():
650            self.assertIsNone(reply["timings"]["predicted_ms"])
651            self.assertIsNone(reply["timings"]["predicted_per_second"])
652        for row in self.get("/metrics")["requests"]:
653            self.assertIsNone(row["engine_generated"])
654            self.assertIsNone(row["decode_ms"])
655            self.assertIsNone(row["decode_tok_s"])
656        self.assertEqual(self.get("/metrics")["totals"]["decode_ms"], 0.0)
657
658    def test_close_at_admission_token_does_not_publish_partial_totals(self):
659        self.assert_incomplete_after_stop("o")
660
661    def test_close_in_slot_does_not_publish_partial_totals(self):
662        self.assert_incomplete_after_stop("k, ")
663
664    def test_slot_to_solo_carry_includes_admission_once(self):
665        self.start(2, slot_cache=True)
666        with mock.patch.object(server, "EOS_IDS", {257}):
667            replies = self.queued_chats(("short", "LONGREPLY"), max_tokens=200)
668        lines = [line.split() for line in self.log.read_text().splitlines()]
669        solos = [line for line in lines if line[0] == "GEN"]
670        self.assertEqual(len(solos), 1, lines)
671        prompt_lengths = [int(line[2]) for line in lines if line[0] == "BGEN"]
672        slot_tokens = int(solos[0][2]) - max(prompt_lengths)
673        self.assertGreaterEqual(slot_tokens, 2)
674        self.assertLess(slot_tokens, 55)
675        # "ok, " + 15 * "la " + "done." + EOS: 55 total tokens. The solo leg times its remaining tokens at 20 ms each.
676        expected_ms = 21.0 + (55 - slot_tokens) * 20.0
677        reply = replies["LONGREPLY"]
678        self.assertEqual((reply["timings"]["predicted_n"], reply["timings"]["predicted_ms"]), (55, expected_ms))
679        row = max(self.get("/metrics")["requests"], key=lambda item: item["output_tokens"])
680        self.assertEqual((row["engine_generated"], row["decode_ms"]), (55, expected_ms))
681
682
683class ParallelService(FakeEngineCase):
684    """The real StrataEngine and Service over HTTP, the fake engine behind them: slots, queues, benchmarks, telemetry.
685    The yielding, restart and failure tests are in serve/test_parallel_yield.py (this file alone ran past 100 s)."""
686
687    def test_bgen_refused_by_the_engine_is_retried_not_a_400(self):
688        """#1994: the engine refuses a BGEN ("no such free slot") although the server saw the slot free: the request
689        goes to another slot (or waits) and is answered; the same conversation's next turn works too."""
690        self.start(2)
691        self.engine.SLOT_PARK_S = 0.2
692        out = self._two_at_once("BUSYSLOT hello")
693        self.assertEqual(out["b"][0], "ok", out["b"])
694        self.assertIn("REFUSED", self.log.read_text())
695        again = self.chat("BUSYSLOT hello")                     # the conversation is not poisoned
696        self.assertEqual(again["choices"][0]["message"]["content"], "ok, done.")
697        time.sleep(0.5)
698        self.assertEqual(self.engine.slot_busy, [False, False])
699
700    def test_bgen_refused_for_good_is_a_retryable_503_and_frees_the_slots(self):
701        """#1994: when the engine keeps refusing, the answer is a 503 (retryable), never a 400, and no slot stays busy.
702        #3040 / #5044: the refused admission keeps an error row but is not a completed request (no prompt tokens, no
703        part in the totals)."""
704        self.start(2)
705        self.engine.SLOT_PARK_S = 0.05
706        out = self._two_at_once("BUSYALL hello")
707        self.assertEqual(out["b"][0], "http", out["b"])
708        self.assertEqual(out["b"][1], 503, out["b"])
709        metrics = self.get("/metrics")
710        refused = [row for row in metrics["requests"] if row["output_tokens"] == 0]
711        self.assertEqual(len(refused), 1, metrics["requests"])
712        self.assertEqual((refused[0]["finish"], refused[0]["prompt_tokens"], refused[0]["prompt_read"]),
713                         ("error", 0, None))
714        self.assertEqual(metrics["totals"]["requests"], 1, "only the admitted request counts")
715        time.sleep(0.5)
716        self.assertEqual(self.engine.slot_busy, [False, False])
717        self.assertEqual(self.chat("fine again")["choices"][0]["message"]["content"], "ok, done.")
718        self.assertEqual(self.get("/metrics")["totals"]["requests"], 2, "a later admitted request counts")
719
720    def test_engine_reports_fewer_slots(self):
721        self.start(4, fit=2)
722        self.assertEqual(self.engine.batch, 2)
723        self.assertEqual(self.get("/v1/status")["concurrency"]["serving"], 2)
724
725    def test_admission_cap_uses_effective_slots_and_rejects_before_stream(self):
726        self.start(4, fit=2)
727        self.svc.max_queue = 1
728        self.assertEqual(self.svc.admission_limit(), 3)
729        self.assertTrue(all(self.svc.reserve_inference() for _ in range(3)))
730        cases = (
731            ("/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}], "stream": True}),
732            ("/v1/messages", {"model": "m", "max_tokens": 8,
733                              "messages": [{"role": "user", "content": "hi"}], "stream": True}),
734            ("/v1/responses", {"model": "m", "input": "hi", "stream": True}),
735        )
736        try:
737            for path, body in cases:
738                req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(),
739                                             headers={"Content-Type": "application/json"})
740                with self.assertRaises(urllib.error.HTTPError) as caught:
741                    urllib.request.urlopen(req, timeout=10)
742                err = caught.exception
743                self.assertEqual(err.code, 429)
744                self.assertEqual(err.headers.get("Retry-After"), "1")
745                self.assertIn("admission_full", err.read().decode())
746            snapshot = self.get("/v1/telemetry")["work"]
747            self.assertEqual((snapshot["admission_reserved"], snapshot["admission_limit"],
748                              snapshot["max_queue"], snapshot["admission_rejected"]), (3, 3, 1, 3))
749        finally:
750            for _ in range(3):
751                self.svc.release_inference()
752        self.assertEqual(self.chat("capacity freed")["choices"][0]["message"]["content"], "ok, done.")
753        self.assertEqual(self.get("/v1/telemetry")["work"]["admission_reserved"], 0)
754
755    def test_queue_timeout_serial_fifo_returns_429_and_recovers(self):
756        self.start(1)
757        self.svc.queue_timeout_s = 0.12
758        self.svc.max_queue = 1
759        self.svc.fifo.acquire()
760        try:
761            with self.assertRaises(urllib.error.HTTPError) as caught:
762                self.chat("waiting for serial turn")
763            self.assertEqual(caught.exception.code, 429)
764            self.assertEqual(caught.exception.headers.get("Retry-After"), "1")
765            self.assertEqual(json.loads(caught.exception.read())["error"]["code"], "queue_wait_timeout")
766            work = self.get("/v1/telemetry")["work"]
767            self.assertEqual((work["queue_timeout_s"], work["queue_timeouts"], work["queued"]),
768                             (0.12, 1, 0))
769        finally:
770            self.svc.fifo.release()
771        self.assertEqual(self.chat("next turn")["choices"][0]["message"]["content"], "ok, done.")
772        self.assertEqual(self.get("/v1/telemetry")["work"]["admission_reserved"], 0)
773
774    def test_queue_timeout_parallel_control_and_stream_formats(self):
775        self.start(2)
776        self.svc.queue_timeout_s = 0.12
777        self.svc.max_queue = 1
778        self.engine.ctl.acquire()
779        cases = (
780            ("/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}]}, "data: "),
781            ("/v1/messages", {"model": "m", "max_tokens": 8,
782                              "messages": [{"role": "user", "content": "hi"}]}, "event: error"),
783            ("/v1/responses", {"model": "m", "input": "hi"}, "event: response.failed"),
784        )
785        try:
786            for path, body, marker in cases:
787                for stream in (False, True):
788                    req = urllib.request.Request(self.base + path,
789                                                 data=json.dumps({**body, "stream": stream}).encode(),
790                                                 headers={"Content-Type": "application/json"})
791                    if stream:
792                        with urllib.request.urlopen(req, timeout=10) as response:
793                            data = response.read().decode()
794                        self.assertIn(marker, data)
795                        self.assertIn("queue_wait_timeout", data)
796                    else:
797                        with self.assertRaises(urllib.error.HTTPError) as caught:
798                            urllib.request.urlopen(req, timeout=10)
799                        self.assertEqual(caught.exception.code, 429)
800                        self.assertIn("queue_wait_timeout", caught.exception.read().decode())
801            work = self.get("/v1/telemetry")["work"]
802            self.assertEqual(work["queue_timeouts"], 6)
803            self.assertEqual((work["admission_reserved"], work["waiting"]), (0, 0))
804        finally:
805            self.engine.ctl.release()
806        self.assertEqual(self.chat("healthy")["choices"][0]["message"]["content"], "ok, done.")
807
808    def test_queue_timeout_parallel_slot_wait_releases_control(self):
809        self.start(2)
810        self.svc.queue_timeout_s = 0.12
811        with self.engine.slot_cv:
812            self.engine.slot_busy[:] = [True, True]
813        try:
814            with self.assertRaises(urllib.error.HTTPError) as caught:
815                self.chat("waiting for a batch slot")
816            self.assertEqual(caught.exception.code, 429)
817            self.assertIn("queue_wait_timeout", caught.exception.read().decode())
818            self.assertFalse(self.engine.ctl.locked())
819            self.assertEqual(self.engine.waiting, 0)
820        finally:
821            with self.engine.slot_cv:
822                self.engine.slot_busy[:] = [False, False]
823                self.engine.slot_cv.notify_all()
824        self.assertEqual(self.chat("slot freed")["choices"][0]["message"]["content"], "ok, done.")
825
826    def test_benchmark_overload_suite_preserves_batch_recovery(self):
827        self.start(2)
828        self.svc.max_queue = 0
829        self.svc.queue_timeout_s = 0.15
830        out = Path(self.tmp.name) / "overload"
831        report = bench.run(Endpoint(self.base, None), Endpoint(self.base, None), out,
832                           suite="parallel-overload-v1", concurrency=6)
833        self.assertTrue(report["successful"])
834        overload = report["phases"][1]
835        self.assertEqual(overload["kind"], "overload")
836        self.assertGreater(overload["summary"]["expected_overload"], 0)
837        self.assertEqual(overload["summary"]["failed"], 0)
838        self.assertTrue(report["phases"][2]["passed"])
839        self.assertEqual(self.get("/v1/telemetry")["work"]["admission_reserved"], 0)
840
841    def test_benchmark_cancel_suite_releases_batch_queue_and_slots(self):
842        self.start(2)
843        self.svc.max_queue = 1
844        self.svc.queue_timeout_s = 5
845        out = Path(self.tmp.name) / "cancel"
846        report = bench.run(Endpoint(self.base, None), Endpoint(self.base, None), out,
847                           suite="parallel-cancel-v1", concurrency=2, request_timeout=15)
848        self.assertTrue(report["successful"], bench.format_summary(bench.summary(report)))
849        self.assertEqual([row["kind"] for row in report["phases"]],
850                         ["warmup", "cancel_active", "cancel_queued", "recovery"])
851        self.assertEqual(report["phases"][2]["summary"]["companion_successful"], 2)
852        self.assertEqual(self.get("/v1/telemetry")["work"]["admission_reserved"], 0)
853
854    def test_benchmark_prefill_cancel_observes_progress_and_companion_completion(self):
855        self.start(2)
856        out = Path(self.tmp.name) / "prefill-cancel"
857        report = bench.run(Endpoint(self.base, None), Endpoint(self.base, None), out,
858                           suite="parallel-prefill-cancel-v1", concurrency=2, request_timeout=15)
859        self.assertTrue(report["successful"], bench.format_summary(bench.summary(report)))
860        self.assertEqual([row["kind"] for row in report["phases"]],
861                         ["warmup", "cancel_prefill", "recovery"])
862        phase = report["phases"][1]
863        self.assertTrue(phase["summary"]["prompt_read_seen"])
864        self.assertGreater(phase["requests"][0]["prompt_read_at_close"], 0)
865        self.assertLess(phase["requests"][0]["prompt_read_at_close"],
866                        phase["requests"][0]["prompt_tokens_at_close"])
867        self.assertEqual(phase["summary"]["client_disconnect_delta"], 1)
868        self.assertEqual(phase["summary"]["companion_successful"], 1)
869        self.assertEqual(self.get("/v1/telemetry")["work"]["admission_reserved"], 0)
870        data = (out / "results.json").read_text()
871        self.assertNotIn("Explain how a serving system", data)
872
873    def test_telemetry_keeps_engine_waiting_age_visible(self):
874        self.start(2)
875        self.svc.max_queue = 1
876        self.svc.queue_timeout_s = 0.5
877        self.engine.ctl.acquire()
878        outcome = []
879        def request():
880            try:
881                self.chat("waiting")
882            except urllib.error.HTTPError as error:
883                outcome.append(error.code)
884                error.read()
885        worker = threading.Thread(target=request)
886        try:
887            worker.start()
888            cutoff = time.monotonic() + 2
889            while time.monotonic() < cutoff:
890                work = self.get("/v1/telemetry")["work"]
891                if any(row["state"] == "waiting" for row in work["requests"]):
892                    break
893                time.sleep(0.01)
894            else:
895                self.fail("engine wait was not visible in telemetry")
896            time.sleep(0.04)
897            work = self.get("/v1/telemetry")["work"]
898            self.assertGreater(work["oldest_queue_s"], 0.03)
899            self.assertTrue(any(row["state"] == "waiting" for row in work["requests"]))
900        finally:
901            self.engine.ctl.release()
902            worker.join(timeout=3)
903        self.assertEqual(outcome, [])
904
905    def test_batch_groups_auto_follows_the_engine(self):
906        """--batch-groups auto: the engine picks the groups and says so (INFO batch_groups=G); the server spreads the
907        requests over those groups, and a plain number is read as before."""
908        self.start(8, says_groups=4, more=["--batch-groups", "auto"])
909        e = self.engine
910        self.assertEqual((e.batch, e.slot_groups), (8, 4))
911        self.assertEqual(e.slot_group, [0, 0, 1, 1, 2, 2, 3, 3])
912        self.assertEqual(e.slot_order[:4], [0, 2, 4, 6])
913        telemetry = self.get("/v1/telemetry")
914        self.assertEqual([s["group"] for s in telemetry["work"]["slots"]], [0, 0, 1, 1, 2, 2, 3, 3])
915        self.tearDown(); self.httpd = self.engine = self.tmp = None
916        self.start(8, more=["--batch-groups", "auto"])          # an engine that reports none: one group
917        self.assertEqual(self.engine.slot_groups, 1)
918        self.tearDown(); self.httpd = self.engine = self.tmp = None
919        self.start(8, more=["--batch-groups", "2"])
920        self.assertEqual(self.engine.slot_groups, 2)
921        self.tearDown(); self.httpd = self.engine = self.tmp = None
922        self.start(8, says_groups=4)                           # 0.1.41: no flag on a layer split = the engine's choice
923        self.assertEqual(self.engine.slot_groups, 4)
924        self.tearDown(); self.httpd = self.engine = self.tmp = None
925        self.start(8, says_groups=4, more=["--batch-groups", "1"])   # the opt-out
926        self.assertEqual(self.engine.slot_groups, 1)
927
928    def test_engine_log_resolves_four_stage_layer_and_device_mapping(self):
929        self.start(8, says_groups=4, stage_plan=True)
930        self.svc.terminal_visibility_order = [2, 0, 3, 1]
931        self.svc.gpu_indices = [2, 0, 3, 1]
932        telemetry = self.get("/v1/telemetry")
933        topology = telemetry["topology"]
934        self.assertEqual(topology["source"], "engine_start_log")
935        self.assertTrue(topology["resolved"])
936        self.assertEqual(telemetry["quality"]["placement"], "reported")
937        self.assertEqual([(row["stage"], row["device_index"], row["layer_start"], row["layer_end"])
938                          for row in topology["stages"]],
939                         [(0, 2, 0, 11), (1, 0, 12, 23), (2, 3, 24, 35), (3, 1, 36, 47)])
940        clean = Endpoint(self.base).snapshot()
941        self.assertEqual(clean["topology"]["stages"], topology["stages"])
942        self.svc.terminal_visibility_order = []
943        partial = self.get("/v1/telemetry")
944        self.assertFalse(partial["topology"]["resolved"])
945        self.assertEqual(len(partial["topology"]["stages"]), 4)
946        self.assertIsNone(partial["topology"]["stages"][0]["device_index"])
947        self.assertEqual(partial["quality"]["placement"], "partial")
948        self.engine.unload()
949        unloaded = self.get("/v1/telemetry")["topology"]
950        self.assertFalse(unloaded["resolved"])
951        self.assertEqual(unloaded["stages"], [])
952
953    def test_engine_batch_window_sample_reaches_telemetry_without_entering_reply(self):
954        self.start(2, batch_sample=True)
955        replies = self.race("first LONGREPLY", "second LONGREPLY", delay=0.05, max_tokens=64)
956        self.assertTrue(all("ok, " in reply for reply, _ in replies.values()))
957        self.assertTrue(any(line.startswith("BGEN") for line in self.log.read_text().splitlines()))
958        deadline = time.monotonic() + 2
959        while True:
960            telemetry = self.get("/v1/telemetry")
961            if telemetry["quality"]["batch_window_rows"] == "measured":
962                break
963            if time.monotonic() >= deadline:
964                self.fail("fake engine's BSTAT sample did not reach telemetry")
965            time.sleep(0.02)
966        work = telemetry["work"]
967        self.assertGreaterEqual(work["effective_rows_window"], 1.0)
968        self.assertLessEqual(work["effective_rows_window"], 2.0)
969        self.assertEqual(work["batch_active_rows_window"], work["effective_rows_window"])
970        self.assertEqual(work["batch_sample_windows"], 1)
971        self.assertEqual(work["batch_sample_span_s"], 0.02)
972        self.assertGreaterEqual(work["batch_sample_age_s"], 0)
973        clean = Endpoint(self.base).snapshot()
974        self.assertEqual(clean["quality"]["batch_window_rows"], "measured")
975        self.assertGreaterEqual(clean["work"]["batch_sample_rows"], 1)
976        self.engine.unload()
977        unloaded = self.get("/v1/telemetry")
978        self.assertIsNone(unloaded["work"]["effective_rows_window"])
979        self.assertEqual(unloaded["quality"]["batch_window_rows"], "unavailable")
980
981    def test_pipeline_stage_host_spans_reach_telemetry_without_entering_reply(self):
982        self.start(2, says_groups=2, stage_plan=True, stage_sample=True)
983        replies = self.race("first LONGREPLY", "second LONGREPLY", delay=0.05, max_tokens=64)
984        self.assertTrue(all("ok, " in reply for reply, _ in replies.values()))
985        deadline = time.monotonic() + 2
986        while True:
987            telemetry = self.get("/v1/telemetry")
988            if telemetry["quality"].get("stage_in_flight_source") == "engine_pstat_host_span":
989                break
990            if time.monotonic() >= deadline:
991                self.fail("fake engine's PSTAT sample did not reach telemetry")
992            time.sleep(0.02)
993        self.assertEqual(telemetry["work"]["stage_in_flight_us"], [16000, 14000, 12000, 10000])
994        clean = Endpoint(self.base).snapshot()
995        self.assertEqual(clean["quality"]["stage_in_flight"], "measured_host_span")
996        self.assertEqual([row["percent"] for row in clean["work"]["stage_in_flight"]],
997                         [80.0, 70.0, 60.0, 50.0])
998        self.engine.unload()
999        unloaded = self.get("/v1/telemetry")
1000        self.assertNotIn("stage_in_flight_us", unloaded["work"])
1001
1002    def test_a_burst_of_connections_is_not_reset(self):
1003        """30-40 clients at once got "connection reset by peer" with the listen backlog of 5 (4 x R9700 burst): the
1004        server listens with a deep backlog (STRATA_HTTP_BACKLOG, 256), so 60 simultaneous requests all get answers."""
1005        import serve.server as server
1006        self.assertGreaterEqual(server.Server.request_queue_size, 64)
1007        self.start(2)
1008        errs, ok = [], []
1009        def one(i):
1010            try:
1011                self.chat(f"burst {i}", max_tokens=8)
1012                ok.append(i)
1013            except Exception as e:                      # noqa: BLE001
1014                errs.append(repr(e))
1015        th = [threading.Thread(target=one, args=(i,)) for i in range(60)]
1016        for t in th: t.start()
1017        for t in th: t.join()
1018        self.assertEqual((len(ok), errs[:2]), (60, []))
1019
1020    def test_stop_strings_in_a_batch_slot(self):
1021        """#454: a stop string cuts the answer in --batch mode too, and the slot is freed for the next request."""
1022        self.start(2)
1023        body = {"messages": [{"role": "user", "content": "hi LONGREPLY"}], "max_tokens": 64, "reasoning_effort": "none",
1024                "stop": ["la la"]}
1025        req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(),
1026                                     headers={"Content-Type": "application/json"})
1027        with urllib.request.urlopen(req, timeout=60) as r:
1028            c = json.loads(r.read().decode())["choices"][0]
1029        self.assertEqual((c["message"]["content"], c["finish_reason"]), ("ok, ", "stop"))
1030        self.assertEqual(self.chat("again")["choices"][0]["message"]["content"], "ok, done.")
1031
1032    def test_engine_turns_batching_off(self):
1033        self.start(4, fit=0)
1034        self.assertEqual(self.engine.batch, 0)
1035        self.assertEqual(self.chat("hi")["choices"][0]["message"]["content"], "ok, done.")
1036
1037    def test_concurrent_requests_share_the_slots(self):
1038        self.start(2)
1039        # the first one decodes long enough for the others to arrive while it runs (also on a busy PC)
1040        texts = ["first question LONGREPLY", "second question, longer", "a third one waits for a slot"]
1041        reply = {t: "ok, " + "la " * 15 + "done." if "LONGREPLY" in t else "ok, done." for t in texts}
1042        out, errors, seen, terminal_seen = {}, [], [], []
1043
1044        def go(t):
1045            try:
1046                out[t] = self.chat(t)
1047            except Exception as e:   # noqa: BLE001 - reported below
1048                errors.append(e)
1049
1050        threads = [threading.Thread(target=go, args=(t,)) for t in texts]
1051        for th in threads:
1052            th.start()
1053            time.sleep(0.05)
1054        deadline = time.time() + 30
1055        while any(th.is_alive() for th in threads) and time.time() < deadline:
1056            m = self.get("/metrics")["live"]
1057            seen.append(m)
1058            terminal_seen.append(self.get("/v1/telemetry"))
1059            time.sleep(0.01)
1060        for th in threads:
1061            th.join(30)
1062        self.assertEqual(errors, [])
1063        for t in texts:
1064            self.assertEqual(out[t]["choices"][0]["message"]["content"], reply[t])
1065        # the slots were reported, and a request was admitted while another decoded in a slot (the fake logs how many
1066        # slots were active at each admission)
1067        self.assertTrue(any(m.get("parallel") == 2 and len(m.get("slots", [])) == 2 for m in seen))
1068        self.assertTrue(any(t["work"]["requests"] for t in terminal_seen))
1069        self.assertTrue(any(s.get("request_id") for t in terminal_seen for s in t["work"]["slots"]))
1070        self.assertTrue(any(isinstance(r.get("first_engine_token_s"), (int, float)) and
1071                            r["first_engine_token_s"] > 0
1072                            for t in terminal_seen for r in t["work"]["requests"]
1073                            if r["state"] == "decoding"), "live per-request first engine token was not observed")
1074        for t in terminal_seen:
1075            self.assertEqual(t["quality"]["request_correlation"], "reported")
1076            self.assertNotIn("input", json.dumps(t))
1077        admitted = [int(x.split()[3]) for x in self.log.read_text().splitlines() if x.startswith("BGEN")]
1078        self.assertIn(1, admitted)
1079        # every request recorded its own row; nothing is left running
1080        with self.svc.status_lock:
1081            self.assertEqual(len(self.svc.history), 3)
1082            self.assertEqual(self.svc.live_reqs, {})
1083            self.assertFalse(self.svc.status["busy"])
1084        self.assertEqual(sorted(r["output_tokens"] for r in self.svc.history),
1085                         sorted(len(reply[t]) + 1 for t in texts))
1086        self.assertTrue(all(isinstance(r.get("first_engine_token_s"), (int, float)) and
1087                            r["first_engine_token_s"] > 0 for r in self.svc.history))
1088        clean = Endpoint(self.base).snapshot()
1089        self.assertTrue(all(isinstance(r.get("first_engine_token_s"), (int, float))
1090                            for r in clean["recent"][:3]))
1091        # never more than two in the slots at once (the fake logs how many were active at each admission)
1092        active = [int(x.split()[3]) for x in self.log.read_text().splitlines() if x.startswith("BGEN")]
1093        self.assertTrue(all(a <= 1 for a in active), active)
1094
1095
1096
1097class EngineOwnedDefaults(unittest.TestCase):
1098    """The parallel stack, the GDN speedups, the Q8_0 hyper-connection read and the Metal fp16 windows are the engine's own defaults
1099    (src/core/arch_defaults.cpp, generate.cpp): the server adds none of them, and a value the config or the shell sets still reaches the engine."""
1100    NAMES = ("STRATA_CKPT_POOL", "STRATA_CKPT_POOL_READY", "STRATA_SLOT_CKPT_MOVE", "STRATA_SLOT_COPY_DIRECT", "STRATA_SLOT_COPY_BATCHSYNC",
1101             "STRATA_BATCH_GDN_GROUPS", "STRATA_BATCH_ATTN_ROWS", "STRATA_BATCH_SELF_COMMIT", "STRATA_QSA_SLOTS",
1102             "STRATA_GDN_TC", "STRATA_GDN_CONVL2", "STRATA_GDN_CHUNKED", "STRATA_HC_Q8", "STRATA_METAL_F16")
1103
1104    def env_for(self, cfg, base=None):
1105        import os
1106        from unittest import mock
1107        with mock.patch.dict(os.environ, base or {}, clear=False):
1108            for k in self.NAMES:
1109                if not (base and k in base):
1110                    os.environ.pop(k, None)
1111            return server.child_env(cfg)
1112
1113    def test_server_adds_none(self):
1114        for cfg in ({"parallel": 8, "args": []}, {"args": ["--batch", "4"]}, {"parallel": 8, "args": [], "backend": "hip"}, {}):
1115            env = self.env_for(cfg)
1116            for k in self.NAMES:
1117                self.assertNotIn(k, env, (k, cfg))
1118
1119    def test_explicit_values_reach_the_engine(self):
1120        env = self.env_for({"parallel": 8, "args": [], "env": {"STRATA_BATCH_GDN_GROUPS": "0"}}, {"STRATA_CKPT_POOL": "0"})
1121        self.assertEqual(env["STRATA_BATCH_GDN_GROUPS"], "0")
1122        self.assertEqual(env["STRATA_CKPT_POOL"], "0")
1123
1124
1125if __name__ == "__main__":
1126    unittest.main()