okami.mom/strata

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

Niko1221Merge f-0213-own (final daf4ac087) into f-0213-int4d482e627

main
27.4 KiB604 linesraw
1"""P0 (round 0213): streamed output must be delivered only to the request that owns it.
2
3#2892 (unbatched replicas cross DONE ownership) and #4451 (--batch: one client's stream reaches another connection).
4
5The fake engine is the one of test_parallel.py with a canary reply: the reply to a prompt is the prompt's own canary
6(two capital letters and 4 digits) repeated, so a token that reaches the wrong request is visible as a foreign canary.  Every
7test forces a LEGAL schedule with events or a hooked lock (the way serve/test_replica_lifetime.py of PR #2886 does),
8so a failure does not depend on winning a scheduler race.
9"""
10import re
11import sys
12import tempfile
13import threading
14import time
15import unittest
16from pathlib import Path
17from unittest import mock
18
19from serve.replicas import ReplicaEngine
20from serve.server import StrataEngine
21from serve.test_parallel import FAKE_BATCH
22
23CANARY_REPEAT = 60
24CANARY_RE = re.compile(rb"[A-Z]{2}\d{4}")
25
26# the fake's `continued` (the whole reply, how much of it the prompt ends with) with a canary reply: the last canary
27# of the prompt, repeated.  STEP is shortened so the many repetitions stay fast.
28CANARY_PATCH = '''
29import re as _re
30_orig_continued = continued
31def continued(ids):
32    pb = bytes(int(x) & 255 for x in ids)
33    found = _re.findall(rb"[A-Z]{2}\\d{4}", pb)
34    if found:
35        R = list((found[-1] + b" ") * %d) + [257]
36        ints = [int(x) for x in ids]
37        return R, max(k for k in range(len(R)) if k == 0 or ints[-k:] == R[:k])
38    return _orig_continued(ids)
39def reply(ids):
40    R, k = continued(ids)
41    return R[k:]
42''' % CANARY_REPEAT
43
44
45def canary_script(step=0.004):
46    text = FAKE_BATCH.replace("STEP = 0.02", f"STEP = {step}")
47    # SLOWPREFILL in a prompt: its read takes a while (a cancel can land inside it).  DEAFSTOP: the engine reads the
48    # whole prompt whatever STOP says and then goes on as if it had not come (a drain that does not get its line in time).
49    old = "        given = None\n        for q in range(CH, len(ids) - 1, CH):\n            time.sleep(STEP / 2)\n"
50    assert old in text
51    text = text.replace(old, "        given = None\n        pbm = bytes(int(x) & 255 for x in ids)\n"
52                        "        slow, deaf = b\"SLOWPREFILL\" in pbm, b\"DEAFSTOP\" in pbm\n"
53                        "        quiet = b\"SILENTREAD\" in pbm\n"
54                        "        for q in range(CH, len(ids) - 1, CH):\n"
55                        "            time.sleep(STEP / 2 + (0.02 if slow or deaf else 0))\n"
56                        "            if quiet and q > CH:\n"
57                        "                continue                  # SILENTREAD: after its first PP line the read says nothing\n", 1)
58    old = "            if stop.is_set():\n                break\n            if active and (q // CH) % 4 == 0:"
59    assert old in text
60    text = text.replace(old, "            if stop.is_set() and not deaf:\n                break\n"
61                        "            if active and (q // CH) % 4 == 0:", 1)
62    old = "        if given:\n            if log:\n                log.write(f\"YIELD"
63    assert old in text
64    text = text.replace(old, "        if deaf:\n            stop.clear()\n" + old, 1)
65    text = text.replace("while True:\n    try:\n        line = lines.get(timeout=STEP if active else None)",
66                        CANARY_PATCH + "while True:\n    try:\n        line = lines.get(timeout=STEP if active else None)", 1)
67    assert CANARY_PATCH in text
68    # VRAM and SAVE / RESTORE answer on the control lines, in the engine's own words
69    old = '    if line:\n        print("ERR unknown " + line[:20], flush=True)\n        continue\n'
70    assert old in text
71    text = text.replace(old, '    if line.startswith("VRAM"):\n        print("VRAM vram_free_mib=100 expert_slots=1", flush=True)\n        continue\n'
72                        '    if line.startswith(("SAVE ", "RESTORE ")):\n'
73                        '        print("SAVED 1 1 1.0" if line.startswith("SAVE") else "RESTORED 1 1 1.0", flush=True)\n'
74                        '        continue\n' + old, 1)
75    return text
76
77
78def prompt_ids(canary: str, filler: int = 0) -> list[int]:
79    return list(f"say {canary} ".encode()) + [ord("x")] * filler + list(f" {canary} please".encode())
80
81
82def expected_reply(canary: str) -> list[int]:
83    return list((canary.encode() + b" ") * CANARY_REPEAT) + [257]
84
85
86def text_of(tokens) -> bytes:
87    return bytes(t for t in tokens if 0 <= t < 256)
88
89
90def foreign(tokens, own: str) -> list[bytes]:
91    """The canaries in a token stream that are not `own`."""
92    return [c for c in CANARY_RE.findall(text_of(tokens)) if c != own.encode()]
93
94
95class FakeEngines:
96    """Real StrataEngine objects (the reader/pump, the generate paths) over the canary fake process."""
97
98    def make_engines(self, n, batch=0, step=0.004):
99        import serve.server as server
100        self.tmp = tempfile.TemporaryDirectory()
101        script = Path(self.tmp.name) / "fake_strata.py"
102        script.write_text(canary_script(step), encoding="utf-8")
103        real = server.subprocess.Popen
104        # kept for the whole test: restart() starts the fake again
105        self.popen_patch = mock.patch.object(server.subprocess, "Popen",
106                                             lambda cmd, **kw: real([sys.executable, str(script), *cmd[1:]], **kw))
107        self.popen_patch.start()
108        engines = []
109        for i in range(n):
110            extra = (["--batch", str(batch)] if batch else [])
111            engines.append(StrataEngine("strata", extra))
112        for e in engines:
113            e.silence_s = 20
114        return engines
115
116    def cleanup_engines(self):
117        for e in getattr(self, "engines", []):
118            try:
119                e.unload()
120            except Exception:                                    # noqa: BLE001
121                pass
122        if getattr(self, "popen_patch", None):
123            self.popen_patch.stop()
124        if getattr(self, "tmp", None):
125            self.tmp.cleanup()
126
127
128class HookLock:
129    """A run lock that calls a hook right after it is released: the successor is then free to take the replica at the
130    exact moment the real race needs (before the previous request's child generator has been finalized)."""
131
132    def __init__(self):
133        self._lock = threading.Lock()
134        self.after_release = None
135
136    def acquire(self, *a, **k):
137        return self._lock.acquire(*a, **k)
138
139    def release(self):
140        self._lock.release()
141        hook, self.after_release = self.after_release, None
142        if hook is not None:
143            hook()
144
145    def locked(self):
146        return self._lock.locked()
147
148
149def collect(gen, into: list) -> None:
150    for t in gen:
151        if t is not None:
152            into.append(t)
153
154
155class ReplicaOwnership(FakeEngines, unittest.TestCase):
156    """#2892: an unbatched replica takes one request at a time under its run lock.  The lock must cover the previous
157    request's whole native exchange (STOP, DONE), and the DONE statistics must belong to the request that read them."""
158
159    def setUp(self):
160        self.engines = self.make_engines(2)
161        self.rep = ReplicaEngine(self.engines)
162        self.rep.heal = lambda: None
163        self.engines[1].ended = True          # only replica 0 is alive: every request goes to it
164        self.lock = HookLock()
165        self.rep.run_locks[0] = self.lock
166
167    def tearDown(self):
168        self.cleanup_engines()
169
170    def wait_reading(self, engine, timeout=5.0):
171        """True once some thread waits on the engine's line queue (the successor sent its GEN and reads)."""
172        end = time.monotonic() + timeout
173        while time.monotonic() < end:
174            if engine.lines.not_empty._waiters:
175                return True
176            time.sleep(0.001)
177        return False
178
179    def run_handoff(self, a_can, b_can, hold_s):
180        """A reads two tokens and its consumer closes it; B takes the replica the moment the lock is free and reads
181        for `hold_s` seconds before A's child is finalized (so A's tokens are already in the line queue)."""
182        a_got, b_got = [], []
183        threads = []
184
185        def successor():
186            def run():
187                collect(self.rep.generate(prompt_ids(b_can), 500, {}, threading.Event()), b_got)
188            t = threading.Thread(target=run, daemon=True)
189            threads.append(t)
190            t.start()
191            self.wait_reading(self.engines[0])
192            time.sleep(hold_s)
193        self.lock.after_release = successor
194        gen_a = self.rep.generate(prompt_ids(a_can), 500, {}, threading.Event())
195        for t in gen_a:
196            if t is not None:
197                a_got.append(t)
198            if len(a_got) >= 2:
199                break
200        gen_a.close()                           # what Service does on a stop token, a stop string or a disconnect
201        del gen_a
202        threads[0].join(30)
203        self.assertFalse(threads[0].is_alive())
204        return a_got, b_got
205
206    def test_a_successor_never_reads_the_predecessors_done(self):
207        """#2892: B is the next request on the replica and A's DONE is still unread."""
208        a_can, b_can = "QA0001", "QB0002"
209        a_got, b_got = self.run_handoff(a_can, b_can, 0)
210        self.assertEqual(foreign(a_got, a_can), [])
211        self.assertEqual(foreign(b_got, b_can), [], "B received A's tokens")
212        self.assertEqual(b_got, expected_reply(b_can), "B's own reply is complete and exactly its own")
213
214    def test_a_successor_never_reads_the_predecessors_tokens(self):
215        """#2892: A's remaining tokens are already queued when B reads."""
216        a_can, b_can = "QA0011", "QB0012"
217        a_got, b_got = self.run_handoff(a_can, b_can, 0.08)
218        self.assertEqual(foreign(b_got, b_can), [], "B received A's tokens")
219        self.assertEqual(b_got, expected_reply(b_can), "B's own reply is complete and exactly its own")
220
221    def test_many_forced_handoffs_never_cross(self):
222        """The forced schedule above, 30 times with different hold times and different cut-off points."""
223        import random
224        rnd = random.Random(2892)
225        bad = []
226        for i in range(30):
227            a_can, b_can = f"QA{i:04d}", f"QB{i:04d}"
228            self.lock.after_release = None
229            cut = rnd.choice((1, 2, 3, 10, 40))
230            hold = rnd.choice((0, 0.002, 0.01, 0.05))
231            a_got, b_got = [], []
232            threads = []
233
234            def successor(b_can=b_can, b_got=b_got, hold=hold, threads=threads):
235                t = threading.Thread(target=lambda: collect(
236                    self.rep.generate(prompt_ids(b_can), 500, {}, threading.Event()), b_got), daemon=True)
237                threads.append(t)
238                t.start()
239                self.wait_reading(self.engines[0])
240                time.sleep(hold)
241            self.lock.after_release = successor
242            gen_a = self.rep.generate(prompt_ids(a_can), 500, {}, threading.Event())
243            for t in gen_a:
244                if t is not None:
245                    a_got.append(t)
246                if len(a_got) >= cut:
247                    break
248            gen_a.close()
249            del gen_a
250            threads[0].join(30)
251            if foreign(b_got, b_can) or b_got != expected_reply(b_can):
252                bad.append((i, cut, hold, len(b_got), foreign(b_got, b_can)[:2]))
253        self.assertEqual(bad, [], f"{len(bad)} of 30 handoffs crossed")
254
255    def test_unforced_back_to_back_requests_never_cross(self):
256        """No hook: B waits for the replica's lock while A is cut off at a random token; 60 repetitions."""
257        import random
258        rnd = random.Random(4451)
259        self.rep.run_locks[0] = threading.Lock()
260        bad = []
261        for i in range(60):
262            a_can, b_can = f"QA{i:04d}", f"QB{i:04d}"
263            cut = rnd.choice((1, 2, 3, 5, 20, 100))
264            a_got, b_got = [], []
265            go = threading.Event()
266            tb = threading.Thread(target=lambda: (go.wait(), collect(
267                self.rep.generate(prompt_ids(b_can), 500, {}, threading.Event()), b_got)), daemon=True)
268            tb.start()
269            gen_a = self.rep.generate(prompt_ids(a_can), 500, {}, threading.Event())
270            for t in gen_a:
271                if t is not None:
272                    a_got.append(t)
273                if len(a_got) >= cut:
274                    break
275            go.set()
276            gen_a.close()
277            del gen_a
278            tb.join(30)
279            if foreign(b_got, b_can) or b_got != expected_reply(b_can):
280                bad.append((i, cut, len(b_got), foreign(b_got, b_can)[:2]))
281        self.assertEqual(bad, [], f"{len(bad)} of 60 crossed")
282
283    def test_the_figures_of_a_request_are_its_own(self):
284        """A runs to its max_tokens; before A's caller reads its DONE figures, B runs to completion on the replica."""
285        a_can, b_can = "QA0003", "QB0004"
286        done = []
287
288        def successor():
289            def run():
290                collect(self.rep.generate(prompt_ids(b_can, 40), 25, {}, threading.Event()), [])
291            t = threading.Thread(target=run, daemon=True)
292            t.start()
293            t.join(30)
294            done.append(t)
295        self.lock.after_release = successor
296        got = []
297        collect(self.rep.generate(prompt_ids(a_can), 10, {}, threading.Event()), got)
298        self.assertTrue(done, "the successor ran")
299        last = self.rep.last
300        self.assertEqual(last.get("generated"), 10, last)
301        self.assertEqual(last.get("prompt_tokens"), len(prompt_ids(a_can)), last)
302
303    def test_an_undrainable_replica_is_not_handed_to_the_next_request(self):
304        """The child cannot be drained (the engine never answers STOP): the replica is ended, not reused."""
305        from serve.server import EngineSilent
306        a_can = "QA0005"
307        engine = self.engines[0]
308        engine.silence_s = 1.0
309        gen_a = self.rep.generate(prompt_ids(a_can), 500, {}, threading.Event())
310        got = []
311        for t in gen_a:
312            if t is not None:
313                got.append(t)
314            if len(got) >= 2:
315                break
316        engine.can_stop = True
317        # the engine stops answering: its process is frozen
318        import os
319        import signal
320        if hasattr(signal, "SIGSTOP"):
321            os.kill(engine.proc.pid, signal.SIGSTOP)
322        else:
323            self.skipTest("needs SIGSTOP to freeze the fake engine")
324        try:
325            try:
326                gen_a.close()
327            except EngineSilent:
328                pass
329        finally:
330            if engine.proc.poll() is None:
331                os.kill(engine.proc.pid, signal.SIGCONT)
332        self.assertFalse(engine.alive(), "the replica that could not be drained is out of the routing")
333        self.assertFalse(self.lock.locked(), "and its run lock is free")
334        self.assertEqual(self.rep.route(prompt_ids("QA0006")), -1)
335
336
337class Client(threading.Thread):
338    """One streaming client of a --batch engine: its own canary, its own cancel Event.  `pause_after`/`resume`: the
339    consumer stops reading after that many tokens until `resume` is set (a slow reader)."""
340
341    def __init__(self, engine, canary, filler=0, max_new=500, pause_after=None, resume=None, extra="", leave_after_beats=None):
342        super().__init__(daemon=True)
343        self.leave_after_beats = leave_after_beats          # close the stream (as Service does) at this PP heartbeat
344        self.engine, self.canary = engine, canary
345        self.ids = prompt_ids(canary + extra, filler)
346        self.max_new, self.pause_after, self.resume = max_new, pause_after, resume
347        self.cancel = threading.Event()
348        self.tokens, self.error, self.paused = [], None, threading.Event()
349
350    def run(self):
351        beats = 0
352        gen = self.engine.generate(self.ids, self.max_new, {}, self.cancel)
353        try:
354            for t in gen:
355                if t is None:
356                    beats += 1
357                    if self.leave_after_beats is not None and beats >= self.leave_after_beats:
358                        gen.close()                              # the consumer leaves: GeneratorExit inside the engine's request
359                        return
360                    continue
361                self.tokens.append(t)
362                if self.pause_after is not None and len(self.tokens) == self.pause_after:
363                    self.paused.set()
364                    self.resume.wait(30)
365        except BaseException as e:                               # noqa: BLE001
366            self.error = e
367
368    def foreign(self):
369        return foreign(self.tokens, self.canary)
370
371    def complete(self):
372        return self.tokens == expected_reply(self.canary)
373
374
375def wait_until(cond, timeout=10.0):
376    end = time.monotonic() + timeout
377    while time.monotonic() < end:
378        if cond():
379            return True
380        time.sleep(0.005)
381    return False
382
383
384class BatchOwnership(FakeEngines, unittest.TestCase):
385    """#4451: a --batch engine.  Every frame a request reads must be its own, whatever happened to the requests before
386    it on the same slot, the same control lines or the same engine process."""
387
388    def setUp(self):
389        self.engines = self.make_engines(1, batch=4)
390        self.engine = self.engines[0]
391        # 0.3 s instead of 300 s for the wait that ends an interrupted exchange (a wrapper that works on every version)
392        orig = self.engine._drain_control
393        self.engine._drain_control = lambda until, timeout=None, born=None, lines_q=None: orig(
394            until, timeout=0.3 if timeout is None else timeout, born=born,
395            **({} if lines_q is None else {"lines_q": lines_q}))
396        self.engine.QUARANTINE_S = 8.0
397
398    def tearDown(self):
399        self.cleanup_engines()
400
401    def start_busy(self, n=1, tag="Y"):
402        """Long requests that hold batch slots, so that the next requests are admitted into slots too."""
403        bg = [Client(self.engine, f"{chr(ord(tag) + i)}B{9990 - i:04d}", max_new=500) for i in range(n)]
404        for c in bg:
405            c.start()
406            time.sleep(0.05)
407        wait_until(lambda: all(len(c.tokens) >= 3 for c in bg))
408        return bg
409
410    def finish(self, clients, timeout=60):
411        for c in clients:
412            c.join(timeout)
413            self.assertFalse(c.is_alive())
414
415    def test_interleaved_clients_get_their_own_replies(self):
416        cs = [Client(self.engine, f"{chr(ord('A') + i)}{chr(ord('K') + i)}{i:04d}") for i in range(4)]
417        for c in cs:
418            c.start()
419            time.sleep(0.02)
420        self.finish(cs)
421        for c in cs:
422            self.assertIsNone(c.error)
423            self.assertEqual(c.foreign(), [])
424            self.assertTrue(c.complete(), c.canary)
425
426    def test_a_cancel_in_the_middle_of_the_prompt_read_then_reuse(self):
427        """The first of several interleaved clients is cancelled while its prompt is being read; the next requests
428        reuse the slot and the control lines and must read only their own frames."""
429        import random
430        rnd = random.Random(4451)
431        bg = self.start_busy(n=2)
432        bad = []
433        for i in range(12):
434            a = Client(self.engine, f"KA{i:04d}", filler=700, extra=" SLOWPREFILL")
435            a.start()
436            time.sleep(rnd.choice((0.03, 0.08, 0.15, 0.3)))
437            a.cancel.set()
438            followers = [Client(self.engine, f"{chr(ord('M') + j)}{chr(ord('Q') + j)}{i:02d}{j:02d}", max_new=60)
439                         for j in range(2)]
440            for f in followers:
441                f.start()
442            self.finish([a] + followers)
443            for f in followers:
444                if f.error or f.foreign() or f.tokens != expected_reply(f.canary)[:60]:
445                    bad.append((i, f.canary, repr(f.error), f.foreign()[:2], len(f.tokens)))
446            self.assertEqual(a.foreign(), [])
447        for c in bg:
448            c.cancel.set()
449        self.finish(bg)
450        for c in bg:
451            self.assertEqual(c.foreign(), [], "a background request received a foreign frame")
452        self.assertEqual(bad, [])
453
454    def test_a_drain_that_times_out_does_not_leak_into_the_next_request(self):
455        """A leaves (its stream is closed, as Service does) in the middle of its prompt read; the engine says nothing for
456        longer than the drain limit (SILENTREAD, DEAFSTOP: ~1 s of silence, then its DONE and BADM).  The control lines stay
457        with A's exchange until they come; the request after it gets its own frames only."""
458        bg = self.start_busy(n=1)
459        a = Client(self.engine, "KA0001", filler=1300, extra=" DEAFSTOP SILENTREAD", leave_after_beats=1)
460        a.start()
461        time.sleep(0.6)                          # past the 0.3 s drain: A's request has left, its engine exchange has not ended
462        # (B's prompt is not under half of A's: a much shorter waiting request would make A give way, BYIELD, at once)
463        b = Client(self.engine, "LB0002", filler=900, max_new=80)
464        b.start()
465        self.finish([a, b])
466        for c in bg:
467            c.cancel.set()
468        self.finish(bg)
469        self.assertIsNone(b.error)
470        self.assertEqual(b.foreign(), [], "B received A's frames")
471        self.assertEqual(b.tokens, expected_reply("LB0002")[:80], "B's reply is its own, in full")
472        self.assertEqual(bg[0].foreign(), [])
473        self.assertTrue(self.engine.alive())
474
475    def test_an_engine_that_keeps_talking_after_a_stop_is_not_given_up_on(self):
476        """The limits count silence, never a read or a decode that still produces lines: the engine takes ~1.8 s to end A's
477        exchange (DEAFSTOP, a PP line every chunk) with the drain at 0.3 s and the quarantine at 0.4 s.  A limit counted
478        from the start would have ended the engine at ~0.7 s, with the other requests in it."""
479        self.engine.QUARANTINE_S = 0.4
480        gen_before = self.engine.gen
481        bg = self.start_busy(n=1)
482        a = Client(self.engine, "KA0001", filler=2600, extra=" DEAFSTOP", leave_after_beats=1)
483        a.start()
484        time.sleep(0.1)
485        b = Client(self.engine, "LB0002", filler=1500, max_new=80)       # (not under half of A's prompt: no BYIELD)
486        b.start()
487        self.finish([a, b], timeout=60)
488        self.assertEqual(self.engine.gen, gen_before, "the engine was ended although it kept talking")
489        self.assertTrue(self.engine.alive())
490        self.assertIsNone(b.error)
491        self.assertEqual(b.tokens, expected_reply("LB0002")[:80])
492        self.assertEqual(bg[0].foreign(), [])
493        self.assertIsNone(bg[0].error, "a request running in another slot was ended with the engine")
494        bg[0].cancel.set()
495        self.finish(bg)
496
497    def test_an_engine_that_goes_silent_after_a_stop_is_ended(self):
498        """The other side of the limit: no line at all for DRAIN_TIMEOUT_S + QUARANTINE_S after the stop (here 0.3 + 0.4 s,
499        the read is silent for ~1.8 s) is a wedged engine: it is ended and the next request starts it again."""
500        self.engine.QUARANTINE_S = 0.4
501        a = Client(self.engine, "KA0001", filler=2600, extra=" DEAFSTOP SILENTREAD", leave_after_beats=1)
502        a.start()
503        self.assertTrue(wait_until(lambda: not self.engine.alive(), 8.0), "a silent engine was not ended")
504        self.finish([a])
505
506    def test_the_engine_ending_during_a_drain_then_a_restart(self):
507        """A is interrupted mid-prompt; the engine dies while A drains; after the restart the new requests (same slot
508        numbers) must never be read by a request of the old process."""
509        old = self.start_busy(n=2)
510        slow = [Client(self.engine, f"{chr(ord('S') + i)}{chr(ord('T') + i)}{i:04d}", pause_after=3,
511                       resume=threading.Event()) for i in range(2)]
512        for c in slow:
513            c.start()
514            time.sleep(0.05)
515        self.assertTrue(wait_until(lambda: all(c.paused.is_set() for c in slow)))
516        a = Client(self.engine, "KA0001", filler=700, extra=" SLOWPREFILL")
517        a.start()
518        time.sleep(0.1)
519        a.cancel.set()
520        self.engine.proc.kill()                  # the engine ends while A's exchange is being drained
521        self.engine.proc.wait()
522        self.finish([a] + old)
523        self.engine.restart()
524        self.assertTrue(self.engine.alive())
525        new = self.start_busy(n=2, tag="D")      # the new process: the same slot numbers again
526        for c in slow:
527            c.resume.set()
528        # they read on: the old process's queued frames, then its end - never the new process's frames
529        time.sleep(1.0)
530        for c in slow:
531            self.assertEqual(c.foreign(), [], f"{c.canary} (old process) read a frame of the new one")
532        for c in new:
533            c.cancel.set()
534        self.finish(new)
535        self.finish(slow)
536        for c in slow:
537            self.assertIsInstance(c.error, Exception, "a request of the dead engine ends with an error")
538        for c in new:
539            self.assertEqual(c.foreign(), [], "a request of the new process received a foreign frame")
540            self.assertTrue(len(c.tokens) >= 3)
541
542    def test_long_generations_are_never_cut_by_the_drain_limits(self):
543        """The drain and quarantine limits (here 0.3 s and 0.4 s, far below a reply's ~1.7 s) apply after a STOP or BSTOP
544        only: replies that are still streaming complete."""
545        self.engine.QUARANTINE_S = 0.4
546        cs = [Client(self.engine, f"{chr(ord('A') + i)}{chr(ord('K') + i)}{i:04d}") for i in range(4)]
547        for c in cs:
548            c.start()
549            time.sleep(0.05)
550        self.finish(cs)
551        for c in cs:
552            self.assertIsNone(c.error)
553            self.assertTrue(c.complete(), c.canary)
554
555    def test_vram_and_session_file_take_the_control_lines_like_a_request(self):
556        """VRAM and SAVE read the control lines for their answer.  Run beside a request that holds them (its solo read
557        or an admission), they took that request's T / PP / DONE lines and it lost its reply."""
558        for what in ("vram", "save", "restore"):
559            a = Client(self.engine, "KA0001")
560            a.start()
561            self.assertTrue(wait_until(lambda: len(a.tokens) >= 3))
562            answers = []
563
564            def call(what=what):
565                try:
566                    if what == "vram":
567                        answers.append(self.engine.vram(None))
568                    else:
569                        answers.append(self.engine.session_file(what, "/tmp/x"))
570                except BaseException as e:               # noqa: BLE001
571                    answers.append(e)
572            t = threading.Thread(target=call, daemon=True)
573            t.start()
574            self.finish([a])
575            t.join(30)
576            self.assertFalse(t.is_alive(), what)
577            self.assertIsNone(a.error, what)
578            self.assertTrue(a.complete(), f"{what}: the request lost lines to the VRAM / session call "
579                                          f"({len(a.tokens)} of {len(expected_reply('KA0001'))} tokens)")
580            self.assertIsInstance(answers[0], dict, answers)
581            self.assertEqual(answers[0].get("vram_free_mib") if what == "vram" else answers[0].get("tokens"),
582                             100 if what == "vram" else 1)
583
584    def test_a_slot_is_not_handed_on_before_the_engine_confirms(self):
585        """A consumer leaves a slot's stream; its BDONE has not come.  Whatever frames still arrive for that slot are
586        not the next request's."""
587        bg = self.start_busy(n=1)
588        a = Client(self.engine, "KA0001", max_new=500)
589        a.start()
590        self.assertTrue(wait_until(lambda: len(a.tokens) >= 5))
591        a.cancel.set()                           # BSTOP: A's slot ends at its next window
592        followers = [Client(self.engine, f"{chr(ord('M') + j)}{chr(ord('Q') + j)}{j:04d}", max_new=60) for j in range(3)]
593        for f in followers:
594            f.start()
595        self.finish([a] + followers)
596        for f in followers:
597            self.assertEqual(f.foreign(), [])
598            self.assertEqual(f.tokens, expected_reply(f.canary)[:60])
599        bg[0].cancel.set()
600        self.finish(bg)
601
602
603if __name__ == "__main__":
604    unittest.main()