diff --git a/apps/host/scripts/make-net-locales.py b/apps/host/scripts/make-net-locales.py new file mode 100644 index 0000000000..459686e009 --- /dev/null +++ b/apps/host/scripts/make-net-locales.py @@ -0,0 +1,46 @@ +"""Writes src/locales/net-.json: the line shown while a download server has not answered yet (lane NET, owner wording 11-10, W14). +Run from apps/host: python scripts/make-net-locales.py +The English text is strata_control/netpolicy.py WORDS["waiting"] with {host} -> {0} and {seconds} -> {1}; setup prints it and +strata_control/progress_words.py hands it to the app as the install step's label. Every entry names all nine languages; keys are net01.. in +the order of S. Placeholders ({0}, {1}) must be kept in every language. The eight translations are first drafts for the owner's later look.""" +import json +import re +from pathlib import Path + +LANGS = ["en", "zh", "ja", "de", "es", "ru", "pt", "ko", "fr"] +S = [] + + +def add(en, zh, ja, de, es, ru, pt, ko, fr): + S.append(dict(en=en, zh=zh, ja=ja, de=de, es=es, ru=ru, pt=pt, ko=ko, fr=fr)) + + +add("Waiting for {0} to answer ({1} s so far)", + "正在等待 {0} 响应(已等待 {1} 秒)", + "{0} の応答を待っています({1} 秒経過)", + "Warten auf eine Antwort von {0} (bisher {1} s)", + "Esperando la respuesta de {0} ({1} s hasta ahora)", + "Ожидание ответа от {0} (прошло {1} с)", + "A aguardar a resposta de {0} ({1} s até agora)", + "{0}의 응답을 기다리는 중 ({1}초 경과)", + "En attente de la réponse de {0} ({1} s jusqu'ici)") + +here = Path(__file__).resolve().parent.parent / "src" / "locales" +NBSP = " " + + +def french(text): + text = re.sub(r"(?<=[A-Za-zÀ-ſ])'(?=[A-Za-zÀ-ſ{])", "’", text) + text = re.sub(r"(?<=\S) ([:;?!])", NBSP + r"\1", text) + return text + + +for lang in LANGS: + data = {} + for i, entry in enumerate(S): + text = entry[lang] + assert sorted(re.findall(r"\{\d+\}", entry["en"])) == sorted(re.findall(r"\{\d+\}", text)), (lang, entry["en"], text) + data[f"net{i + 1:02d}"] = french(text) if lang == "fr" else text + with (here / f"net-{lang}.json").open("w", encoding="utf-8", newline="\n") as handle: + handle.write(json.dumps(data, ensure_ascii=False, indent=1) + "\n") +print("written", len(S), "strings in", len(LANGS), "languages") diff --git a/apps/host/src/lib/catalog-de.ts b/apps/host/src/lib/catalog-de.ts index e224235aea..255c665127 100644 --- a/apps/host/src/lib/catalog-de.ts +++ b/apps/host/src/lib/catalog-de.ts @@ -14,4 +14,5 @@ import r3 from '../locales/r3-de.json'; import pic from '../locales/pic-de.json'; import gui from '../locales/gui-de.json'; import sav from '../locales/sav-de.json'; -export default {...base,...tune,...tools,...fix,...gh,...ui,...engine,...pick,...df2,...upd,...r3,...pic,...gui,...sav} as Record; +import net from '../locales/net-de.json'; +export default {...base,...tune,...tools,...fix,...gh,...ui,...engine,...pick,...df2,...upd,...r3,...pic,...gui,...sav,...net} as Record; diff --git a/apps/host/src/lib/catalog-es.ts b/apps/host/src/lib/catalog-es.ts index 95c4103984..fc1a16e676 100644 --- a/apps/host/src/lib/catalog-es.ts +++ b/apps/host/src/lib/catalog-es.ts @@ -14,4 +14,5 @@ import r3 from '../locales/r3-es.json'; import pic from '../locales/pic-es.json'; import gui from '../locales/gui-es.json'; import sav from '../locales/sav-es.json'; -export default {...base,...tune,...tools,...fix,...gh,...ui,...engine,...pick,...df2,...upd,...r3,...pic,...gui,...sav} as Record; +import net from '../locales/net-es.json'; +export default {...base,...tune,...tools,...fix,...gh,...ui,...engine,...pick,...df2,...upd,...r3,...pic,...gui,...sav,...net} as Record; diff --git a/apps/host/src/lib/catalog-fr.ts b/apps/host/src/lib/catalog-fr.ts index d7662056ea..5518f4f092 100644 --- a/apps/host/src/lib/catalog-fr.ts +++ b/apps/host/src/lib/catalog-fr.ts @@ -14,4 +14,5 @@ import r3 from '../locales/r3-fr.json'; import pic from '../locales/pic-fr.json'; import gui from '../locales/gui-fr.json'; import sav from '../locales/sav-fr.json'; -export default {...base,...tune,...tools,...fix,...gh,...ui,...engine,...pick,...df2,...upd,...r3,...pic,...gui,...sav} as Record; +import net from '../locales/net-fr.json'; +export default {...base,...tune,...tools,...fix,...gh,...ui,...engine,...pick,...df2,...upd,...r3,...pic,...gui,...sav,...net} as Record; diff --git a/apps/host/src/lib/catalog-ja.ts b/apps/host/src/lib/catalog-ja.ts index a8ccec9b44..250912030a 100644 --- a/apps/host/src/lib/catalog-ja.ts +++ b/apps/host/src/lib/catalog-ja.ts @@ -14,4 +14,5 @@ import r3 from '../locales/r3-ja.json'; import pic from '../locales/pic-ja.json'; import gui from '../locales/gui-ja.json'; import sav from '../locales/sav-ja.json'; -export default {...base,...tune,...tools,...fix,...gh,...ui,...engine,...pick,...df2,...upd,...r3,...pic,...gui,...sav} as Record; +import net from '../locales/net-ja.json'; +export default {...base,...tune,...tools,...fix,...gh,...ui,...engine,...pick,...df2,...upd,...r3,...pic,...gui,...sav,...net} as Record; diff --git a/apps/host/src/lib/catalog-ko.ts b/apps/host/src/lib/catalog-ko.ts index b45659813d..f3f7f3f5f7 100644 --- a/apps/host/src/lib/catalog-ko.ts +++ b/apps/host/src/lib/catalog-ko.ts @@ -14,4 +14,5 @@ import r3 from '../locales/r3-ko.json'; import pic from '../locales/pic-ko.json'; import gui from '../locales/gui-ko.json'; import sav from '../locales/sav-ko.json'; -export default {...base,...tune,...tools,...fix,...gh,...ui,...engine,...pick,...df2,...upd,...r3,...pic,...gui,...sav} as Record; +import net from '../locales/net-ko.json'; +export default {...base,...tune,...tools,...fix,...gh,...ui,...engine,...pick,...df2,...upd,...r3,...pic,...gui,...sav,...net} as Record; diff --git a/apps/host/src/lib/catalog-pt.ts b/apps/host/src/lib/catalog-pt.ts index ca4239c9b9..e9f751fa31 100644 --- a/apps/host/src/lib/catalog-pt.ts +++ b/apps/host/src/lib/catalog-pt.ts @@ -14,4 +14,5 @@ import r3 from '../locales/r3-pt.json'; import pic from '../locales/pic-pt.json'; import gui from '../locales/gui-pt.json'; import sav from '../locales/sav-pt.json'; -export default {...base,...tune,...tools,...fix,...gh,...ui,...engine,...pick,...df2,...upd,...r3,...pic,...gui,...sav} as Record; +import net from '../locales/net-pt.json'; +export default {...base,...tune,...tools,...fix,...gh,...ui,...engine,...pick,...df2,...upd,...r3,...pic,...gui,...sav,...net} as Record; diff --git a/apps/host/src/lib/catalog-ru.ts b/apps/host/src/lib/catalog-ru.ts index 778b42acb0..0c6b8661b6 100644 --- a/apps/host/src/lib/catalog-ru.ts +++ b/apps/host/src/lib/catalog-ru.ts @@ -14,4 +14,5 @@ import r3 from '../locales/r3-ru.json'; import pic from '../locales/pic-ru.json'; import gui from '../locales/gui-ru.json'; import sav from '../locales/sav-ru.json'; -export default {...base,...tune,...tools,...fix,...gh,...ui,...engine,...pick,...df2,...upd,...r3,...pic,...gui,...sav} as Record; +import net from '../locales/net-ru.json'; +export default {...base,...tune,...tools,...fix,...gh,...ui,...engine,...pick,...df2,...upd,...r3,...pic,...gui,...sav,...net} as Record; diff --git a/apps/host/src/lib/catalog-zh.ts b/apps/host/src/lib/catalog-zh.ts index 8850286164..0f4903cf9e 100644 --- a/apps/host/src/lib/catalog-zh.ts +++ b/apps/host/src/lib/catalog-zh.ts @@ -14,4 +14,5 @@ import r3 from '../locales/r3-zh.json'; import pic from '../locales/pic-zh.json'; import gui from '../locales/gui-zh.json'; import sav from '../locales/sav-zh.json'; -export default {...base,...tune,...tools,...fix,...gh,...ui,...engine,...pick,...df2,...upd,...r3,...pic,...gui,...sav} as Record; +import net from '../locales/net-zh.json'; +export default {...base,...tune,...tools,...fix,...gh,...ui,...engine,...pick,...df2,...upd,...r3,...pic,...gui,...sav,...net} as Record; diff --git a/apps/host/src/lib/i18n.ts b/apps/host/src/lib/i18n.ts index 5d3dff79dc..2da812a695 100644 --- a/apps/host/src/lib/i18n.ts +++ b/apps/host/src/lib/i18n.ts @@ -21,13 +21,15 @@ import pic_en from '../locales/pic-en.json'; import gui_en from '../locales/gui-en.json'; /* The notice for chats the host could not write (sav-.json, scripts/make-chatsave-locales.py). */ import sav_en from '../locales/sav-en.json'; +/* The line shown while a download server has not answered yet (net-.json, scripts/make-net-locales.py; strata_control/netpolicy.py). */ +import net_en from '../locales/net-en.json'; export const LANGUAGES=[{value:'en',label:'English'},{value:'zh',label:'中文(简体)'},{value:'ja',label:'日本語'},{value:'de',label:'Deutsch'},{value:'fr',label:'Français'},{value:'es',label:'Español'},{value:'ru',label:'Русский'},{value:'pt',label:'Português'},{value:'ko',label:'한국어'}] as const; export type Language=typeof LANGUAGES[number]['value']; /* The Tune model dialog's strings live in tune-.json (apps/host/scripts/make-tune-locales.py) so other interface work does not collide with them. */ /* The tool-server, picture and agent-result strings of the tools and images fixes live in tools-.json for the same reason. */ /* The strings that had no key in the files above (#3479, #3825) and the 0.2.4.3 fixes live in fix-.json (scripts/make-fix-locales.py). */ -const english:Record={...baseEnglish,...tune_en,...tools_en,...fix_en,...gh_en,...ui_en,...engine_en,...pick_en,...df2_en,...upd_en,...r3_en,...pic_en,...gui_en,...sav_en}; +const english:Record={...baseEnglish,...tune_en,...tools_en,...fix_en,...gh_en,...ui_en,...engine_en,...pick_en,...df2_en,...upd_en,...r3_en,...pic_en,...gui_en,...sav_en,...net_en}; /* English is the key of every string, so it stays in the main file. The other eight languages are one file each, fetched the first time a language is used (the saved language before the first screen is drawn, a language picked later when it is picked): most people read one of the nine. */ type Catalog=Record; diff --git a/apps/host/src/locales/net-de.json b/apps/host/src/locales/net-de.json new file mode 100644 index 0000000000..abe2a46790 --- /dev/null +++ b/apps/host/src/locales/net-de.json @@ -0,0 +1,3 @@ +{ + "net01": "Warten auf eine Antwort von {0} (bisher {1} s)" +} diff --git a/apps/host/src/locales/net-en.json b/apps/host/src/locales/net-en.json new file mode 100644 index 0000000000..bef38617f1 --- /dev/null +++ b/apps/host/src/locales/net-en.json @@ -0,0 +1,3 @@ +{ + "net01": "Waiting for {0} to answer ({1} s so far)" +} diff --git a/apps/host/src/locales/net-es.json b/apps/host/src/locales/net-es.json new file mode 100644 index 0000000000..15e7eed423 --- /dev/null +++ b/apps/host/src/locales/net-es.json @@ -0,0 +1,3 @@ +{ + "net01": "Esperando la respuesta de {0} ({1} s hasta ahora)" +} diff --git a/apps/host/src/locales/net-fr.json b/apps/host/src/locales/net-fr.json new file mode 100644 index 0000000000..4663dad34b --- /dev/null +++ b/apps/host/src/locales/net-fr.json @@ -0,0 +1,3 @@ +{ + "net01": "En attente de la réponse de {0} ({1} s jusqu’ici)" +} diff --git a/apps/host/src/locales/net-ja.json b/apps/host/src/locales/net-ja.json new file mode 100644 index 0000000000..6bb47b3b39 --- /dev/null +++ b/apps/host/src/locales/net-ja.json @@ -0,0 +1,3 @@ +{ + "net01": "{0} の応答を待っています({1} 秒経過)" +} diff --git a/apps/host/src/locales/net-ko.json b/apps/host/src/locales/net-ko.json new file mode 100644 index 0000000000..59f980f16d --- /dev/null +++ b/apps/host/src/locales/net-ko.json @@ -0,0 +1,3 @@ +{ + "net01": "{0}의 응답을 기다리는 중 ({1}초 경과)" +} diff --git a/apps/host/src/locales/net-pt.json b/apps/host/src/locales/net-pt.json new file mode 100644 index 0000000000..a57258aac9 --- /dev/null +++ b/apps/host/src/locales/net-pt.json @@ -0,0 +1,3 @@ +{ + "net01": "A aguardar a resposta de {0} ({1} s até agora)" +} diff --git a/apps/host/src/locales/net-ru.json b/apps/host/src/locales/net-ru.json new file mode 100644 index 0000000000..dacdb13f88 --- /dev/null +++ b/apps/host/src/locales/net-ru.json @@ -0,0 +1,3 @@ +{ + "net01": "Ожидание ответа от {0} (прошло {1} с)" +} diff --git a/apps/host/src/locales/net-zh.json b/apps/host/src/locales/net-zh.json new file mode 100644 index 0000000000..c037212860 --- /dev/null +++ b/apps/host/src/locales/net-zh.json @@ -0,0 +1,3 @@ +{ + "net01": "正在等待 {0} 响应(已等待 {1} 秒)" +} diff --git a/apps/host/tests/net-waiting.test.mjs b/apps/host/tests/net-waiting.test.mjs new file mode 100644 index 0000000000..80f606a94b --- /dev/null +++ b/apps/host/tests/net-waiting.test.mjs @@ -0,0 +1,36 @@ +/** The line shown while a download server has not answered yet (lane NET, W14): in all nine languages, the host and the seconds filled in from + * setup's English label (strata_control/netpolicy.py WORDS["waiting"], handed over as the install step's label). */ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { build } from 'esbuild'; +import { fileURLToPath } from 'node:url'; +import { readFileSync } from 'node:fs'; + +const here = (p) => fileURLToPath(new URL(p, import.meta.url)); +async function bundle(entry) { + const result = await build({ + entryPoints: [here(entry)], bundle: true, format: 'esm', platform: 'node', write: false, logLevel: 'silent', + alias: { react: here('./helpers/react-stub.mjs') }, loader: { '.json': 'json' }, + }); + return import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}`); +} + +const LINE = 'Waiting for {0} to answer ({1} s so far)'; + +test('the waiting line exists in all nine languages with both placeholders', () => { + for (const lang of ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']) { + const file = JSON.parse(readFileSync(here(`../src/locales/net-${lang}.json`), 'utf8')); + assert.deepEqual(Object.keys(file), ['net01'], lang); + assert.ok(/\{0\}/.test(file.net01) && /\{1\}/.test(file.net01), `${lang} keeps {0} and {1}`); + if (lang === 'en') assert.equal(file.net01, LINE, 'the approved wording'); + else assert.notEqual(file.net01, LINE, `${lang} is translated`); + } +}); + +test('setup\'s English label is translated with the host and the seconds kept', async () => { + const i18n = await bundle('../src/lib/i18n.ts'); + await i18n.setTranslationLanguage('de'); + assert.equal(i18n.tr('Waiting for huggingface.co to answer (15 s so far)'), 'Warten auf eine Antwort von huggingface.co (bisher 15 s)'); + await i18n.setTranslationLanguage('en'); + assert.equal(i18n.tr('Waiting for huggingface.co to answer (15 s so far)'), 'Waiting for huggingface.co to answer (15 s so far)'); +}); diff --git a/conftest.py b/conftest.py index 09acf8fa14..81e275e3cf 100644 --- a/conftest.py +++ b/conftest.py @@ -4,6 +4,23 @@ A test that reaches it must never touch the real file, so the whole session gets import os import tempfile +import pytest as _pytest + + +@_pytest.fixture(autouse=True) +def _fresh_host_memory(): + """The network rule remembers, per process, a host that did not answer (strata_control/netpolicy.py HOSTS). A test run is one process: each + test starts with an empty memory, so one test's dead fake server does not make the next test's request "fail a moment ago".""" + def forget(): + try: + from strata_control import netpolicy + netpolicy.HOSTS.forget() + except ImportError: + pass + forget() + yield + forget() + _home = tempfile.mkdtemp(prefix="strata-pytest-config-") os.environ["APPDATA"] = _home os.environ["XDG_CONFIG_HOME"] = _home diff --git a/setup.py b/setup.py index 586be7c66e..9532091d93 100644 --- a/setup.py +++ b/setup.py @@ -64,6 +64,7 @@ from pathlib import Path from strata_control import acquisition from strata_control import tls +from strata_control import netpolicy tls.install() # #3722: HTTPS checks the server against the operating system's certificates (what Chrome and curl.exe do) from strata_control import atomic @@ -1117,13 +1118,29 @@ def _urlopen(req, timeout=None): (strata_control/acquisition.py), only an explicit setup, update or install does.""" acquisition.require("a download") try: - return urllib.request.urlopen(req, timeout=timeout) + # strata_control/netpolicy.py: `timeout` bounds the connection phase (lookup, connect, TLS, the answer's headers); a read after + # the answer that gets no byte for netpolicy.STALL_S ends the connection + return netpolicy.urlopen(req, timeout=timeout) except urllib.error.URLError as e: if tls.is_certificate_error(e): # not the raw urlopen text, and never a way to skip the check raise tls.CertificateProblem(tls.host_of(req.full_url if hasattr(req, "full_url") else str(req))) from None raise +def _open_net(req, check_memory: bool = True): + """One request under the network rule (strata_control/netpolicy.py): 12 s, then one retry with 30 s, a line naming the host after + 5 s, and a host that did not answer is not asked again in this run. Raises netpolicy.NetFailure, HTTPError or CertificateProblem.""" + return netpolicy.open_url(_urlopen, req, say=lambda line: say(f" {line} ..."), check_memory=check_memory) + + +def net_fail(e: "netpolicy.NetFailure", url: str, what=None): + """setup's stop for a host that cannot be reached: the plain sentence, the one next step, then the proxy and ModelScope hints.""" + extra = "".join(" " + h[2:3].upper() + h[3:] + "." for h in (proxy_hint(), source_hint(url)) if h) + if e.detail(): + say(f" ({e.host}: {e.detail()})") # the raw reason, for the log + fail(e.headline(netpolicy.what_words(what)), e.next_step() + extra) + + def run(cmd, cwd=None, env=None, check=True, quiet=False): """An install, build or preparation step (pip, cmake, a package manager, tools/*.py): never part of a start.""" acquisition.require("an install or build step (" + Path(str(cmd[0])).name + ")") @@ -2717,7 +2734,7 @@ class _Source: if stale is not None and self.final is not None and self.final != stale: return self.final # another connection already got a fresh address req = urllib.request.Request(self.url, headers={"User-Agent": "strata-setup", "Range": "bytes=0-0"}) - with _urlopen(req, timeout=60) as r: + with _urlopen(req, timeout=netpolicy.RETRY_CONNECT_S) as r: cr = (r.headers.get("Content-Range") or "").strip() if r.status != 206 or cr != f"bytes 0-0/{self.total}": raise _NoRange(f"HTTP {r.status}, Content-Range {cr!r}") @@ -2910,7 +2927,7 @@ def _fetch_run(src: _Source, st: _Pieces, f, run: list): try: url = src.get() req = urllib.request.Request(url, headers={"User-Agent": "strata-setup", "Range": f"bytes={pos}-{end}"}) - with _urlopen(req, timeout=60) as r: + with _urlopen(req, timeout=netpolicy.RETRY_CONNECT_S) as r: _check_ranged(r, pos, end, st.total, src.etag) while pos <= end: if st.stop.is_set(): @@ -3141,7 +3158,7 @@ def _repair_piece(src: _Source, st: _Pieces, f, i: int, stats: dict): try: url = src.get() req = urllib.request.Request(url, headers={"User-Agent": "strata-setup", "Range": f"bytes={pos}-{end}"}) - with _urlopen(req, timeout=60) as r: + with _urlopen(req, timeout=netpolicy.RETRY_CONNECT_S) as r: _check_ranged(r, pos, end, st.total, src.etag) while pos <= end: if st.stop.is_set(): @@ -3252,7 +3269,7 @@ def download_single(url: str, part: Path, total: int, label: str): break # ask for (a range past the end is a 416, retried 30 times) try: req = urllib.request.Request(url, headers={"User-Agent": "strata-setup", "Range": f"bytes={have}-"}) - with _urlopen(req, timeout=60) as r: + with _urlopen(req, timeout=netpolicy.RETRY_CONNECT_S) as r: if have: m = _CONTENT_RANGE.match(r.headers.get("Content-Range") or "") if r.status != 206 or not m or int(m.group(1)) != have or (total and int(m.group(3)) != total): @@ -3294,7 +3311,7 @@ def range_total(url: str) -> int: (ModelScope's: #1915); 0 when it does not say. With the length known the file comes over several connections.""" try: req = urllib.request.Request(url, headers={"User-Agent": "strata-setup", "Range": "bytes=0-0"}) - with _urlopen(req, timeout=60) as r: + with _urlopen(req, timeout=netpolicy.RETRY_CONNECT_S) as r: m = re.match(r"\s*bytes 0-0/(\d+)\s*$", r.headers.get("Content-Range") or "") return int(m.group(1)) if r.status == 206 and m else 0 except (OSError, http.client.HTTPException): @@ -3336,7 +3353,7 @@ def download(url, dst: Path, what=None): return ms = ms_file(url) if model_source() == "modelscope" else None if ms is not None: - if reachable(ms_url(*ms), timeout=30): + if reachable(ms_url(*ms), timeout=netpolicy.FIRST_CONNECT_S): url = ms_url(*ms) else: warn(f"{what or dst.name}: ModelScope does not answer; downloading it from {hf_endpoint()}") @@ -3345,10 +3362,11 @@ def download(url, dst: Path, what=None): total = 0 # the file's pinned size and SHA-256, when it has them (ModelScope's copy is checked against the same pin) pin = REPO_PINS.get(ms[0], {}).get(ms[1].rsplit("/", 1)[-1]) if ms is not None else file_pin(url) - for attempt in range(5): + for _unpinned in range(2): # the size: one request under the network rule (no more 5 x 60 s in silence) try: req = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "strata-setup"}) - total = int(_urlopen(req, timeout=60).headers.get("Content-Length", 0)) + with _open_net(req) as r: + total = int(r.headers.get("Content-Length", 0) or 0) break except urllib.error.HTTPError as e: if e.code == 404 and hf_unpinned(url) != url: # the pinned revision is gone from the repository @@ -3360,17 +3378,15 @@ def download(url, dst: Path, what=None): url = hf_unpinned(url) pin = None continue - if attempt == 4: - fail(f"cannot reach {url.split('/')[2]} ({e})", - "check your internet connection and run it again" + proxy_hint() + source_hint(url)) - time.sleep(5) - except tls.CertificateProblem as e: # the same answer five times: no retry + fail(f"cannot reach {url.split('/')[2]} ({e})", + "check your internet connection and run it again" + proxy_hint() + source_hint(url)) + except tls.CertificateProblem as e: # the same answer every time: no retry fail(f"cannot download from {url.split('/')[2]}: its security certificate was not accepted", str(e)) - except OSError as e: - if attempt == 4: - fail(f"cannot reach {url.split('/')[2]} ({e})", - "check your internet connection and run it again" + proxy_hint() + source_hint(url)) - time.sleep(5) + except netpolicy.NetFailure as e: + net_fail(e, url, what) + except (OSError, http.client.HTTPException) as e: + fail(f"cannot reach {url.split('/')[2]} ({e})", + "check your internet connection and run it again" + proxy_hint() + source_hint(url)) if not total: total = range_total(url) meta = ms_meta(*ms) if ms is not None else None diff --git a/strata_cli/launch/cmd.py b/strata_cli/launch/cmd.py index 5ae148be5e..80cee8878f 100644 --- a/strata_cli/launch/cmd.py +++ b/strata_cli/launch/cmd.py @@ -565,7 +565,7 @@ def _interrupted_move_notice() -> None: def _printer(quiet: bool = False): """An emit callback that prints readable lines: new text once, progress in steps of 10% when not on a terminal.""" - state = {"last": None, "pct": -10, "stage": None} + state = {"last": None, "pct": -10, "stage": None, "key": None} isatty = sys.stdout.isatty() def emit(ev) -> None: @@ -577,9 +577,10 @@ def _printer(quiet: bool = False): sys.stdout.write(f"\r {text} {ev.pct:.0f}% " + ("\n" if ev.pct >= 100 else "")) sys.stdout.flush() return - if ev.pct < 100 and ev.pct < state["pct"] + 10 and state["stage"] == ev.stage: + key = text.rsplit(":", 1)[0] # the sentence without its figure: a new sentence is always shown + if ev.pct < 100 and ev.pct < state["pct"] + 10 and state["stage"] == ev.stage and key == state["key"]: return - state["pct"] = ev.pct + state["pct"], state["key"] = ev.pct, key if ev.stage == "start" and ev.text.startswith("Loading the model") and state["stage"] == "start" and not isatty: n = int("".join(ch for ch in ev.text.split("…")[-1] if ch.isdigit()) or 0) if n % 15: diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index bdf9a02a26..648f012add 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -109,7 +109,11 @@ def missing_file(failure: str) -> bool: def capital(text: str) -> str: - """A reason that was written to stand alone ("the update feed could not be read: ...") starts the sentence it is joined to with a capital.""" + """A reason that was written to stand alone ("the update feed could not be read: ...") starts the sentence it is joined to with a capital. + A host name stays as it is written ("github.com did not answer ...", strata_control/netpolicy.py).""" + first = text.split(" ", 1)[0] + if "." in first.strip(".") and re.fullmatch(r"[a-z0-9.-]+", first.rstrip(".")): + return text return text[:1].upper() + text[1:] @@ -1256,9 +1260,10 @@ class Runner: for line in self._read_lines(p): if self.cancel.is_set(): self._stop_children() + self.keep_setup_output(lines + [f"(you stopped it{': ' + said[0] if said else ''})"]) # the log says where it stood raise Cancelled() if line is None: # nothing printed for a while: the long steps (packing, converting) are silent - if said and said[1] != "download" and time.monotonic() - quiet_since >= self.HEARTBEAT_S: + if said and time.monotonic() - quiet_since >= self.HEARTBEAT_S: # (the download phase too: a server that does not answer is silent) quiet_since = time.monotonic() self.emit("model", f"{said[0]} (still working, {_elapsed(time.monotonic() - step_since)} so far)", None, step=step_seen) continue @@ -1279,11 +1284,10 @@ class Runner: dl, phase, label = prog.get("download"), prog.get("phase"), prog.get("label") if prog.get("step") != step_seen: step_seen, step_since = prog.get("step"), time.monotonic() - if label and not dl: - said = (label, phase) - else: - said = None - if dl and dl.get("total_gb", 0) >= 0.05 and not (s.model_path and phase == "download"): + said = (label, phase) if label else None + if phase == "waiting": # setup is waiting for a server to answer: say which one (netpolicy's line) + self.emit("model", label, None, step=prog.get("step")) + elif dl and dl.get("total_gb", 0) >= 0.05 and not (s.model_path and phase == "download"): if phase == "download" and already is None: already = float(dl["percent"]) >= 99.5 text = download_text(dl, bool(already) and phase == "download", label) diff --git a/strata_control/netpolicy.py b/strata_control/netpolicy.py index a769843b1e..4609ff7771 100644 --- a/strata_control/netpolicy.py +++ b/strata_control/netpolicy.py @@ -11,7 +11,8 @@ the screen. The rule here: unreachable, a refused certificate, an HTTP error other than 408/429/5xx. 3. One retry, ``RETRY_GAP_S`` later, for a timeout, a reset before the first byte, or HTTP 408/429/5xx. A host that never answers is given up after about 12 + 2 + 30 = 44 s. -4. A host given up under rule 3 is not tried again for ``HOST_MEMORY_S`` *in the same process* (``HOSTS``, memory only, never on disk: +4. A host given up under rule 3 after the whole window (12 s, then 30 s) is not tried again for ``HOST_MEMORY_S`` *in the same process* + (``HOSTS``, memory only, never on disk; a call with shorter limits reads it but never writes it; a new run always tries afresh). The next file from it fails at once with the same message. 5. Once the answer has come, a read that gets no byte for ``STALL_S`` ends that connection (the caller resumes from the byte it reached). A download stops only after ``GIVE_UP_S`` in a row without a new byte (``StallClock``); there is no total time cap, so a @@ -59,9 +60,14 @@ WORDS = { "Models that are already on this computer still start without the internet."), "stalled": "No data arrived for {minutes} minutes, so the download of {what} stopped at {percent}%.", "stalled_next": "Run the same command again: it continues where it stopped.", + "update_no_answer": ("{host} did not answer within {seconds} seconds, so the update check could not run. Check that this computer can open " + "https://{host}, then try again. Strata keeps working with what is installed."), + # (W7's two companions, owner 11-10) + "update_offline": "this computer could not connect to {host} (it looks offline), so the update check could not run. Strata keeps working with what is installed.", + "update_again": "{host} did not answer a moment ago, so the update check was not tried again. Strata keeps working with what is installed.", } -#: the waiting line as setup prints it (" Waiting for huggingface.co to answer (15 s so far) ..."), for the progress readers +#: the waiting line as setup prints it (" Waiting for github.com to answer (15 s so far) ..."), for the progress readers WAITING_RE = re.compile(r"^\s*Waiting for (?P\S+) to answer \((?P\d+) s so far\)") @@ -256,17 +262,12 @@ def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_ad left = deadline - time.monotonic() if left <= 0: break - sock = socket.socket(af, socktype, proto) - try: - sock.settimeout(left) - if source_address: - sock.bind(source_address) - sock.connect(sa) + try: # through socket.create_connection (a numeric address: no second lookup) + sock = socket.create_connection(sa[:2], left, source_address) sock.settimeout(max(0.05, deadline - time.monotonic())) return sock except OSError as exc: last = exc - sock.close() if last is not None and not isinstance(last, (TimeoutError, socket.timeout)): raise last raise TimeoutError(f"{host} did not accept a connection within {limit:.0f} s") @@ -340,7 +341,7 @@ _OPENER_LOCK = threading.Lock() def urlopen(request, timeout=None): """urllib.request.urlopen with the rule's connection classes: `timeout` bounds the connection phase, reads after the answer stall - out after STALL_S. Without a timeout it behaves as urllib does.""" + out after STALL_S. Without a timeout it behaves as urllib does. (Tests that fake the network replace this function.)""" global _OPENER with _OPENER_LOCK: if _OPENER is None: @@ -354,7 +355,7 @@ def urlopen(request, timeout=None): # ------------------------------------------------------------------------------------------------ one request under the rule def open_url(open_fn: Callable, request, *, host: str | None = None, say: Callable[[str], None] | None = None, - memory: HostMemory | None = None, limits: Iterable[float] = CONNECT_LIMITS, gap: float | None = None, + memory: HostMemory | None = None, limits: Iterable[float] | None = None, gap: float | None = None, sleep: Callable[[float], None] = time.sleep, clock: Callable[[], float] = time.monotonic, check_memory: bool = True, wait_after: float | None = None, wait_every: float | None = None): """open_fn(request, timeout=limit) under rules 1-4 and 6. Returns the answer. Raises NetFailure when the host did not answer or @@ -362,10 +363,18 @@ def open_url(open_fn: Callable, request, *, host: str | None = None, say: Callab refusal of the acquisition rule) unchanged.""" url = getattr(request, "full_url", request) host = host or host_of(str(url)) + try: # remembered per host and port (a test server on 127.0.0.1 is not github.com) + key = (urllib.parse.urlsplit(str(url)).netloc or host).lower() + except ValueError: + key = host memory = HOSTS if memory is None else memory - if check_memory and memory.failed_recently(host): + if check_memory and memory.failed_recently(key): raise NetFailure(host, "again") - limits = tuple(limits) + limits = tuple(CONNECT_LIMITS if limits is None else limits) + # Only a failure that had the whole window of the rule (12 s, then 30 s) is remembered: a call with shorter limits (an optional read + # of 5 s) may READ the memory and skip a host that already failed, but never WRITES it, so a slow but working link that a short read + # gave up on still gets its full attempt from a download that needs it (coordinator, 11-10). + full = len(limits) >= len(CONNECT_LIMITS) and all(a >= b for a, b in zip(limits, CONNECT_LIMITS)) gap = RETRY_GAP_S if gap is None else gap start = clock() with WaitLine(host, say, wait_after, wait_every, clock): @@ -388,7 +397,8 @@ def open_url(open_fn: Callable, request, *, host: str | None = None, say: Callab sleep(gap) continue if k in ("no_answer", "retry"): - memory.remember(host) + if full: + memory.remember(key) raise NetFailure(host, "no_answer", exc, clock() - start) from None if k == "offline": raise NetFailure(host, "offline", exc, clock() - start) from None diff --git a/strata_control/progress_words.py b/strata_control/progress_words.py index dddf46fb39..d118ee55be 100644 --- a/strata_control/progress_words.py +++ b/strata_control/progress_words.py @@ -18,6 +18,12 @@ from dataclasses import dataclass STEP_RE = re.compile(r"=== Step (\d+): (.+?) ===") CHECKING_RE = re.compile(r"^\s*checking\b.*\bSHA-256\b", re.I) PROGRESS_RE = re.compile(r"\s*(\S.*?): +([\d.]+) / ([\d.]+) GB \((\d+)%\)") +try: # the network rule's own line and words (one place for them) + from strata_control.netpolicy import WAITING_RE, WORDS as _NET_WORDS + WAITING_WORDS = _NET_WORDS["waiting"] +except ImportError: # an older strata_control beside a newer reader: never waiting + WAITING_RE = re.compile(r"(?!)") + WAITING_WORDS = "" @dataclass(frozen=True) @@ -51,6 +57,10 @@ def describe(step: int | None, lines: list[str], download: dict | None = None) - download figure in them (`{"file": ..., "percent": ...}` or None).""" recent = _after_last_step(lines) dl_file = str((download or {}).get("file", "")).lower() + last_line = next((ln for ln in reversed(recent) if ln.strip()), "") + waiting = WAITING_RE.match(last_line) + if waiting: # a server has not answered yet (strata_control/netpolicy.py prints this line) + return Words("waiting", WAITING_WORDS.format(host=waiting.group("host"), seconds=waiting.group("seconds"))) if step is None: return Words("working", "Getting your model ready") if step <= 2: diff --git a/tests/terminal/test_net_launch_waits.py b/tests/terminal/test_net_launch_waits.py new file mode 100644 index 0000000000..6d61e3e304 --- /dev/null +++ b/tests/terminal/test_net_launch_waits.py @@ -0,0 +1,180 @@ +"""Item 1 of lane NET: the silent wait in launch step 5. setup.download() against a server that accepts and never answers, a refusing +port and a working one (the rule's limits scaled down); what `strata launch` shows while setup waits (the waiting line, the heartbeat in +the download phase, the plain printer); setup's [X] reason in the launch error and the setup log.""" + +from __future__ import annotations + +import contextlib +import io +import re +import time +import unittest +from unittest import mock + +import setup +from strata_cli.launch import cmd +from strata_cli.launch.runner import Event, LaunchError, Runner, capital +from strata_control import netpolicy, progress_words +from tests.terminal.test_flow2_022 import Base as FlowBase +from tests.terminal.test_netpolicy import BlackHole, Server, ok_body, refused_port + + +def scaled(): + """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.""" + return [mock.patch.object(netpolicy, "CONNECT_LIMITS", (0.4, 0.8)), mock.patch.object(netpolicy, "RETRY_GAP_S", 0.1), + mock.patch.object(netpolicy, "WAIT_LINE_AFTER_S", 0.2), mock.patch.object(netpolicy, "WAIT_LINE_EVERY_S", 0.3), + mock.patch.dict("os.environ", {"STRATA_SOURCE": "huggingface"})] + + +class SetupDownloadWaits(unittest.TestCase): + def setUp(self): + import tempfile + from pathlib import Path + for p in scaled(): + p.start() + self.addCleanup(p.stop) + self.memory = netpolicy.HostMemory() + p = mock.patch.object(netpolicy, "HOSTS", self.memory) + p.start() + self.addCleanup(p.stop) + t = tempfile.TemporaryDirectory(prefix="strata-netwait-") + self.addCleanup(t.cleanup) + self.dir = Path(t.name) + + def download(self, url, name="model-00001-of-00002.gguf", what=None): + buf = io.StringIO() + t0 = time.monotonic() + with contextlib.redirect_stdout(buf): + try: + setup.download(url, self.dir / name, what) + code = 0 + except SystemExit as e: + code = e.code + return code, buf.getvalue(), time.monotonic() - t0 + + def test_a_black_hole_shows_the_host_soon_and_fails_fast_with_the_reason(self): + hole = BlackHole() + self.addCleanup(hole.close) + code, out, took = self.download(f"http://127.0.0.1:{hole.port}/m/model-00001-of-00002.gguf") + self.assertEqual(code, 1, out) + self.assertLess(took, 2.5, out) # 0.4 + 0.1 + 0.8, not 5 x 60 + 4 x 5 s + self.assertRegex(out, r"(?m)^ Waiting for 127\.0\.0\.1 to answer \(0 s so far\) \.\.\.$") + self.assertRegex(out, r"\[X\] 127\.0\.0\.1 did not answer within 1 seconds, so the model files could not be downloaded\.") + 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. " + "Models that are already on this computer still start without the internet.", out) + self.assertEqual(len(hole.held), 2) + # the next file from the same server: at once, with the same sentence + code, out, took = self.download(f"http://127.0.0.1:{hole.port}/m/model-00002-of-00002.gguf", "model-00002-of-00002.gguf") + self.assertEqual(code, 1) + self.assertLess(took, 0.3) + self.assertIn("[X] 127.0.0.1 did not answer a moment ago either, so the model files could not be downloaded.", out) + self.assertEqual(len(hole.held), 2) + + def test_the_picture_reader_is_named(self): + hole = BlackHole() + self.addCleanup(hole.close) + code, out, _t = self.download(f"http://127.0.0.1:{hole.port}/m/mmproj.gguf", "mmproj.gguf", "vision encoder") + self.assertIn("so the picture reader could not be downloaded.", out) + + def test_a_refusing_port_fails_at_once_with_no_waiting_line(self): + port = refused_port() + code, out, took = self.download(f"http://127.0.0.1:{port}/m/model-00001-of-00002.gguf") + self.assertEqual(code, 1) + self.assertLess(took, 0.5) + self.assertNotIn("Waiting for", out) + 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) + + def test_a_working_server_still_downloads_and_prints_no_waiting_line(self): + srv = Server(ok_body(b"x" * 1000)) + self.addCleanup(srv.close) + code, out, _t = self.download(srv.url("/m/small.bin"), "small.bin") + self.assertEqual(code, 0, out) + self.assertEqual((self.dir / "small.bin").read_bytes(), b"x" * 1000) + self.assertNotIn("Waiting for", out) + + +class LaunchShowsTheWait(FlowBase): + def run_lines(self, steps, heartbeat=0.3): + r = self.runner(family="qwen", model="Q2_0", vision="off", context=32768) + r.HEARTBEAT_S = heartbeat + seen = [] + r.emit_cb = lambda ev: seen.append((time.monotonic(), ev.text)) + + def slow(): + for delay, line in steps: + time.sleep(delay) + yield line + "\n" + proc = mock.Mock() + proc.stdout = slow() + proc.wait.return_value = 1 + t0 = time.monotonic() + with mock.patch.object(Runner, "_spawn", return_value=proc), mock.patch.object(Runner, "adopt_prepared_files", return_value=None): + with self.assertRaises(LaunchError) as cm: + r.ensure_model() + return [(t - t0, x) for t, x in seen], cm.exception + + def test_the_waiting_line_is_shown_and_the_reason_is_the_error(self): + seen, err = self.run_lines([ + (0, "=== Step 5: downloading Qwen3.8-Flash-Next Q2_0 ==="), + (0.2, " Waiting for huggingface.co to answer (5 s so far) ..."), + (0.2, " Waiting for huggingface.co to answer (15 s so far) ..."), + (0, " (huggingface.co: TimeoutError: timed out)"), + (0, ""), + (0, " [X] huggingface.co did not answer within 44 seconds, so the model files could not be downloaded."), + (0, " Check that this computer can open https://huggingface.co, then run the same command again: what is already " + "downloaded is kept. Models that are already on this computer still start without the internet."), + ]) + texts = [x for _t, x in seen] + self.assertIn("Waiting for huggingface.co to answer (5 s so far)", texts) + self.assertIn("Waiting for huggingface.co to answer (15 s so far)", texts) + self.assertLess(seen[0][0], 0.2) # the step's own sentence at once, before setup says anything + self.assertIn("The model could not be installed. huggingface.co did not answer within 44 seconds, so the model files could not " + "be downloaded.", err.text) + self.assertIn("Check that this computer can open https://huggingface.co", err.next) + + def test_a_silent_download_phase_gets_the_heartbeat(self): + seen, _err = self.run_lines([(0, "=== Step 5: downloading Qwen3.8-Flash-Next Q2_0 ==="), (1.3, "[X] stopped for the test")]) + beats = [x for _t, x in seen if "still working" in x] + self.assertGreaterEqual(len(beats), 2, seen) + self.assertTrue(beats[0].startswith("Getting the model files (still working, "), beats) + + +class Words(unittest.TestCase): + def test_the_waiting_phase(self): + w = progress_words.describe(5, ["=== Step 5: downloading x ===", " Waiting for github.com to answer (25 s so far) ..."]) + self.assertEqual((w.phase, w.label), ("waiting", "Waiting for github.com to answer (25 s so far)")) + w = progress_words.describe(5, ["=== Step 5: downloading x ===", " Waiting for github.com to answer (25 s so far) ...", + " model.gguf: 0.10 / 66.40 GB (0%)"]) + self.assertNotEqual(w.phase, "waiting") + + def test_the_app_string_is_the_same_sentence(self): + import json + from pathlib import Path + en = json.loads((Path(__file__).resolve().parents[2] / "apps" / "host" / "src" / "locales" / "net-en.json").read_text(encoding="utf-8")) + self.assertEqual(en["net01"], netpolicy.WORDS["waiting"].replace("{host}", "{0}").replace("{seconds}", "{1}")) + + def test_a_host_name_keeps_its_small_letter(self): + self.assertEqual(capital("huggingface.co did not answer"), "huggingface.co did not answer") + self.assertEqual(capital("the update feed could not be read"), "The update feed could not be read") + self.assertEqual(capital("no engine. is here"), "No engine. is here") + + +class PlainPrinter(unittest.TestCase): + def test_the_second_download_shows_its_first_figure(self): + buf = io.StringIO() + with mock.patch.object(cmd.sys, "stdout", buf): + emit = cmd._printer() + emit(Event("model", "Getting Q2_0 ready…", 0)) + emit(Event("model", "Downloading the model files: 30.0 of 66.4 GB", 45)) + emit(Event("model", "Downloading the model files: 66.4 of 66.4 GB", 100)) + emit(Event("model", "Downloading the picture reader: 0.0 of 0.9 GB", 0)) + emit(Event("model", "Downloading the picture reader: 0.0 of 0.9 GB", 1)) + emit(Event("model", "Downloading the picture reader: 0.1 of 0.9 GB", 12)) + text = buf.getvalue() + self.assertIn("Downloading the picture reader: 0.0 of 0.9 GB", text) + self.assertIn("Downloading the picture reader: 0.1 of 0.9 GB", text) + self.assertEqual(text.count("picture reader"), 2) # the same sentence is still thinned to 10% steps + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/terminal/test_netpolicy.py b/tests/terminal/test_netpolicy.py index b13eaaec6a..963faf45da 100644 --- a/tests/terminal/test_netpolicy.py +++ b/tests/terminal/test_netpolicy.py @@ -129,6 +129,9 @@ class Base(unittest.TestCase): self.memory = N.HostMemory() self.opener = N.build_opener(urllib.request.ProxyHandler({})) self.lines = [] + 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 + p.start() + self.addCleanup(p.stop) def open(self, url, limits=(0.4, 0.8), **kw): kw.setdefault("memory", self.memory) @@ -194,6 +197,24 @@ class BlackHoleFailsFast(Base): self.open(f"http://127.0.0.1:{hole.port}/b", check_memory=False) self.assertEqual(cm.exception.kind, "no_answer") + def test_a_shorter_call_reads_the_memory_but_never_writes_it(self): + hole = BlackHole() + self.addCleanup(hole.close) + with self.assertRaises(N.NetFailure) as cm: + self.open(f"http://127.0.0.1:{hole.port}/models", limits=(0.2, 0.2)) # an optional 5 s read, scaled + self.assertEqual(cm.exception.kind, "no_answer") + self.assertFalse(self.memory.failed_recently(f"127.0.0.1:{hole.port}"), "a short read does not mark the host") + with self.assertRaises(N.NetFailure) as cm: # the required download: its own full window + self.open(f"http://127.0.0.1:{hole.port}/engine") + self.assertEqual(cm.exception.kind, "no_answer") + self.assertEqual(len(hole.held), 4) + self.assertTrue(self.memory.failed_recently(f"127.0.0.1:{hole.port}")) + t0 = time.monotonic() + with self.assertRaises(N.NetFailure) as cm: # and a later short read skips it at once + self.open(f"http://127.0.0.1:{hole.port}/models", limits=(0.2, 0.2)) + self.assertEqual(cm.exception.kind, "again") + self.assertLess(time.monotonic() - t0, 0.1) + def test_the_waiting_line_names_the_host(self): hole = BlackHole() self.addCleanup(hole.close) diff --git a/tests/terminal/test_no_acquisition.py b/tests/terminal/test_no_acquisition.py index 196b5fa9c8..0930d6be3b 100644 --- a/tests/terminal/test_no_acquisition.py +++ b/tests/terminal/test_no_acquisition.py @@ -222,6 +222,7 @@ class StartNeverAcquiresTests(unittest.TestCase): st.enter_context(mock.patch.object(setup, "ROOT", self.root)) st.enter_context(mock.patch.object(sys, "argv", ["setup.py", *argv])) st.enter_context(mock.patch.object(urllib.request, "urlopen", rec.urlopen)) + st.enter_context(mock.patch.object(setup.netpolicy, "urlopen", rec.urlopen)) for n in ("run", "call", "Popen", "check_call", "check_output"): st.enter_context(mock.patch.object(subprocess, n, rec.program)) st.enter_context(mock.patch.object(setup, "gpus", lambda: gpus or [])) @@ -292,7 +293,7 @@ class StartNeverAcquiresTests(unittest.TestCase): lambda: setup.cmake_build(self.root, self.root / "b", "strata", [], None, ""), lambda: setup.pip_cuda_libs(13), ] - with mock.patch.object(urllib.request, "urlopen", rec.urlopen), \ + with mock.patch.object(urllib.request, "urlopen", rec.urlopen), mock.patch.object(setup.netpolicy, "urlopen", rec.urlopen), \ mock.patch.object(subprocess, "run", rec.program), mock.patch.object(subprocess, "Popen", rec.program): with acquisition.forbidden(): for i, call in enumerate(calls): diff --git a/tests/terminal/test_tls_trust.py b/tests/terminal/test_tls_trust.py index 33daf5d72f..24500c75f4 100644 --- a/tests/terminal/test_tls_trust.py +++ b/tests/terminal/test_tls_trust.py @@ -86,7 +86,7 @@ class Plain(unittest.TestCase): import setup request = types.SimpleNamespace(full_url="https://github.com/x/y") with mock.patch.object(setup.acquisition, "require", lambda *a, **k: None), \ - mock.patch.object(setup.urllib.request, "urlopen", side_effect=cert_error()): + mock.patch.object(setup.netpolicy, "urlopen", side_effect=cert_error()): with self.assertRaises(tls.CertificateProblem) as cm: setup._urlopen(request) self.assertIn("github.com", str(cm.exception)) @@ -96,7 +96,7 @@ class Plain(unittest.TestCase): import setup refused = urllib.error.URLError(ConnectionRefusedError()) with mock.patch.object(setup.acquisition, "require", lambda *a, **k: None), \ - mock.patch.object(setup.urllib.request, "urlopen", side_effect=refused): + mock.patch.object(setup.netpolicy, "urlopen", side_effect=refused): with self.assertRaises(urllib.error.URLError): setup._urlopen(types.SimpleNamespace(full_url="https://github.com/x")) diff --git a/tools/test_setup_download.py b/tools/test_setup_download.py index 84c5a3a45a..38890aeb88 100644 --- a/tools/test_setup_download.py +++ b/tools/test_setup_download.py @@ -705,7 +705,7 @@ class WholeMarkNeedsThePin(unittest.TestCase): shard.write_bytes(b"x" * 8) pin = (8, "ab" * 32) # a pin of this file's size, so the "full length" branch is the one taken calls = [] - with mock.patch.dict(setup.REPO_PINS[self.repo], {self.name: pin}), mock.patch.object(setup, "range_total", return_value=8), mock.patch.object(setup, "_urlopen", lambda *a, **k: type("R", (), {"headers": {"Content-Length": "8"}})()), mock.patch.object(setup, "verify_sha256", lambda *a, **k: calls.append(a)): + with mock.patch.dict(setup.REPO_PINS[self.repo], {self.name: pin}), mock.patch.object(setup, "range_total", return_value=8), mock.patch.object(setup, "_urlopen", lambda *a, **k: type("R", (), {"headers": {"Content-Length": "8"}, "__enter__": lambda s: s, "__exit__": lambda s, *e: False, "close": lambda s: None})()), mock.patch.object(setup, "verify_sha256", lambda *a, **k: calls.append(a)): setup.mark_whole_unless_pinned([shard], self.hf, own=False) self.assertFalse(setup.done(shard)) setup.download(self.hf + self.name, shard) diff --git a/tools/test_setup_engine_hash.py b/tools/test_setup_engine_hash.py index 2c09a8f2d0..c3ac4a850d 100644 --- a/tools/test_setup_engine_hash.py +++ b/tools/test_setup_engine_hash.py @@ -83,7 +83,7 @@ class WhereTheHashComesFrom(unittest.TestCase): def test_a_local_folder_asks_the_api_nothing_at_all(self): # Air-gapped and shared-IP installs must not depend on GitHub answering. - with mock.patch.object(setup.urllib.request, "urlopen", + with mock.patch.object(setup.netpolicy, "urlopen", side_effect=AssertionError("the API was called")): self.assertIsNone(setup.engine_digest(ASSET, LOCAL_BASE)) @@ -119,7 +119,7 @@ class DigestLookup(unittest.TestCase): seen.append(req.full_url) return R(payload) - patcher = mock.patch.object(setup.urllib.request, "urlopen", open_it) + patcher = mock.patch.object(setup.netpolicy, "urlopen", open_it) patcher.start() self.addCleanup(patcher.stop) return seen @@ -164,7 +164,7 @@ class DigestLookup(unittest.TestCase): def test_none_when_github_cannot_be_reached(self): for exc in (OSError("no network"), TimeoutError("slow")): - with mock.patch.object(setup.urllib.request, "urlopen", side_effect=exc): + with mock.patch.object(setup.netpolicy, "urlopen", side_effect=exc): self.assertIsNone(setup.engine_digest(ASSET, TAG_BASE), exc) def test_picks_the_asset_the_url_actually_wants(self): diff --git a/tools/test_setup_llama_archive.py b/tools/test_setup_llama_archive.py index 9a7bda52b1..a9dde516f7 100644 --- a/tools/test_setup_llama_archive.py +++ b/tools/test_setup_llama_archive.py @@ -42,7 +42,7 @@ class LlamaSourceArchive(unittest.TestCase): stack.enter_context(mock.patch.object(setup, "ROOT", self.root)) # a plain path: download() copies it (file:// plus a Windows drive letter is not one) stack.enter_context(mock.patch.object(setup, "LLAMA_CPP_ZIP", str(self.source))) - stack.enter_context(mock.patch.object(setup.urllib.request, "urlopen", + stack.enter_context(mock.patch.object(setup.netpolicy, "urlopen", side_effect=AssertionError("test must not use the network"))) stack.enter_context(contextlib.redirect_stdout(io.StringIO())) diff --git a/tools/test_setup_model_pins.py b/tools/test_setup_model_pins.py index d76c26623d..dac4bc99a0 100644 --- a/tools/test_setup_model_pins.py +++ b/tools/test_setup_model_pins.py @@ -125,7 +125,7 @@ class DownloadChecksThePin(unittest.TestCase): return Response(b"", length=length) return Response(body, status=200) - return seen, mock.patch.object(setup.urllib.request, "urlopen", urlopen) + return seen, mock.patch.object(setup.netpolicy, "urlopen", urlopen) def run_download(self, name, served, pinned, length=None): seen, patch = self.serve(served, length if length is not None else len(served)) @@ -177,7 +177,7 @@ class NotFoundOnThePinnedCommit(unittest.TestCase): def test_it_stops_with_a_plain_message(self): seen = [] out = io.StringIO() - with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.urllib.request, "urlopen", self.urlopen(seen)), \ + with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.netpolicy, "urlopen", self.urlopen(seen)), \ mock.patch.dict(setup.os.environ, {"STRATA_SOURCE": "huggingface"}), contextlib.redirect_stdout(out): setup.os.environ.pop("STRATA_ALLOW_UNPINNED", None) dst = Path(d) / "t.gguf" @@ -190,7 +190,7 @@ class NotFoundOnThePinnedCommit(unittest.TestCase): def test_the_opt_out_takes_the_current_file_and_says_so(self): seen = [] - with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.urllib.request, "urlopen", self.urlopen(seen)), \ + with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.netpolicy, "urlopen", self.urlopen(seen)), \ mock.patch.dict(setup.os.environ, {"STRATA_SOURCE": "huggingface", "STRATA_ALLOW_UNPINNED": "1"}), \ mock.patch.object(setup, "_unpinned_said", []): dst = Path(d) / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf" @@ -214,7 +214,7 @@ class InstalledModelsNeedNoNetwork(unittest.TestCase): def urlopen(req, timeout=None): raise AssertionError("network used for an installed file: " + req.full_url) - with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.urllib.request, "urlopen", urlopen), \ + with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.netpolicy, "urlopen", urlopen), \ mock.patch.dict(setup.os.environ, {"HF_ENDPOINT": "http://127.0.0.1:9", "STRATA_SOURCE": "auto"}): dst = Path(d) / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf" dst.write_bytes(b"installed by an earlier setup") # no hash in its mark (installed before the pins) @@ -227,7 +227,7 @@ class InstalledModelsNeedNoNetwork(unittest.TestCase): def urlopen(req, timeout=None): raise urllib.error.URLError("no route to host") - with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.urllib.request, "urlopen", urlopen), \ + with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.netpolicy, "urlopen", urlopen), \ mock.patch.object(setup.time, "sleep", lambda s: None), \ mock.patch.dict(setup.os.environ, {"STRATA_SOURCE": "huggingface"}): with self.assertRaises(SystemExit): diff --git a/tools/test_setup_modelscope.py b/tools/test_setup_modelscope.py index 50301d465d..eda345f42a 100644 --- a/tools/test_setup_modelscope.py +++ b/tools/test_setup_modelscope.py @@ -145,7 +145,7 @@ class Download(Base): def test_falls_back_when_modelscope_is_silent(self): calls = [] with mock.patch.object(setup, "reachable", return_value=False), \ - mock.patch.object(setup.urllib.request, "urlopen", + mock.patch.object(setup.netpolicy, "urlopen", side_effect=lambda req, timeout=0: calls.append(req.full_url) or (_ for _ in ()).throw( OSError("offline"))), \ mock.patch.object(setup.time, "sleep"), self.assertRaises(SystemExit): diff --git a/tools/test_setup_pins.py b/tools/test_setup_pins.py index 4b26bcb7ef..2f0cd84443 100644 --- a/tools/test_setup_pins.py +++ b/tools/test_setup_pins.py @@ -102,7 +102,7 @@ class HuggingFacePins(unittest.TestCase): seen.append((req.get_method(), req.full_url)) raise not_found(req.full_url) - with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.urllib.request, "urlopen", urlopen), mock.patch.dict(setup.os.environ, {"STRATA_SOURCE": "huggingface"}): + with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.netpolicy, "urlopen", urlopen), mock.patch.dict(setup.os.environ, {"STRATA_SOURCE": "huggingface"}): setup.os.environ.pop("STRATA_ALLOW_UNPINNED", None) dst = Path(d) / "m.gguf" with self.assertRaises(SystemExit): @@ -122,7 +122,7 @@ class HuggingFacePins(unittest.TestCase): return Response(b"model bytes", status=200) # the pinned Hugging Face path itself (setup's --source huggingface; auto may pick ModelScope) - with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.urllib.request, "urlopen", urlopen), mock.patch.dict(setup.os.environ, {"STRATA_SOURCE": "huggingface", "STRATA_ALLOW_UNPINNED": "1"}), mock.patch.object(setup, "_unpinned_said", []): + with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.netpolicy, "urlopen", urlopen), mock.patch.dict(setup.os.environ, {"STRATA_SOURCE": "huggingface", "STRATA_ALLOW_UNPINNED": "1"}), mock.patch.object(setup, "_unpinned_said", []): dst = Path(d) / "m.gguf" _, out = quiet(setup.download, setup.FAMILIES["qwen"]["mmproj_hf"] + "m.gguf", dst) self.assertEqual(dst.read_bytes(), b"model bytes") @@ -142,7 +142,7 @@ class HuggingFacePins(unittest.TestCase): return Response(b"model bytes") raise urllib.error.HTTPError(req.full_url, 416, "Range Not Satisfiable", {}, None) - with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.urllib.request, "urlopen", urlopen), \ + with tempfile.TemporaryDirectory() as d, mock.patch.object(setup.netpolicy, "urlopen", urlopen), \ mock.patch.object(setup.time, "sleep", lambda s: None): dst = Path(d) / "m.gguf" dst.with_name("m.gguf.part").write_bytes(b"model bytes") @@ -265,7 +265,7 @@ class Engine(unittest.TestCase): raise not_found(req.full_url) return Response() - with mock.patch.object(setup.urllib.request, "urlopen", urlopen), \ + with mock.patch.object(setup.netpolicy, "urlopen", urlopen), \ mock.patch.object(setup, "download", self.fake_download(got, wrote)), \ mock.patch.object(setup, "engine_digest", self.fake_digest(wrote)): eng, out = quiet(setup.get_prebuilt, setup.PREBUILT_URL, {"arch": 89}, "gpu") @@ -304,7 +304,7 @@ class Engine(unittest.TestCase): z.writestr(setup.EXE, b"engine") setup.mark(dst) - with mock.patch.object(setup.urllib.request, "urlopen", lambda req, timeout=None: Response()), \ + with mock.patch.object(setup.netpolicy, "urlopen", lambda req, timeout=None: Response()), \ mock.patch.object(setup, "download", download), \ mock.patch.object(setup, "engine_digest", self.fake_digest(wrote)): eng, _ = quiet(setup.get_prebuilt, setup.PREBUILT_URL, {"arch": 89}, "gpu") @@ -336,7 +336,7 @@ class Engine(unittest.TestCase): def urlopen(req, timeout=None): raise AssertionError("asked the network for an installed engine") - with mock.patch.object(setup.urllib.request, "urlopen", urlopen): + with mock.patch.object(setup.netpolicy, "urlopen", urlopen): eng, out = quiet(setup.get_prebuilt, setup.PREBUILT_URL, {"arch": 89}, "gpu") self.assertEqual(eng, self.root / "engine") self.assertEqual((self.root / "engine" / setup.EXE).read_bytes(), b"old") diff --git a/tools/test_setup_rocm_pins.py b/tools/test_setup_rocm_pins.py index 69f0d4ffa2..e13541f4b5 100644 --- a/tools/test_setup_rocm_pins.py +++ b/tools/test_setup_rocm_pins.py @@ -80,7 +80,7 @@ class RocmPick(unittest.TestCase): def test_unreadable_index_keeps_the_preferred_version(self): self.assertEqual(setup.rocm_pick([], "7.10.0a20251120"), ("7.10.0a20251120", None)) - with mock.patch.object(setup.urllib.request, "urlopen", side_effect=OSError("offline")): + with mock.patch.object(setup.netpolicy, "urlopen", side_effect=OSError("offline")): self.assertEqual(setup.rocm_wanted(setup.ROCM_INDEXES["gfx1030"]), ("7.13.0a20260515", None)) def test_the_index_page_is_read_from_the_rocm_folder(self): @@ -94,13 +94,13 @@ class RocmPick(unittest.TestCase): def fake(req, timeout=0): seen.append(req.full_url) return Resp() - with mock.patch.object(setup.urllib.request, "urlopen", fake): + with mock.patch.object(setup.netpolicy, "urlopen", fake): self.assertEqual(setup.rocm_wanted(setup.ROCM_INDEXES["gfx1030"])[0], "7.13.0a20260515") self.assertEqual(seen, ["https://rocm.nightlies.amd.com/v2/gfx103X-all/rocm/"]) def test_the_override_is_exact_and_not_looked_up(self): with mock.patch.object(setup, "ROCM_VERSION_OVERRIDE", "7.12.0a20260311"), \ - mock.patch.object(setup.urllib.request, "urlopen", side_effect=AssertionError("no lookup")): + mock.patch.object(setup.netpolicy, "urlopen", side_effect=AssertionError("no lookup")): self.assertEqual(setup.rocm_wanted(setup.ROCM_INDEXES["gfx1030"]), ("7.12.0a20260311", None)) with mock.patch.object(setup, "ROCM_VERSION_OVERRIDE", "7.10.0a20251120"): # forced, but still warned about version, note = setup.rocm_wanted(setup.ROCM_INDEXES["gfx1151"]) diff --git a/tools/test_setup_strix_halo.py b/tools/test_setup_strix_halo.py index dc2469872c..f4942a1bcd 100644 --- a/tools/test_setup_strix_halo.py +++ b/tools/test_setup_strix_halo.py @@ -404,7 +404,7 @@ class WindowsZip(unittest.TestCase): mock.patch.object(setup, "say", lambda *a, **k: None), mock.patch.object(setup, "ok", lambda *a, **k: None), mock.patch.object(setup, "download", self.fake_download), mock.patch.object(setup, "engine_digest", self.fake_digest), - mock.patch.object(setup.urllib.request, "urlopen", lambda *a, **k: io.BytesIO(b"")), + mock.patch.object(setup.netpolicy, "urlopen", lambda *a, **k: io.BytesIO(b"")), mock.patch.object(setup, "hip_runtime_beside_exe", lambda eng: None)): p.start() self.addCleanup(p.stop)