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
10.8 KiB199 linesraw
1"""Item 1 of lane NET: the silent wait in launch step 5. setup.download() against a server that accepts and never answers, a refusing
2port and a working one (the rule's limits scaled down); what `strata launch` shows while setup waits (the waiting line, the heartbeat in
3the download phase, the plain printer); setup's [X] reason in the launch error and the setup log."""
4
5from __future__ import annotations
6
7import contextlib
8import io
9import re
10import time
11import unittest
12from unittest import mock
13
14import setup
15from strata_cli.launch import cmd
16from strata_cli.launch.runner import Event, LaunchError, Runner, capital
17from strata_control import netpolicy, progress_words
18from tests.terminal.test_flow2_022 import Base as FlowBase
19from tests.terminal.test_netpolicy import AT_ONCE_S, REFUSED_WAIT_LINE_S, REFUSED_WINDOW, BlackHole, Server, ok_body, refused_port
20
21
22def scaled():
23    """The rule with sub-second limits: 0.4 s, 0.1 s gap, 0.8 s; the waiting line after 0.2 s, then every 0.3 s."""
24    return [mock.patch.object(netpolicy, "CONNECT_LIMITS", (0.4, 0.8)), mock.patch.object(netpolicy, "RETRY_GAP_S", 0.1),
25            mock.patch.object(netpolicy, "WAIT_LINE_AFTER_S", 0.2), mock.patch.object(netpolicy, "WAIT_LINE_EVERY_S", 0.3),
26            mock.patch.dict("os.environ", {"STRATA_SOURCE": "huggingface"})]
27
28
29class SetupDownloadWaits(unittest.TestCase):
30    def setUp(self):
31        import tempfile
32        from pathlib import Path
33        for p in scaled():
34            p.start()
35            self.addCleanup(p.stop)
36        self.memory = netpolicy.HostMemory()
37        p = mock.patch.object(netpolicy, "HOSTS", self.memory)
38        p.start()
39        self.addCleanup(p.stop)
40        t = tempfile.TemporaryDirectory(prefix="strata-netwait-")
41        self.addCleanup(t.cleanup)
42        self.dir = Path(t.name)
43
44    def download(self, url, name="model-00001-of-00002.gguf", what=None):
45        buf = io.StringIO()
46        t0 = time.monotonic()
47        with contextlib.redirect_stdout(buf):
48            try:
49                setup.download(url, self.dir / name, what)
50                code = 0
51            except SystemExit as e:
52                code = e.code
53        return code, buf.getvalue(), time.monotonic() - t0
54
55    def test_a_black_hole_shows_the_host_soon_and_fails_fast_with_the_reason(self):
56        hole = BlackHole()
57        self.addCleanup(hole.close)
58        code, out, took = self.download(f"http://127.0.0.1:{hole.port}/m/model-00001-of-00002.gguf")
59        self.assertEqual(code, 1, out)
60        self.assertLess(took, 2.5, out)                                  # 0.4 + 0.1 + 0.8, not 5 x 60 + 4 x 5 s
61        self.assertRegex(out, r"(?m)^  Waiting for 127\.0\.0\.1 to answer \(0 s so far\) \.\.\.$")
62        self.assertRegex(out, r"\[X\]  127\.0\.0\.1 did not answer within 1 seconds, so the model files could not be downloaded\.")
63        self.assertIn("Check that this computer can open https://127.0.0.1, then run the same command again: what is already downloaded is kept. "
64                      "Models that are already on this computer still start without the internet.", out)
65        self.assertEqual(len(hole.held), 2)
66        # the next file from the same server: at once, with the same sentence
67        code, out, took = self.download(f"http://127.0.0.1:{hole.port}/m/model-00002-of-00002.gguf", "model-00002-of-00002.gguf")
68        self.assertEqual(code, 1)
69        self.assertLess(took, 0.3)
70        self.assertIn("[X]  127.0.0.1 did not answer a moment ago either, so the model files could not be downloaded.", out)
71        self.assertEqual(len(hole.held), 2)
72
73    def test_a_short_model_list_read_does_not_cost_the_download_its_own_attempt(self):
74        """The model-list read at the start of setup (5 s, optional) fails on a black hole; the engine or model download from the same host
75        afterwards still gets its own full window and says W3, not W5 (coordinator 11-10)."""
76        from strata_control import transfer
77        hole = BlackHole()
78        self.addCleanup(hole.close)
79        with self.assertRaises(transfer.TransferError):
80            transfer.read_small(f"http://127.0.0.1:{hole.port}/strata-feed.json", timeout=0.2)
81        self.assertEqual(len(hole.held), 2)
82        code, out, took = self.download(f"http://127.0.0.1:{hole.port}/m/model-00001-of-00002.gguf")
83        self.assertEqual(code, 1)
84        self.assertGreater(took, 1.0)
85        self.assertEqual(len(hole.held), 4)
86        self.assertIn("[X]  127.0.0.1 did not answer within 1 seconds, so the model files could not be downloaded.", out)
87        self.assertNotIn("a moment ago", out)
88
89    def test_the_picture_reader_is_named(self):
90        hole = BlackHole()
91        self.addCleanup(hole.close)
92        code, out, _t = self.download(f"http://127.0.0.1:{hole.port}/m/mmproj.gguf", "mmproj.gguf", "vision encoder")
93        self.assertIn("so the picture reader could not be downloaded.", out)
94
95    def test_a_refusing_port_fails_at_once_with_no_waiting_line(self):
96        port = refused_port()
97        with mock.patch.object(netpolicy, "CONNECT_LIMITS", REFUSED_WINDOW), mock.patch.object(netpolicy, "WAIT_LINE_AFTER_S", REFUSED_WAIT_LINE_S):
98            code, out, took = self.download(f"http://127.0.0.1:{port}/m/model-00001-of-00002.gguf")
99        self.assertEqual(code, 1)
100        self.assertLess(took, AT_ONCE_S)
101        self.assertNotIn("Waiting for", out)
102        self.assertIn("[X]  This computer could not connect to 127.0.0.1 (it looks offline), so the model files could not be downloaded.", out)
103
104    def test_a_working_server_still_downloads_and_prints_no_waiting_line(self):
105        srv = Server(ok_body(b"x" * 1000))
106        self.addCleanup(srv.close)
107        code, out, _t = self.download(srv.url("/m/small.bin"), "small.bin")
108        self.assertEqual(code, 0, out)
109        self.assertEqual((self.dir / "small.bin").read_bytes(), b"x" * 1000)
110        self.assertNotIn("Waiting for", out)
111
112
113class LaunchShowsTheWait(FlowBase):
114    def run_lines(self, steps, heartbeat=0.3):
115        r = self.runner(family="qwen", model="Q2_0", vision="off", context=32768)
116        r.HEARTBEAT_S = heartbeat
117        seen = []
118        r.emit_cb = lambda ev: seen.append((time.monotonic(), ev.text))
119
120        def slow():
121            for delay, line in steps:
122                time.sleep(delay)
123                yield line + "\n"
124        proc = mock.Mock()
125        proc.stdout = slow()
126        proc.wait.return_value = 1
127        t0 = time.monotonic()
128        with mock.patch.object(Runner, "_spawn", return_value=proc), mock.patch.object(Runner, "adopt_prepared_files", return_value=None):
129            with self.assertRaises(LaunchError) as cm:
130                r.ensure_model()
131        return [(t - t0, x) for t, x in seen], cm.exception
132
133    def test_the_waiting_line_is_shown_and_the_reason_is_the_error(self):
134        seen, err = self.run_lines([
135            (0, "=== Step 5: downloading Qwen3.8-Flash-Next Q2_0 ==="),
136            (0.2, "  Waiting for huggingface.co to answer (5 s so far) ..."),
137            (0.2, "  Waiting for huggingface.co to answer (15 s so far) ..."),
138            (0, "  (huggingface.co: TimeoutError: timed out)"),
139            (0, ""),
140            (0, "  [X]  huggingface.co did not answer within 44 seconds, so the model files could not be downloaded."),
141            (0, "       Check that this computer can open https://huggingface.co, then run the same command again: what is already "
142                "downloaded is kept. Models that are already on this computer still start without the internet."),
143        ])
144        texts = [x for _t, x in seen]
145        self.assertIn("Waiting for huggingface.co to answer (5 s so far)", texts)
146        self.assertIn("Waiting for huggingface.co to answer (15 s so far)", texts)
147        # the step's own sentence comes first, before setup has said anything (an order, not a stopwatch: a slow or loaded machine only moves both)
148        self.assertFalse(seen[0][1].startswith("Waiting for"), seen[0])
149        self.assertLess(seen[0][0], next(t for t, x in seen if x.startswith("Waiting for")))
150        self.assertIn("The model could not be installed. huggingface.co did not answer within 44 seconds, so the model files could not "
151                      "be downloaded.", err.text)
152        self.assertIn("Check that this computer can open https://huggingface.co", err.next)
153
154    def test_a_silent_download_phase_gets_the_heartbeat(self):
155        seen, _err = self.run_lines([(0, "=== Step 5: downloading Qwen3.8-Flash-Next Q2_0 ==="), (1.3, "[X] stopped for the test")])
156        beats = [x for _t, x in seen if "still working" in x]
157        self.assertGreaterEqual(len(beats), 2, seen)
158        self.assertTrue(beats[0].startswith("Getting the model files (still working, "), beats)
159
160
161class Words(unittest.TestCase):
162    def test_the_waiting_phase(self):
163        w = progress_words.describe(5, ["=== Step 5: downloading x ===", "  Waiting for github.com to answer (25 s so far) ..."])
164        self.assertEqual((w.phase, w.label), ("waiting", "Waiting for github.com to answer (25 s so far)"))
165        w = progress_words.describe(5, ["=== Step 5: downloading x ===", "  Waiting for github.com to answer (25 s so far) ...",
166                                        "  model.gguf:   0.10 / 66.40 GB (0%)"])
167        self.assertNotEqual(w.phase, "waiting")
168
169    def test_the_app_string_is_the_same_sentence(self):
170        import json
171        from pathlib import Path
172        en = json.loads((Path(__file__).resolve().parents[2] / "apps" / "host" / "src" / "locales" / "net-en.json").read_text(encoding="utf-8"))
173        self.assertEqual(en["net01"], netpolicy.WORDS["waiting"].replace("{host}", "{0}").replace("{seconds}", "{1}"))
174
175    def test_a_host_name_keeps_its_small_letter(self):
176        self.assertEqual(capital("huggingface.co did not answer"), "huggingface.co did not answer")
177        self.assertEqual(capital("the update feed could not be read"), "The update feed could not be read")
178        self.assertEqual(capital("no engine. is here"), "No engine. is here")
179
180
181class PlainPrinter(unittest.TestCase):
182    def test_the_second_download_shows_its_first_figure(self):
183        buf = io.StringIO()
184        with mock.patch.object(cmd.sys, "stdout", buf):
185            emit = cmd._printer()
186            emit(Event("model", "Getting Q2_0 ready…", 0))
187            emit(Event("model", "Downloading the model files: 30.0 of 66.4 GB", 45))
188            emit(Event("model", "Downloading the model files: 66.4 of 66.4 GB", 100))
189            emit(Event("model", "Downloading the picture reader: 0.0 of 0.9 GB", 0))
190            emit(Event("model", "Downloading the picture reader: 0.0 of 0.9 GB", 1))
191            emit(Event("model", "Downloading the picture reader: 0.1 of 0.9 GB", 12))
192        text = buf.getvalue()
193        self.assertIn("Downloading the picture reader: 0.0 of 0.9 GB", text)
194        self.assertIn("Downloading the picture reader: 0.1 of 0.9 GB", text)
195        self.assertEqual(text.count("picture reader"), 2)               # the same sentence is still thinned to 10% steps
196
197
198if __name__ == "__main__":
199    unittest.main()