okami.mom/strata

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

Niko1221Merge main 6c642df75 into f-own-int (round 16: network waits, robustness, Windows kill-on-close job start, GitHub and transfer fixes)cd9745050

main
15.8 KiB381 linesraw
1"""strata_control/netpolicy.py against local servers: one that accepts and never answers (a black hole), a port that refuses, a server
2that answers and then trickles bytes, a server that answers normally. Timings are scaled down (limits under a second); the rule's own
3numbers are checked as constants. The slow real-time trickle test (bytes every 20-50 s for more than 5 minutes) runs with
4STRATA_SLOW_NET_TESTS=1."""
5import http.server
6import os
7import re
8import socket
9import socketserver
10import threading
11import time
12import unittest
13import urllib.error
14import urllib.request
15from unittest import mock
16
17from strata_control import netpolicy as N
18
19
20class BlackHole:
21    """Accepts connections and never sends a byte (and never reads one)."""
22
23    def __init__(self):
24        self.sock = socket.socket()
25        self.sock.bind(("127.0.0.1", 0))
26        self.sock.listen(16)
27        self.port = self.sock.getsockname()[1]
28        self.held, self.stop = [], False
29        self.thread = threading.Thread(target=self._accept, daemon=True)
30        self.thread.start()
31
32    def _accept(self):
33        while not self.stop:
34            try:
35                c, _ = self.sock.accept()
36            except OSError:
37                return
38            self.held.append(c)
39
40    def close(self):
41        self.stop = True
42        for c in self.held:
43            c.close()
44        self.sock.close()
45
46
47#: "fails at once" for a refused connection. Windows itself reports a refused loopback port only after 2.03-2.04 s (measured on the owner PC: it tries the
48#: connection again first), longer than the scaled test windows, so there the refused-port tests use windows of 3 / 6 s, a waiting-line delay of 3 s and
49#: a limit of 4 s; on Linux and macOS the refusal is immediate (0.4 / 0.8 s windows, 0.5 s). Either way far under the rule's 12 s / 44 s windows.
50AT_ONCE_S = 4.0 if os.name == "nt" else 0.5
51REFUSED_WINDOW = (3.0, 6.0) if os.name == "nt" else (0.4, 0.8)
52REFUSED_WAIT_LINE_S = 3.0 if os.name == "nt" else 0.5
53
54
55def refused_port() -> int:
56    s = socket.socket()
57    s.bind(("127.0.0.1", 0))
58    port = s.getsockname()[1]
59    s.close()
60    return port
61
62
63class Server:
64    """A small HTTP server; `behave(handler)` writes each answer."""
65
66    def __init__(self, behave):
67        outer = self
68        self.requests = 0
69
70        class H(http.server.BaseHTTPRequestHandler):
71            protocol_version = "HTTP/1.1"
72
73            def log_message(self, *a):
74                pass
75
76            def do_GET(self):
77                outer.requests += 1
78                behave(self, outer.requests)
79
80            do_HEAD = do_GET
81
82        class TS(socketserver.ThreadingMixIn, http.server.HTTPServer):
83            daemon_threads = True
84            allow_reuse_address = True
85
86        self.httpd = TS(("127.0.0.1", 0), H)
87        self.port = self.httpd.server_address[1]
88        threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
89
90    def url(self, path="/f"):
91        return f"http://127.0.0.1:{self.port}{path}"
92
93    def close(self):
94        self.httpd.shutdown()
95        self.httpd.server_close()
96
97
98def ok_body(body=b"hello"):
99    def behave(h, n):
100        h.send_response(200)
101        h.send_header("Content-Length", str(len(body)))
102        h.end_headers()
103        if h.command != "HEAD":
104            h.wfile.write(body)
105    return behave
106
107
108def trickle(total: int, every: float):
109    def behave(h, n):
110        h.send_response(200)
111        h.send_header("Content-Length", str(total))
112        h.end_headers()
113        for _ in range(total):
114            time.sleep(every)
115            try:
116                h.wfile.write(b"x")
117                h.wfile.flush()
118            except OSError:
119                return
120    return behave
121
122
123def headers_then_silence(h, n):
124    h.send_response(200)
125    h.send_header("Content-Length", "100")
126    h.end_headers()
127    h.wfile.flush()
128    time.sleep(5)
129
130
131def read_then_silence(h, n):
132    time.sleep(5)
133
134
135class Base(unittest.TestCase):
136    def setUp(self):
137        self.memory = N.HostMemory()
138        self.opener = N.build_opener(urllib.request.ProxyHandler({}))
139        self.lines = []
140        p = mock.patch.object(N, "CONNECT_LIMITS", (0.4, 0.8))      # the rule's window, scaled: (0.4, 0.8) is the full window here
141        p.start()
142        self.addCleanup(p.stop)
143
144    def open(self, url, limits=(0.4, 0.8), **kw):
145        kw.setdefault("memory", self.memory)
146        kw.setdefault("gap", 0.1)
147        kw.setdefault("say", self.lines.append)
148        return N.open_url(self.opener.open, urllib.request.Request(url), limits=limits, **kw)
149
150
151class TheRuleNumbers(unittest.TestCase):
152    def test_numbers_as_approved(self):
153        self.assertEqual((N.FIRST_CONNECT_S, N.RETRY_CONNECT_S, N.RETRY_GAP_S), (12.0, 30.0, 2.0))
154        self.assertEqual((N.STALL_S, N.GIVE_UP_S, N.HOST_MEMORY_S), (60.0, 300.0, 600.0))
155        self.assertEqual((N.WAIT_LINE_AFTER_S, N.WAIT_LINE_EVERY_S), (5.0, 10.0))
156        self.assertLessEqual(N.FIRST_CONNECT_S + N.RETRY_GAP_S + N.RETRY_CONNECT_S, 45)
157
158
159class BlackHoleFailsFast(Base):
160    def test_accepts_and_never_answers_fails_after_both_limits(self):
161        hole = BlackHole()
162        self.addCleanup(hole.close)
163        t0 = time.monotonic()
164        with self.assertRaises(N.NetFailure) as cm:
165            self.open(f"http://127.0.0.1:{hole.port}/f")
166        took = time.monotonic() - t0
167        self.assertEqual(cm.exception.kind, "no_answer")
168        self.assertGreaterEqual(took, 1.2)
169        self.assertLess(took, 2.5)                          # 0.4 + 0.1 + 0.8, not two stall periods
170        self.assertEqual(len(hole.held), 2)                  # one retry, no more
171        self.assertIn("127.0.0.1 did not answer within", cm.exception.headline("the picture reader"))
172        self.assertIn("so the picture reader could not be downloaded.", cm.exception.headline("the picture reader"))
173
174    def test_a_tls_handshake_that_never_answers_is_bounded(self):
175        hole = BlackHole()
176        self.addCleanup(hole.close)
177        t0 = time.monotonic()
178        with self.assertRaises(N.NetFailure) as cm:
179            self.open(f"https://127.0.0.1:{hole.port}/f")
180        self.assertEqual(cm.exception.kind, "no_answer")
181        self.assertLess(time.monotonic() - t0, 2.5)
182
183    def test_the_wait_for_the_answer_counts_in_the_connection_phase(self):
184        srv = Server(read_then_silence)                      # reads the request, never answers: not 60 s of stall
185        self.addCleanup(srv.close)
186        t0 = time.monotonic()
187        with self.assertRaises(N.NetFailure):
188            self.open(srv.url())
189        self.assertLess(time.monotonic() - t0, 2.5)
190
191    def test_the_host_is_not_tried_again_in_this_run(self):
192        hole = BlackHole()
193        self.addCleanup(hole.close)
194        with self.assertRaises(N.NetFailure):
195            self.open(f"http://127.0.0.1:{hole.port}/a")
196        t0 = time.monotonic()
197        with self.assertRaises(N.NetFailure) as cm:
198            self.open(f"http://127.0.0.1:{hole.port}/b")
199        self.assertLess(time.monotonic() - t0, 0.2)
200        self.assertEqual(cm.exception.kind, "again")
201        self.assertEqual(len(hole.held), 2)
202        self.assertIn("did not answer a moment ago either", cm.exception.headline("the model files"))
203        # a resume of a download that already moved does not ask the memory
204        with self.assertRaises(N.NetFailure) as cm:
205            self.open(f"http://127.0.0.1:{hole.port}/b", check_memory=False)
206        self.assertEqual(cm.exception.kind, "no_answer")
207
208    def test_a_shorter_call_reads_the_memory_but_never_writes_it(self):
209        hole = BlackHole()
210        self.addCleanup(hole.close)
211        with self.assertRaises(N.NetFailure) as cm:
212            self.open(f"http://127.0.0.1:{hole.port}/models", limits=(0.2, 0.2))      # an optional 5 s read, scaled
213        self.assertEqual(cm.exception.kind, "no_answer")
214        self.assertFalse(self.memory.failed_recently(f"127.0.0.1:{hole.port}"), "a short read does not mark the host")
215        with self.assertRaises(N.NetFailure) as cm:                                  # the required download: its own full window
216            self.open(f"http://127.0.0.1:{hole.port}/engine")
217        self.assertEqual(cm.exception.kind, "no_answer")
218        self.assertEqual(len(hole.held), 4)
219        self.assertTrue(self.memory.failed_recently(f"127.0.0.1:{hole.port}"))
220        t0 = time.monotonic()
221        with self.assertRaises(N.NetFailure) as cm:                                  # and a later short read skips it at once
222            self.open(f"http://127.0.0.1:{hole.port}/models", limits=(0.2, 0.2))
223        self.assertEqual(cm.exception.kind, "again")
224        self.assertLess(time.monotonic() - t0, 0.1)
225
226    def test_the_waiting_line_names_the_host(self):
227        hole = BlackHole()
228        self.addCleanup(hole.close)
229        with self.assertRaises(N.NetFailure):
230            self.open(f"http://127.0.0.1:{hole.port}/f", limits=(0.8, 0.8), wait_after=0.2, wait_every=0.4)
231        self.assertGreaterEqual(len(self.lines), 2)
232        self.assertEqual(self.lines[0], "Waiting for 127.0.0.1 to answer (0 s so far)")
233        for line in self.lines:
234            self.assertRegex(line, N.WAITING_RE)
235
236    def test_the_memory_is_in_memory_only_and_expires(self):
237        now = [0.0]
238        m = N.HostMemory(clock=lambda: now[0])
239        m.remember("github.com")
240        self.assertTrue(m.failed_recently("github.com"))
241        now[0] = N.HOST_MEMORY_S - 1
242        self.assertTrue(m.failed_recently("github.com"))
243        now[0] = N.HOST_MEMORY_S
244        self.assertFalse(m.failed_recently("github.com"))
245        self.assertFalse(N.HostMemory().failed_recently("github.com"))   # a new run (a new process) starts empty
246
247
248class ClearFailuresAreImmediate(Base):
249    def test_a_refused_port_fails_at_once_without_retry_or_line(self):
250        port = refused_port()
251        t0 = time.monotonic()
252        with self.assertRaises(N.NetFailure) as cm:
253            self.open(f"http://127.0.0.1:{port}/f", limits=REFUSED_WINDOW, wait_after=REFUSED_WAIT_LINE_S)
254        self.assertLess(time.monotonic() - t0, AT_ONCE_S)
255        self.assertEqual(cm.exception.kind, "offline")
256        self.assertFalse(self.memory.failed_recently("127.0.0.1"))
257        self.assertIn("This computer could not connect to 127.0.0.1 (it looks offline)", cm.exception.headline("the model files"))
258
259    def test_no_dns_answer_fails_at_once(self):
260        with mock.patch.object(N.socket, "getaddrinfo", side_effect=socket.gaierror(-3, "Temporary failure in name resolution")):
261            t0 = time.monotonic()
262            with self.assertRaises(N.NetFailure) as cm:
263                self.open("http://huggingface.co/f")
264        self.assertLess(time.monotonic() - t0, 0.5)
265        self.assertEqual((cm.exception.kind, cm.exception.host), ("offline", "huggingface.co"))
266
267    def test_a_name_lookup_that_hangs_is_bounded(self):
268        def slow(*a, **k):
269            time.sleep(3)
270            raise socket.gaierror(-3, "late")
271        with mock.patch.object(N.socket, "getaddrinfo", side_effect=slow):
272            t0 = time.monotonic()
273            with self.assertRaises(N.NetFailure) as cm:
274                self.open("http://huggingface.co/f", limits=(0.3, 0.3))
275        self.assertLess(time.monotonic() - t0, 1.5)
276        self.assertEqual(cm.exception.kind, "no_answer")
277
278    def test_404_is_not_tried_again_503_is_tried_once(self):
279        def behave(h, n):
280            h.send_response(404 if h.path == "/gone" else (503 if n == 1 else 200))
281            h.send_header("Content-Length", "0")
282            h.end_headers()
283        srv = Server(behave)
284        self.addCleanup(srv.close)
285        with self.open(srv.url("/busy")) as r:              # request 1: 503, request 2: 200
286            self.assertEqual(r.status, 200)
287        self.assertEqual(srv.requests, 2)
288        with self.assertRaises(urllib.error.HTTPError):
289            self.open(srv.url("/gone"))
290        self.assertEqual(srv.requests, 3)
291
292
293class WorkingServers(Base):
294    def test_a_normal_answer_is_one_request_and_no_line(self):
295        srv = Server(ok_body(b"hello"))
296        self.addCleanup(srv.close)
297        with self.open(srv.url(), wait_after=0.5) as r:
298            self.assertEqual(r.read(), b"hello")
299        self.assertEqual(srv.requests, 1)
300        self.assertEqual(self.lines, [])
301
302    def test_a_silent_body_stalls_out_after_the_stall_time(self):
303        srv = Server(headers_then_silence)
304        self.addCleanup(srv.close)
305        opener = N.build_opener(urllib.request.ProxyHandler({}), stall=0.5)
306        r = opener.open(srv.url(), timeout=2)
307        t0 = time.monotonic()
308        with self.assertRaises(OSError):
309            r.read()
310        self.assertLess(time.monotonic() - t0, 1.5)
311
312    def test_a_trickle_slower_than_the_connect_limit_keeps_going(self):
313        srv = Server(trickle(8, 0.3))                        # a byte every 0.3 s for 2.4 s: longer than every connect limit
314        self.addCleanup(srv.close)
315        opener = N.build_opener(urllib.request.ProxyHandler({}), stall=1.0)
316        with N.open_url(opener.open, srv.url(), limits=(0.2, 0.2), memory=self.memory) as r:
317            self.assertEqual(r.read(), b"x" * 8)
318
319    @unittest.skipUnless(os.environ.get("STRATA_SLOW_NET_TESTS") == "1", "real-time trickle: STRATA_SLOW_NET_TESTS=1")
320    def test_real_time_trickle_for_more_than_five_minutes(self):
321        """A few bytes every 20-50 s for about 6 minutes, with the rule's own STALL_S: the link is slow but alive and is never cut."""
322        gaps = [20, 35, 50, 25, 45, 30, 50, 40, 20, 50]             # 365 s
323        def behave(h, n):
324            h.send_response(200)
325            h.send_header("Content-Length", str(3 * len(gaps)))
326            h.end_headers()
327            for g in gaps:
328                time.sleep(g)
329                h.wfile.write(b"abc")
330                h.wfile.flush()
331        srv = Server(behave)
332        self.addCleanup(srv.close)
333        t0 = time.monotonic()
334        with N.open_url(N.urlopen, srv.url(), memory=self.memory) as r:
335            got = b""
336            while len(got) < 3 * len(gaps):
337                b = r.read(3)
338                if not b:
339                    break
340                got += b
341        self.assertEqual(len(got), 3 * len(gaps))
342        self.assertGreater(time.monotonic() - t0, N.GIVE_UP_S)
343
344
345class Kinds(unittest.TestCase):
346    def test_kinds(self):
347        U = urllib.error.URLError
348        self.assertEqual(N.kind(U(socket.gaierror(-2, "x"))), "offline")
349        self.assertEqual(N.kind(U(ConnectionRefusedError())), "offline")
350        self.assertEqual(N.kind(U(TimeoutError("_ssl.c:993: The handshake operation timed out"))), "no_answer")
351        self.assertEqual(N.kind(U("timed out")), "no_answer")
352        self.assertEqual(N.kind(TimeoutError()), "no_answer")
353        self.assertEqual(N.kind(U(ConnectionResetError())), "retry")
354        self.assertEqual(N.kind(urllib.error.HTTPError("u", 503, "", {}, None)), "http_retry")
355        self.assertEqual(N.kind(urllib.error.HTTPError("u", 404, "", {}, None)), "http")
356
357    def test_stall_clock(self):
358        now = [0.0]
359        c = N.StallClock(clock=lambda: now[0])
360        c.progress(0)
361        now[0] = 299
362        self.assertFalse(c.expired())
363        c.progress(10)                                       # any new byte resets it
364        now[0] = 500
365        self.assertFalse(c.expired())
366        c.progress(10)                                       # the same count is no progress
367        now[0] = 599
368        self.assertTrue(c.expired())
369        self.assertEqual(c.words("the model files", 37, 100),
370                         ("No data arrived for 5 minutes, so the download of the model files stopped at 37%.",
371                          "Run the same command again: it continues where it stopped."))
372
373    def test_what_words(self):
374        self.assertEqual(N.what_words(None), "the model files")
375        self.assertEqual(N.what_words("vision encoder"), "the picture reader")
376        self.assertEqual(N.what_words("llama.cpp source"), "the tools that prepare models")
377        self.assertEqual(N.what_words("Strata engine"), "the Strata engine")
378
379
380if __name__ == "__main__":
381    unittest.main()