okami.mom/strata

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

Niko1221serve/test_admit_order: the engine stand-in sets the arrivals deque the coalescing code reads203df526f

main
5.0 KiB121 linesraw
1"""serve/test_admit_order.py - STRATA_ADMIT_SHORT_FIRST: new requests take the control lines short prompts first
2(StrataEngine._take_control / _admit_next; no process, no GPU).
3
4    python -m unittest serve.test_admit_order -v
5"""
6from __future__ import annotations
7
8import sys
9import collections
10import threading
11import time
12import unittest
13from pathlib import Path
14from unittest import mock
15
16sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
17import serve.server as server  # noqa: E402
18from serve.server import StrataEngine  # noqa: E402
19
20
21def engine_without_process(n=2):
22    """A StrataEngine with the admission state of a started one and no process: alive() is `e.up`."""
23    e = StrataEngine("missing-executable", [], lazy=True)
24    e.batch = n
25    e.slot_busy = [False] * n
26    e.slot_claims, e.slot_releasing, e._orphan_seen = set(), set(), {}
27    e.slot_cv = threading.Condition()
28    e.waiting, e.admitting, e.wait_lens, e.ctl_epoch = 0, 0, [], 0
29    e.arrivals = collections.deque(maxlen=64)
30    e.ctl = threading.Lock()
31    e.gen = 1
32    e.up = True
33    e.alive = lambda: e.up
34    return e
35
36
37class AdmitOrderTest(unittest.TestCase):
38    def setUp(self):
39        self.e = engine_without_process(16)
40        self.order, self.cancels = [], []
41        self.order_lock = threading.Lock()
42
43    def tearDown(self):
44        for c in self.cancels:
45            c.set()
46
47    def take(self, name, plen, **kw):
48        """A request waiting for the control lines; once it has them it notes its name and gives them back."""
49        c = threading.Event()
50        self.cancels.append(c)
51
52        def go():
53            gen = self.e._take_control(c, plen, **kw)
54            try:
55                while True:
56                    next(gen)
57            except StopIteration as s:
58                if s.value:
59                    with self.order_lock:
60                        self.order.append(name)
61                    time.sleep(0.05)                # its read
62                    self.e.ctl.release()
63        threading.Thread(target=go, daemon=True).start()
64
65    def until(self, cond, s=5.0):
66        end = time.time() + s
67        while time.time() < end and not cond():
68            time.sleep(0.01)
69        self.assertTrue(cond())
70
71    def queue(self, *reqs):
72        """While a long read holds the control lines, the requests arrive in this order; then the read ends."""
73        self.assertTrue(self.e.ctl.acquire(timeout=1))
74        for name, plen in reqs:
75            self.take(name, plen, new=True)
76            self.until(lambda n=len(self.order) + sum(1 for _ in self.e.wait_lens): self.e.waiting >= 1)
77            time.sleep(0.02)                        # (distinct arrival times)
78        self.until(lambda: self.e.waiting == len(reqs))
79        self.e.ctl.release()
80        self.until(lambda: len(self.order) == len(reqs), s=15.0)
81        return self.order
82
83    def test_short_first_puts_the_chat_before_the_agent_reads(self):
84        with mock.patch.object(server, "ADMIT_SHORT_FIRST", 8192), mock.patch.object(server, "ADMIT_MAX_WAIT_S", 60.0):
85            order = self.queue(("agent1", 120000), ("agent2", 190000), ("chat", 500), ("agent3", 150000))
86        self.assertEqual(order[0], "chat")
87        self.assertEqual(order[1:], ["agent1", "agent2", "agent3"])      # arrival order among the long ones
88
89    def test_a_long_request_that_waited_too_long_goes_first(self):
90        with mock.patch.object(server, "ADMIT_SHORT_FIRST", 8192), mock.patch.object(server, "ADMIT_MAX_WAIT_S", 0.2):
91            self.assertTrue(self.e.ctl.acquire(timeout=1))
92            self.take("agent", 120000, new=True)
93            self.until(lambda: self.e.waiting == 1)
94            time.sleep(0.4)                         # past STRATA_ADMIT_MAX_WAIT_S
95            self.take("chat", 500, new=True)
96            self.until(lambda: self.e.waiting == 2)
97            self.e.ctl.release()
98            self.until(lambda: len(self.order) == 2, s=15.0)
99        self.assertEqual(self.order, ["agent", "chat"])
100
101    def test_off_by_default(self):
102        self.assertEqual(server.ADMIT_SHORT_FIRST if "STRATA_ADMIT_SHORT_FIRST" not in __import__("os").environ
103                         else 0, 0)
104        with mock.patch.object(server, "ADMIT_SHORT_FIRST", 0):
105            order = self.queue(("agent1", 120000), ("chat", 500))
106        self.assertEqual(sorted(order), ["agent1", "chat"])            # both get their turn, in any order
107
108    def test_a_continuation_is_not_held_back(self):
109        """A request already admitted once (new=False: promoted from the solo path) is not part of the order."""
110        with mock.patch.object(server, "ADMIT_SHORT_FIRST", 8192), mock.patch.object(server, "ADMIT_MAX_WAIT_S", 60.0):
111            self.assertTrue(self.e.ctl.acquire(timeout=1))
112            self.take("chat", 500, new=True)
113            self.take("continuation", 190000)
114            self.until(lambda: self.e.waiting == 2)
115            self.e.ctl.release()
116            self.until(lambda: len(self.order) == 2, s=15.0)
117        self.assertEqual(sorted(self.order), ["chat", "continuation"])
118
119
120if __name__ == "__main__":
121    unittest.main()