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