diff --git a/docs/DETAILS.md b/docs/DETAILS.md index cc888218..0a55c8ec 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -907,7 +907,8 @@ print(r.choices[0].message.content) from going to sleep while at least one request is running or waiting (Windows' `SetThreadExecutionState` with `ES_SYSTEM_REQUIRED`; the screen may still turn off), and gives the normal sleep rules back when the server is idle and when it exits. Default off. On Linux and macOS it does nothing (one line at startup says so). -- **A hard thinking budget (opt-in).** `"reasoning_budget_tokens": N` in a request (OpenAI or Anthropic) caps the +- **A hard thinking budget (opt-in).** `"reasoning_budget_tokens": N` (or llama.cpp's `"thinking_budget_tokens": N`, which + clients written for llama-server send) in a request (OpenAI or Anthropic) caps the thinking at N tokens: when it gets there the server ends it with a short wrap-up line and ``, and the model answers from there (the engine continues from what it already holds, so nothing is read again). The wrap-up is part of the thinking the client sees and counts as output tokens. `"reasoning_budget_tokens": N` in diff --git a/docs/MAC.md b/docs/MAC.md index 19483ab6..d21131e8 100644 --- a/docs/MAC.md +++ b/docs/MAC.md @@ -56,7 +56,7 @@ What the first run does (each step is skipped when it is already done): 1. **Python.** It needs Python 3.10 or newer, but macOS ships 3.9. If that is all your Mac has, `setup.sh` downloads a standalone Python 3.12 (25 MB, pinned by SHA-256) into `.python`. No sudo, no Homebrew. 2. **Checks your Mac:** the chip, the memory, the macOS version, the Command Line Tools and the free disk. -3. **Python packages** into `.venv`. CMake and Ninja come from pip. +3. **Python packages** into `.venv`. CMake and Ninja come from pip too, installed just before the build in step 4. 4. **Builds the engine** (`build-metal/strata`). It uses Apple's metal-cpp headers (pinned by SHA-256) and llama.cpp's ggml at the commit the PC build pins. 5. **Downloads the model.** The download resumes if interrupted. `--gguf-dir` uses files you already have. 6. **Prepares the model:** the pack (seconds), and the MTP draft layer (about 5 GB of the original checkpoint). On a Mac that streams: the experts' copy instead of the draft layer (about 3 minutes on the M4, checked byte for byte against the model file). diff --git a/metal/setup_mac.py b/metal/setup_mac.py index d7ebb96f..834de130 100644 --- a/metal/setup_mac.py +++ b/metal/setup_mac.py @@ -6,7 +6,7 @@ What it does, each step skipped when it is already done: 1. checks the Mac: Apple Silicon, the chip, unified memory, macOS version, the Command Line Tools, free disk 2. recommends a model by memory (recommend, never force: an explicit --model is kept, with what it risks) - 3. installs the Python packages into .venv (cmake and ninja come from pip: no Homebrew, no sudo) + 3. installs the Python packages into .venv (cmake and ninja come from pip, just before step 4: no Homebrew, no sudo) 4. builds the Metal engine from source: metal-cpp (Apple's headers) and llama.cpp's ggml at the pinned commit 5. downloads the model (setup.py's downloader: resumable, the pinned revision) 6. prepares the model: the native pack (tools/iq_pack.py) and the MTP draft layer (tools/mtp_fetch.py, mtp_pack.py) @@ -127,6 +127,7 @@ def build_engine(llama: Path, jobs: int | None = None) -> Path: S.ok(f"Metal engine: {EXE} (built for this source)") return EXE mcpp = metal_cpp() + S.ensure_build_tools() # cmake and ninja are in requirements-build.txt, not requirements.txt (#3403) S.say(" Building the Metal engine from source (5-15 minutes the first time) ...") BUILD_DIR.mkdir(exist_ok=True) log = BUILD_DIR / "build.log" @@ -170,6 +171,7 @@ def build_vision(llama: Path) -> Path: return VISION_EXE except (OSError, ValueError): pass + S.ensure_build_tools() S.say(" Building the image encoder (1-3 minutes) ...") env = dict(os.environ, PATH=str(Path(sys.executable).parent) + os.pathsep + os.environ.get("PATH", "")) log = ROOT / "build-vision.log" @@ -416,9 +418,9 @@ def main(argv=None) -> int: if free < need: S.warn(f"about {need:.0f} GB are needed on the disk ({free:.0f} GB free): kept as you chose; it may run out") - # ---- 3. Python packages (cmake and ninja among them: the engine build's tools) + # ---- 3. Python packages (cmake and ninja come with the build in step 4, from requirements-build.txt) S.step(3, "Python packages") - S.pip_install(S.requirement_lines() if S.REQUIREMENTS.exists() else S.PY_PACKAGES, "numpy, jinja2, ..., cmake, ninja") + S.pip_install(S.requirement_lines() if S.REQUIREMENTS.exists() else S.PY_PACKAGES, "numpy, jinja2, ...") # ---- 4. the engine S.step(4, "the Strata engine (Metal)") diff --git a/serve/server.py b/serve/server.py index 83a5fb51..82a04856 100644 --- a/serve/server.py +++ b/serve/server.py @@ -1015,8 +1015,15 @@ class StrataEngine: pin["preexec_fn"] = lambda: os.sched_setaffinity(0, cpus) end_leftover_engines(exe) # one an earlier run lost still holds the GPU and the memory spawned_at = time.monotonic() - self.proc = popen("the Strata engine", [exe, "--serve", *args], cwd=cwd, stdin=subprocess.PIPE, - stdout=subprocess.PIPE, stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env, **pin) + try: + self.proc = popen("the Strata engine", [exe, "--serve", *args], cwd=cwd, stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=self.log, text=True, encoding="utf-8", bufsize=1, env=env, + **pin) + except OSError: # nothing started: the narrator stops, the log handle goes back + loading.set() + if log: + self.log.close() + raise # the READY read has a timeout (#1317): the lines come from a thread, up to READY, so the rest of the stream # stays for _pump (one reader at a time) ready_q: queue.Queue = queue.Queue() @@ -2560,6 +2567,13 @@ class Vision: args += ["--min-tokens", str(cfg["min_tokens"])] return args + def _ensure_dir(self): + """#3370: a temp cleaner (Windows Storage Sense) removes the empty work folder while the encoder is unloaded; the next + start then failed with WinError 267 for as long as the server lived. Make it again; pictures cached in it are gone.""" + if not self.dir.is_dir(): + self.dir.mkdir(parents=True, exist_ok=True) + self.cache.clear() + def _start(self): """Start the reader. When a GPU reader that has a CPU reader to fall back on does not start (the GPU runtime does not load, the card is not in its build, the card is busy), the CPU reader is started instead, for good, with one log line @@ -2577,6 +2591,7 @@ class Vision: def _start_reader(self): args, log, env = self.spawn + self._ensure_dir() # cwd is the encoder's directory: the ENC lines name the files relative to it (#480: no space in the line) self.proc = popen("the image encoder", args, role="vision", stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=log or subprocess.DEVNULL, text=True, encoding="utf-8", bufsize=1, env=env, @@ -2739,6 +2754,7 @@ class Vision: data = self.normalize(source if isinstance(source, bytes) else self.load(source)) key = hashlib.sha256(data).hexdigest()[:32] with self.lock: + self._ensure_dir() if key in self.cache: self.cache[key] = self.cache.pop(key) # most recently used last return self.cache[key] @@ -3776,10 +3792,13 @@ class Service: return int(getattr(self.engine, "max_context", 0) or getattr(self.engine, "known_ctx", 0) or 0) def reasoning_budget(self, req) -> int | None: - """#123: the most tokens this request may think, or None: the request's `reasoning_budget_tokens`, else the - config's. 0 (or less) means no budget, so a request can turn a configured one off. ValueError (a 400) for - anything that is not a whole number.""" - value = (req or {}).get("reasoning_budget_tokens") if isinstance(req, dict) else None + """#123: the most tokens this request may think, or None: the request's `reasoning_budget_tokens` (or, as + llama.cpp reads it, `thinking_budget_tokens`), else the config's. 0 (or less) means no budget, so a request can + turn a configured one off. ValueError (a 400) for anything that is not a whole number.""" + req = req if isinstance(req, dict) else {} + value = req.get("reasoning_budget_tokens") + if value is None: # a null does not hide the other name + value = req.get("thinking_budget_tokens") if value is None: value = self.reasoning_budget_tokens if isinstance(value, float) and value.is_integer(): @@ -3951,9 +3970,13 @@ class Service: "(a minute or two) ...", flush=True) try: self.engine.restart() - except Exception: + except Exception as e: if vision_started: self.vision.unload() + # the program could not be started at all (missing, not executable, or blocked by Windows - #735): the + # request path answers EngineDied with a 503, but takes a bare OSError for a client that went away (#2496) + if isinstance(e, OSError): + raise EngineDied(f"the engine could not be started: {e}") from e raise print("[strata] the engine is running again", flush=True) if self.restore_after_load: # an image job unloaded it: its conversation comes back @@ -5599,14 +5622,14 @@ def anthropic_events(svc: Service, req: dict, ids, thinking, tools, max_new, can stop = "stop_sequence" if x.get("stop_sequence") is not None else \ "tool_use" if used_tool and streamed <= finished and x["finish"] == "stop" else \ {"stop": "end_turn", "length": "max_tokens", "cancel": "end_turn"}[x["finish"]] - # the final counts, Anthropic's way: input_tokens leaves out what the conversation cache already held, - # which is cache_read_input_tokens (message_start could only say the whole prompt). At least the last - # prompt token is always read, and Claude Code takes an input_tokens of 0 as "not given" and keeps - # message_start's whole prompt beside cache_read_input_tokens: the prompt counted twice (#1013) + # the final counts (message_start could only say the whole prompt): what was read now stays for the next + # request, a cache write; input_tokens keeps the last token, as 0 makes Claude Code count the prompt twice (#1013) reused = max(0, min(x.get("reused") or 0, len(ids) - 1)) + read_now = len(ids) - reused yield "message_delta", {"type": "message_delta", "delta": {"stop_reason": stop, "stop_sequence": x.get("stop_sequence")}, - "usage": {"input_tokens": len(ids) - reused, "cache_read_input_tokens": reused, + "usage": {"input_tokens": 1, "cache_creation_input_tokens": read_now - 1, + "cache_read_input_tokens": reused, "output_tokens": x["completion_tokens"]}} yield "message_stop", {"type": "message_stop"} diff --git a/serve/test_parallel_yield.py b/serve/test_parallel_yield.py index b807ee7c..eeabe383 100644 --- a/serve/test_parallel_yield.py +++ b/serve/test_parallel_yield.py @@ -240,7 +240,7 @@ class ParallelServiceYield(tp.FakeEngineCase): prompt = self.svc.history[[h["output_tokens"] for h in self.svc.history].index( max(h["output_tokens"] for h in self.svc.history))]["prompt_total"] self.assertGreaterEqual(u["input_tokens"], 1, u) - self.assertEqual(u["input_tokens"] + u["cache_read_input_tokens"], prompt, u) + self.assertEqual(u["input_tokens"] + u["cache_creation_input_tokens"] + u["cache_read_input_tokens"], prompt, u) self.assertEqual(u["cache_read_input_tokens"], 3, u) # the first read's reuse, not the continuation's def test_a_slot_request_ended_by_its_stop_token_reports_the_slot_leg(self): diff --git a/serve/test_ready_timeout.py b/serve/test_ready_timeout.py index 78ef33d0..009d9ecc 100644 --- a/serve/test_ready_timeout.py +++ b/serve/test_ready_timeout.py @@ -104,5 +104,40 @@ class ReadyTimeout(unittest.TestCase): self.assertFalse(svc.engine.starting) +class SpawnFailure(unittest.TestCase): + """The engine program cannot be started at all (missing, not executable, or blocked by Windows - #735): the + request that was loading it gets a 503 with the reason, not a dropped connection.""" + BODIES = {'/v1/chat/completions': {'messages': [{'role': 'user', 'content': 'hi'}], 'max_tokens': 8}, + '/v1/messages': {'model': 'strata', 'max_tokens': 8, 'messages': [{'role': 'user', 'content': 'hi'}]}, + '/v1/responses': {'input': 'hi', 'max_output_tokens': 8}} + + def test_missing_engine_answers_503_and_leaves_nothing_running(self): + tmp = tempfile.TemporaryDirectory(); self.addCleanup(tmp.cleanup) + root = Path(tmp.name) + eng = StrataEngine(str(root / 'no-such-engine'), [], log=str(root / 'engine.log'), lazy=True) + svc = Service(eng, ByteTokenizer(), ChatTemplate(Path(__file__).parent / 'chat_template.jinja')) + httpd = serve(svc, port=0) + self.addCleanup(httpd.shutdown); self.addCleanup(httpd.server_close) + base = f'http://127.0.0.1:{httpd.server_address[1]}' + before = set(threading.enumerate()) + cases = list(self.BODIES.items()) + [('/v1/chat/completions', + {**self.BODIES['/v1/chat/completions'], 'stream': True})] + for path, body in cases: + with self.subTest(path=path, stream=body.get('stream', False)): + req = urllib.request.Request(base + path, data=json.dumps(body).encode(), + headers={'Content-Type': 'application/json'}) + with self.assertRaises(urllib.error.HTTPError) as cm: + urllib.request.urlopen(req, timeout=30) + self.assertEqual(cm.exception.code, 503) + self.assertIn('the engine could not be started', cm.exception.read().decode()) + self.assertTrue(eng.log.closed) # our handle on the engine log is given back + # the start narrator ("still starting ... please wait") ends with the failed start + deadline = time.monotonic() + 5 + while (narrators := [t for t in set(threading.enumerate()) - before if '(narrate_start)' in t.name]) \ + and time.monotonic() < deadline: + time.sleep(0.1) + self.assertEqual(narrators, []) + + if __name__ == '__main__': unittest.main() diff --git a/serve/test_request_accounting.py b/serve/test_request_accounting.py index 145fdd56..55ff0540 100644 --- a/serve/test_request_accounting.py +++ b/serve/test_request_accounting.py @@ -148,14 +148,14 @@ class RequestAccounting(unittest.TestCase): usage = self.chat("/v1/messages")["usage"] self.assertEqual(self.engine.attempts, 2) self.assertEqual(usage["cache_read_input_tokens"], 5) - self.assertEqual(usage["input_tokens"], len(self.engine.prompts[0]) - 5) + self.assertEqual(usage["input_tokens"] + usage["cache_creation_input_tokens"], len(self.engine.prompts[0]) - 5) def test_anthropic_stream_classifies_only_original_input_as_cached(self): events = self.chat("/v1/messages", stream=True) usage = next(event["usage"] for event in events if event["type"] == "message_delta") self.assertEqual(self.engine.attempts, 2) self.assertEqual(usage["cache_read_input_tokens"], 5) - self.assertEqual(usage["input_tokens"], len(self.engine.prompts[0]) - 5) + self.assertEqual(usage["input_tokens"] + usage["cache_creation_input_tokens"], len(self.engine.prompts[0]) - 5) def test_single_segment_keeps_its_own_usage_and_timings(self): response = self.chat(budget=10000) diff --git a/serve/test_server.py b/serve/test_server.py index 961236d3..8bbe6e65 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -74,7 +74,8 @@ class MaxTokens(unittest.TestCase): return s, b, u.get("prompt_tokens"), u.get("completion_tokens") s, b = self.post("/v1/messages", {"model": "m", "messages": msgs, **budget}) u = b.get("usage", {}) - return s, b, u.get("input_tokens"), u.get("output_tokens") + prompt = sum(u.get(k) or 0 for k in ("input_tokens", "cache_creation_input_tokens", "cache_read_input_tokens")) + return s, b, prompt if u else None, u.get("output_tokens") def test_anthropic_thinks_only_when_asked(self): # #278: Anthropic's thinking is opt-in; "thinking", an effort or a reasoning_budget_tokens (#123) asks for it @@ -3712,7 +3713,9 @@ class UsageAndStatus(unittest.TestCase): def test_anthropic(self): u = self.chat("/v1/messages")["usage"] self.assertEqual(u["cache_read_input_tokens"], ClockedEngine.REUSED) - self.assertEqual(u["input_tokens"] + u["cache_read_input_tokens"], len(self.engine.last_prompt)) + self.assertEqual(u["input_tokens"], 1) # what was read now is kept: written to the cache + self.assertEqual(u["input_tokens"] + u["cache_creation_input_tokens"] + u["cache_read_input_tokens"], + len(self.engine.last_prompt)) self.assertGreater(u["output_tokens"], 0) def test_v1_status(self): @@ -4128,6 +4131,17 @@ class ThinkingBudget(unittest.TestCase): self.assertEqual(b["usage"]["completion_tokens"], 20 + len(extra) + len(ThinkingEngine.ANSWER) + 1) self.assertEqual(b["usage"]["prompt_tokens"], len(first)) + def test_llama_cpp_thinking_budget_tokens_is_the_same_budget(self): + """llama.cpp's name (pi-llama-cpp sends it): the same wrap-up; reasoning_budget_tokens wins when both are set.""" + from serve.server import REASONING_WRAP_UP + wrap = REASONING_WRAP_UP.split("")[0] + code, b = self.openai(thinking_budget_tokens=20) + self.assertEqual(code, 200, b) + self.assertEqual(b["choices"][0]["message"]["reasoning_content"], ThinkingEngine.THOUGHT[:20] + wrap) + code, b = self.openai(reasoning_budget_tokens=10, thinking_budget_tokens=20) + self.assertEqual(code, 200, b) + self.assertEqual(b["choices"][0]["message"]["reasoning_content"], ThinkingEngine.THOUGHT[:10] + wrap) + def test_a_stop_string_is_found_in_the_answer_after_the_wrap_up(self): """#454: the continuation after the thinking budget is cut at a stop string too.""" code, b = self.openai(reasoning_budget_tokens=20, stop=["answer is"]) diff --git a/serve/test_vision_workdir.py b/serve/test_vision_workdir.py new file mode 100644 index 00000000..2bba189c --- /dev/null +++ b/serve/test_vision_workdir.py @@ -0,0 +1,46 @@ +"""#3370: the encoder's work folder is made again when a temp cleaner removed it while the encoder was unloaded. + + python -m serve.test_vision_workdir +""" +import io +import tempfile +import unittest +from pathlib import Path +from types import SimpleNamespace +from unittest import mock + +import serve.server as server + + +class WorkDir(unittest.TestCase): + def test_start_makes_a_removed_work_folder_again(self): + proc = SimpleNamespace(stdin=io.StringIO(), stdout=io.StringIO("READY\n"), kill=lambda: None, + wait=lambda timeout=None: 0, poll=lambda: None) + with tempfile.TemporaryDirectory() as tmp: + v = server.Vision.__new__(server.Vision) + v.spawn = (["strata-vision"], None, None) + v.dir = Path(tmp) / "strata-vision-gone" + v.cache = {"k": (v.dir / "k.sve", 4)} + seen = [] + + def fake_popen(*a, **k): + seen.append(Path(k["cwd"]).is_dir()) # the real popen raises WinError 267 when it is not + return proc + + with mock.patch.object(server, "popen", fake_popen): + v._start() + self.assertEqual(seen, [True]) + self.assertTrue(v.dir.is_dir()) + self.assertEqual(v.cache, {}) # its cached embeddings went with the folder + + def test_an_existing_folder_and_its_cache_are_left_alone(self): + with tempfile.TemporaryDirectory() as tmp: + v = server.Vision.__new__(server.Vision) + v.dir = Path(tmp) + v.cache = {"k": (v.dir / "k.sve", 4)} + v._ensure_dir() + self.assertEqual(len(v.cache), 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/serve/web/app.css b/serve/web/app.css index 0c75e60e..66d96acd 100644 --- a/serve/web/app.css +++ b/serve/web/app.css @@ -4,7 +4,7 @@ html, body { height: 100%; } body { display: flex; flex-direction: column; overflow: hidden; } main { flex: 1; min-height: 0; display: flex; } -.view { flex: 1; min-height: 0; display: flex; flex-direction: column; } +.view { flex: 1; min-height: 0; min-width: 0; display: flex; flex-direction: column; } .view[hidden] { display: none; } .muted { color: var(--st-ink-muted); } .small { font-size: var(--st-fs-xs); } @@ -53,8 +53,9 @@ main { flex: 1; min-height: 0; display: flex; } font-size: var(--st-fs-md); } /* MCP tool calls inside an answer: one compact collapsible block per call */ .st-bubble .tool-call { margin: var(--st-s-3) 0; } -.tool-call > summary { min-width: 0; padding: 8px 12px; } -.tool-call__name { font: 500 var(--st-fs-sm)/1.2 var(--st-font-mono); color: var(--st-ink); white-space: nowrap; } +.tool-call > summary { min-width: 0; padding: 8px 12px; overflow: hidden; } +.tool-call__name { font: 500 var(--st-fs-sm)/1.2 var(--st-font-mono); color: var(--st-ink); white-space: nowrap; + min-width: 0; overflow: hidden; text-overflow: ellipsis; } .tool-call__preview { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--st-fs-xs); } .tool-call .st-badge, .tool-call summary .small { flex: none; } .tool-call[data-state="error"] { border-color: color-mix(in srgb, var(--st-danger) 35%, var(--st-line)); } diff --git a/setup.py b/setup.py index 0cce69cc..65f123ff 100644 --- a/setup.py +++ b/setup.py @@ -64,6 +64,7 @@ from pathlib import Path from strata_control import acquisition from strata_control import draft_layer +from strata_control.discovery import in_trash from strata_control import user_args ROOT = Path(__file__).resolve().parent @@ -1738,7 +1739,7 @@ def recommend_remote_expert_opt(cfg: dict, off: bool = False) -> None: plain helper path). The engine uses it only with a helper cache; a layer split runs as before. A recommendation: `off` (setup's --no-remote-expert-opt) or "remote_expert_opt": false in the config keeps it out, and a single-GPU config is not touched.""" - if not isinstance(cfg.get("gpu"), list) or len(cfg["gpu"]) < 2: + if len(gpu_sel(cfg.get("gpu"))) < 2: return args = cfg.setdefault("args", []) if off or cfg.get("remote_expert_opt") is False: @@ -4910,8 +4911,9 @@ def install_build_tools(gpu, yes): return nvcc, find_vcvars(cuda_v) if WIN else None -def cmake_build(src, bdir, target, defs, vcvars, bat_name): - acquisition.require("a compile (cmake)") +def ensure_build_tools(): + """cmake and ninja for a local compile, installed from requirements-build.txt when missing (#3403: the Mac setup + compiles without cmake_build(), so it calls this too). Returns (cmake, ninja).""" # The ready-made engine path never calls this function. Keep build helpers out of # the normal serving environment, and use already installed tools offline. build_packages = requirement_lines(BUILD_REQUIREMENTS) if BUILD_REQUIREMENTS.exists() else BUILD_PACKAGES @@ -4921,6 +4923,12 @@ def cmake_build(src, bdir, target, defs, vcvars, bat_name): cmake, ninja = find_tool("cmake"), find_tool("ninja") if cmake is None or ninja is None: fail("cmake / ninja not found after installing them", "run: .venv python -m pip install -r requirements-build.txt") + return cmake, ninja + + +def cmake_build(src, bdir, target, defs, vcvars, bat_name): + acquisition.require("a compile (cmake)") + cmake, ninja = ensure_build_tools() conf = [cmake, "-G", "Ninja", f"-DCMAKE_MAKE_PROGRAM={ninja}", "-S", str(src), "-B", str(bdir), "-DCMAKE_BUILD_TYPE=Release", *defs] build = [cmake, "--build", str(bdir), "--target", target, "-j", str(max(2, (os.cpu_count() or 4) // 2))] @@ -5382,7 +5390,7 @@ def has_data(folder: Path) -> bool: def other_installs(settings: dict) -> list: """Strata folders besides this one that may hold model files: the ones this user ran before, and Strata* folders next to this one (a zip unpacked again lands in e.g. `Strata-main (1)\\Strata-main`).""" - cands = [Path(p) for p in settings.get("installs", [])] + cands = [Path(p) for p in settings.get("installs", []) if not in_trash(p)] for base in dict.fromkeys(() if app_settings_file() else (home().parent, home().parent.parent)): try: for d in base.iterdir(): @@ -5559,7 +5567,8 @@ def data_folder(requested: str | None, move: bool = False, yes: bool = True, set warn(f"some model files are still in {folder} (in use, or already in {dest})") else: ok(f"model files from {folder} moved to {dest} (a new copy of Strata finds them there)") - installs = [str(home())] + [p for p in settings.get("installs", []) if p != str(home()) and Path(p).is_dir()] + installs = [str(home())] + [p for p in settings.get("installs", []) + if p != str(home()) and Path(p).is_dir() and not in_trash(p)] save_settings({**settings, "data_dir": str(dest), "installs": installs[:20]}) return dest, elsewhere @@ -5983,11 +5992,29 @@ def hip_config_cards(sel) -> list[dict]: return cards +def gpu_sel(value) -> list: + """A config's "gpu" as a list of card numbers: 0, [0, 2] or the string form "0,2" (which serve splits + the same way). [] when it names none. Without this, a string "0,1" reached gpu_info() whole and + calibrate died with "there is no GPU 0,1" on a dual-GPU config.""" + if value is None or value == "": + return [] + items = value if isinstance(value, (list, tuple)) else str(value).split(",") + sel = [] + for x in items: + x = str(x).strip() + if x == "": + continue + sel.append(int(x) if x.isdigit() else x) + return sel + + def hardware_key(cfg: dict) -> str: """What a calibration is valid for: this GPU, CPU and RAM, and the model with its context and images setting (the context's KV cache and the image encoder take VRAM from the expert cache). #566: a HIP config's cards are AMD's (hip_config_cards) - nvidia-smi's list named them "?" (or another card with that number) before.""" sel = cfg.get("gpu") + if isinstance(sel, str): + sel = gpu_sel(sel) if cfg.get("backend") == "hip": gl = hip_config_cards(sel) else: diff --git a/src/qwen35/q36_engine.cu b/src/qwen35/q36_engine.cu index b0d7e75c..03660de4 100644 --- a/src/qwen35/q36_engine.cu +++ b/src/qwen35/q36_engine.cu @@ -1652,11 +1652,14 @@ struct Engine { std::memcpy(t, u, sizeof(u)); } unsigned ds_a, ds_b; + const __half t0h = __float2half(t[0]); // host side: __half_as_ushort is __device__ only + unsigned short t0bits; + std::memcpy(&t0bits, &t0h, sizeof(t0bits)); std::memcpy(&ds_a, &a[o], 4); std::memcpy(&ds_b, &b[o], 4); std::fprintf(stderr, "VDEBUG block %zu: ds new %08x old %08x, qs bytes %s, cpu butterfly sum %.9g (half %04x)\n", blk, ds_a, ds_b, std::memcmp(&a[o + 4], &b[o + 4], 32) == 0 ? "equal" : "DIFFER", (double) t[0], - (unsigned) __half_as_ushort(__float2half(t[0]))); + (unsigned) t0bits); break; } } diff --git a/strata_cli/launch/runner.py b/strata_cli/launch/runner.py index 3a8b7071..44d1c653 100644 --- a/strata_cli/launch/runner.py +++ b/strata_cli/launch/runner.py @@ -142,6 +142,8 @@ def files_present(cfg: dict) -> list[str]: missing.append(tok) for flag in ("--pack", "--mtp"): args = [str(a) for a in cfg.get("args") or []] + if flag == "--mtp" and flag in args and args.index(flag) + 1 < len(args) and args[args.index(flag) + 1].isdigit(): + continue # Qwen3.6: a number is the draft depth, not a folder (#3298) if flag in args and args.index(flag) + 1 < len(args) and not Path(args[args.index(flag) + 1]).exists(): missing.append(args[args.index(flag) + 1]) vision = cfg.get("vision") diff --git a/strata_control/calibration.py b/strata_control/calibration.py index a020f2f7..b158f741 100644 --- a/strata_control/calibration.py +++ b/strata_control/calibration.py @@ -290,8 +290,10 @@ def _measure_locked(ref: str, path: Path, profile: dict | None, revision: str | _exclusive_preflight(cfg, profile) if output.exists() or output.is_symlink(): raise ProfileError("calibration report path already exists", 2) + if not output.parent.is_dir(): # before the 19 minute sweep, not after it (#3187) + raise ProfileError("report output directory does not exist", 5) identity = _identity(path, cfg, profile, revision) - cal = _full_folder("tools.calibrate") + cal =_full_folder("tools.calibrate") execute = runner or cal.run runner_cfg = _runtime_cfg(cfg, profile) runner_cfg["exe"] = str(_resolved(cfg["exe"], cfg, path)) diff --git a/strata_control/discovery.py b/strata_control/discovery.py index 6280185c..96443808 100644 --- a/strata_control/discovery.py +++ b/strata_control/discovery.py @@ -96,13 +96,26 @@ def _read_json(path: Path) -> dict: return data if isinstance(data, dict) else {} +def in_trash(path: str | os.PathLike) -> bool: + """#3410: True when ``path`` is inside a Trash / Recycle Bin folder (a Strata folder that was deleted with the file manager + is still a folder there, and was remembered as an install): ~/.local/share/Trash/files/.., /.Trash-1000/.., ~/.Trash/.., + $RECYCLE.BIN\\..""" + parts = [x.lower() for x in Path(path).parts] + for i, x in enumerate(parts): + if x in (".trash", "$recycle.bin", "recycler", "$recycle.bin.old") or x.startswith(".trash-"): + return True + if x == "trash" and i + 1 < len(parts) and parts[i + 1] in ("files", "info", "expunged"): + return True # the XDG Trash: ~/.local/share/Trash/files + return False + + def _installs_in(settings: dict) -> list[Path]: items = settings.get("installs") found: list[Path] = [] for raw in (items if isinstance(items, list) else [])[:20]: if isinstance(raw, str) and raw: p = Path(raw).expanduser() - if p.is_absolute() and p not in found: + if p.is_absolute() and p not in found and not in_trash(p): found.append(p) return found diff --git a/strata_control/doctor.py b/strata_control/doctor.py index 3691febb..610b505d 100644 --- a/strata_control/doctor.py +++ b/strata_control/doctor.py @@ -192,6 +192,8 @@ def inspect(config_path: Path | None, *, profile_id: str | None = None, live: bo "required": True, "reason": "missing argument value"}) continue raw = args[index + 1] + if arg == "--mtp" and str(raw).isdigit(): + continue # Qwen3.6: --mtp 2 is the draft depth, not a folder (#3298) if kind == "file_with_scale": candidate, separator, scale = raw.rpartition(":") if separator: diff --git a/strata_control/private_files.py b/strata_control/private_files.py index 0a37309a..d04c74a5 100644 --- a/strata_control/private_files.py +++ b/strata_control/private_files.py @@ -95,6 +95,16 @@ def current_user_sid() -> str: return _sid_cache +def _same_sid(sddl_trustee: str, sid: str) -> bool: + """True when an SDDL trustee names ``sid``. SDDL prints well-known accounts as two-letter aliases (the built-in + Administrator, RID 500, is ``LA``), so an alias is turned into its string SID before the compare (#3302).""" + if sddl_trustee == sid: + return True + if not WINDOWS: + return False + return _string_sid(sddl_trustee) == sid.upper() + + def restrict_to_current_user(path: str | os.PathLike, *, directory: bool | None = None) -> None: """Make ``path`` readable and writable by the current user only. @@ -165,16 +175,15 @@ def is_private(path: str | os.PathLike) -> bool: """ if not WINDOWS: return not (os.lstat(path).st_mode & 0o077) + if not volume_has_acls(path): + return True # FAT / exFAT: there are no permissions to check sddl = dacl_sddl(path) head = sddl.split("(", 1)[0] entries = re.findall(r"\(([^()]*)\)", sddl) if not head.startswith("D:") or "P" not in head[2:] or len(entries) != 1: return False fields = entries[0].split(";") - return len(fields) >= 6 and fields[0] == "A" and fields[5] == current_user_sid() - - -_PRIVILEGED = {"SY", "BA", "OW", "CO", "CG", "S-1-5-18", "S-1-5-32-544", "S-1-3-4"} + return len(fields) >= 6 and fields[0] == "A" and _same_sid(fields[5], current_user_sid()) def is_unshared(path: str | os.PathLike) -> bool: @@ -187,13 +196,105 @@ def is_unshared(path: str | os.PathLike) -> bool: """ if not WINDOWS: return is_private(path) - sddl = dacl_sddl(path) - allowed = _PRIVILEGED | {current_user_sid()} + if not volume_has_acls(path): + return True # FAT / exFAT: there are no permissions to check + return not unshared_offenders(dacl_sddl(path)) + + +def volume_has_acls(path: str | os.PathLike) -> bool: + """False for a drive without file permissions (FAT, exFAT); True for NTFS/ReFS, and when it cannot be told (Windows only).""" + if not WINDOWS: + return True + try: + drive = os.path.splitdrive(os.path.abspath(os.fspath(path)))[0] + if not drive: + return True + flags = wintypes.DWORD() + fn = _kernel.GetVolumeInformationW + fn.argtypes = [wintypes.LPCWSTR, wintypes.LPWSTR, wintypes.DWORD, ctypes.c_void_p, ctypes.c_void_p, + ctypes.POINTER(wintypes.DWORD), wintypes.LPWSTR, wintypes.DWORD] + if not fn(drive.rstrip("\\") + "\\", None, 0, None, None, ctypes.byref(flags), None, 0): + return True + return bool(flags.value & 0x00000008) # FILE_PERSISTENT_ACLS + except (OSError, ValueError): + return True + + +_ACCOUNT_NAMES = {"WD": "Everyone", "BU": "Users", "AU": "Authenticated Users", "IU": "Interactive users", + "NU": "Network users", "AN": "Anonymous", "DU": "Domain Users", "S-1-1-0": "Everyone", + "S-1-5-32-545": "Users", "S-1-5-11": "Authenticated Users", "S-1-5-4": "Interactive users"} + + +def _string_sid(trustee: str) -> str: + """An SDDL trustee (a string SID or a two-letter alias such as LA, BA, SY, WD) as an upper-case string SID; the text itself + when Windows does not know it.""" + if trustee.upper().startswith("S-1-"): + return trustee.upper() + pointer = ctypes.c_void_p() + if not _advapi.ConvertStringSidToSidW(trustee, ctypes.byref(pointer)): + return trustee.upper() + try: + text = wintypes.LPWSTR() + if not _advapi.ConvertSidToStringSidW(pointer.value, ctypes.byref(text)): + return trustee.upper() + try: + return text.value.upper() + finally: + _kernel.LocalFree(ctypes.cast(text, ctypes.c_void_p)) + finally: + _kernel.LocalFree(pointer) + + +def _is_privileged_sid(sid: str) -> bool: + """SYSTEM, the Administrators group, the built-in Administrator account (RID 500, SDDL "LA"), OWNER RIGHTS / CREATOR OWNER / GROUP.""" + return sid in ("S-1-5-18", "S-1-5-32-544", "S-1-3-4", "S-1-3-0", "S-1-3-1") or \ + re.fullmatch(r"S-1-5-21-[0-9-]+-500", sid) is not None + + +def unshared_offenders(sddl: str) -> list[str]: + """The trustees of an SDDL DACL that make the object reachable by someone besides this user, SYSTEM and the administrators: + every allow entry that applies to the object itself, whatever form its account is written in (a string SID or an alias such + as LA). An inherit-only entry (flag IO) is for the children of a folder, not for the folder, and is left out.""" + me = current_user_sid().upper() + out: list[str] = [] for entry in re.findall(r"\(([^()]*)\)", sddl): fields = entry.split(";") - if len(fields) >= 6 and fields[0] in ("A", "OA") and fields[5] not in allowed: - return False - return True + if len(fields) < 6 or fields[0] not in ("A", "OA") or "IO" in re.findall("..", fields[1].upper()): + continue + sid = _string_sid(fields[5]) + if sid == me or _is_privileged_sid(sid) or fields[5].upper() in ("SY", "BA", "OW", "CO", "CG", "LA"): + continue + if fields[5] not in out: + out.append(fields[5]) + return out + + +def account_name(trustee: str) -> str: + """A plain name for an SDDL trustee (Everyone, Users, DOMAIN\\name), or the SID text when it cannot be looked up.""" + plain = _ACCOUNT_NAMES.get(trustee.upper()) or _ACCOUNT_NAMES.get(_string_sid(trustee)) + if plain or not WINDOWS: + return plain or trustee + pointer = ctypes.c_void_p() + if not _advapi.ConvertStringSidToSidW(trustee, ctypes.byref(pointer)): + return trustee + try: + name, domain = ctypes.create_unicode_buffer(256), ctypes.create_unicode_buffer(256) + n, d, use = wintypes.DWORD(256), wintypes.DWORD(256), wintypes.DWORD() + lookup = _advapi.LookupAccountSidW + lookup.argtypes = [wintypes.LPCWSTR, ctypes.c_void_p, wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD), + wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD), ctypes.POINTER(wintypes.DWORD)] + if lookup(None, pointer, name, ctypes.byref(n), domain, ctypes.byref(d), ctypes.byref(use)): + return f"{domain.value}\\{name.value}" if domain.value else name.value + return trustee + finally: + _kernel.LocalFree(pointer) + + +def who_can_reach(path: str | os.PathLike) -> list[str]: + """Plain names of the accounts besides this user, SYSTEM and the administrators that can reach ``path`` (Windows; [] elsewhere).""" + if not WINDOWS: + return [] + return [account_name(t) for t in unshared_offenders(dacl_sddl(path))] # ---------------------------------------------------------------------------------------------- access repair diff --git a/strata_control/runtime.py b/strata_control/runtime.py index c88a9455..da16698f 100644 --- a/strata_control/runtime.py +++ b/strata_control/runtime.py @@ -109,14 +109,67 @@ def runtime_dir() -> Path: raise ProfileError("STRATA_RUNTIME_DIR must be absolute") existed = base.exists() _private_mkdir(base, parents=True, exist_ok=True) - if WINDOWS and not existed: - private_files.restrict_to_current_user(base, directory=True) # no mode bits on NTFS: a protected ACL details = base.lstat() + if WINDOWS and stat.S_ISDIR(details.st_mode): + if not private_files.volume_has_acls(base): # exFAT / FAT: no permissions exist, so there is nothing to check + _warn_no_acls(base) + return base + if not existed: + _make_private(base) # no mode bits on NTFS: a protected ACL + if not _is_private(details, base): + # A folder that was there before (made by an elevated install, an older version, or with the parent's ACL inherited) can + # name other accounts. It is the user's own state folder: take that away instead of stopping the launch, then check again. + _make_private(base) + try: + details = base.lstat() + except OSError: + pass if not stat.S_ISDIR(details.st_mode) or not _is_private(details, base): - raise ProfileError("runtime directory must be owner-only (mode 0700)", 5) + raise ProfileError(_not_private_message(base), 5) return base +def _make_private(base: Path) -> None: + """Windows: a protected ACL naming this user; where that is refused (a folder made by an elevated run), take ownership first.""" + try: + private_files.restrict_to_current_user(base, directory=True) + except OSError: + pass + if _is_private(None, base): # type: ignore[arg-type] - details are not used on Windows + return + try: + private_files.repair_access(base, tree=False) + except OSError: + pass + + +_NO_ACL_WARNED: set[str] = set() + + +def _warn_no_acls(base: Path) -> None: + if str(base) not in _NO_ACL_WARNED: + _NO_ACL_WARNED.add(str(base)) + print(f"[strata] {base} is on a drive that has no file permissions (FAT or exFAT), so other accounts on this PC could " + f"read what Strata keeps there. Use a drive formatted as NTFS if that matters.", file=sys.stderr, flush=True) + + +def _not_private_message(base: Path) -> str: + if WINDOWS: + try: + names = private_files.who_can_reach(base) if base.is_dir() else [] + readable = True + except OSError: + names, readable = [], False + if not readable: + return (f"Strata cannot read the permissions of {base}, the folder where it keeps its running state. Run Strata once as " + f"yourself (not as administrator), or delete that folder: Strata makes a private one again.") + who = ", ".join(names) if names else "other accounts" + return (f"Strata keeps its running state in {base}, and {who} can open that folder. Strata could not change that. " + f"Right-click the folder, choose Properties > Security, and remove those accounts (or delete the folder: Strata " + f"makes a private one again).") + return "runtime directory must be owner-only (mode 0700)" + + def acquire_activity_lease(*, shared: bool) -> int: """Let managed hosts coexist while excluding a local calibration run.""" directory = runtime_dir() diff --git a/tests/terminal/test_calibration.py b/tests/terminal/test_calibration.py index 127463d9..5ebc74ac 100644 --- a/tests/terminal/test_calibration.py +++ b/tests/terminal/test_calibration.py @@ -326,6 +326,13 @@ class CalibrationFlowTests(unittest.TestCase): ["engine.calibrate.rollback", "engine.calibrate.apply", "engine.calibrate.measure"]) + def test_missing_report_folder_is_refused_before_the_sweep(self): + # #3187: the sweep takes ~19 minutes; the folder check must not wait until after it + for output in (self.root / "no-such-dir" / "report.json", self.config / "report.json"): + with self.assertRaisesRegex(profiles.ProfileError, "report output directory does not exist"): + calibration.measure("local", output, exclusive_ack=True, + runner=lambda *_a, **_k: self.fail("the sweep must not start")) + def test_calibration_rechecks_reviewed_digests_inside_operation_lock(self): report_path = self.root / "pinned-calibration.json" with self.assertRaisesRegex(profiles.ProfileError, "source changed after review"): diff --git a/tests/terminal/test_issues_022.py b/tests/terminal/test_issues_022.py new file mode 100644 index 00000000..3385aca8 --- /dev/null +++ b/tests/terminal/test_issues_022.py @@ -0,0 +1,392 @@ +"""Small fixes from the 0.2.2 issue sweep, one test class per issue number.""" + +from __future__ import annotations + +import json +import os +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + + +class Issue3298MtpDepth(unittest.TestCase): + """Qwen3.6 passes `--mtp 2` (a draft depth); it is not a folder.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + + def test_doctor_does_not_look_for_a_folder_named_2(self): + from strata_control import doctor + engine = self.root / "engine" + engine.write_text("x", encoding="utf-8") + engine.chmod(0o700) + tok = self.root / "tok" + tok.mkdir() + for n in ("vocab.json", "merges.txt", "token_type.json"): + (tok / n).write_text("{}", encoding="utf-8") + model = self.root / "m.gguf" + model.write_bytes(b"x") + cfg = self.root / "run.json" + cfg.write_text(json.dumps({"exe": str(engine), "args": ["--native", str(model), "--mtp", "2", "--vision"], + "cwd": str(self.root), "tokenizer": str(tok), "model_name": "q36", "port": 8095}), + encoding="utf-8") + report = doctor.inspect(cfg) + self.assertNotIn("mtp", [c["name"] for c in report["components"]]) + self.assertEqual([c["name"] for c in report["components"] if c["status"] not in ("ok",) + and c.get("required") and c["name"] in ("native", "mtp", "pack")], []) + + def test_doctor_still_checks_an_mtp_folder(self): + from strata_control import doctor + engine = self.root / "engine" + engine.write_text("x", encoding="utf-8") + engine.chmod(0o700) + tok = self.root / "tok" + tok.mkdir() + for n in ("vocab.json", "merges.txt", "token_type.json"): + (tok / n).write_text("{}", encoding="utf-8") + cfg = self.root / "run.json" + cfg.write_text(json.dumps({"exe": str(engine), "args": ["--mtp", str(self.root / "gone")], + "cwd": str(self.root), "tokenizer": str(tok), "model_name": "x", "port": 8095}), + encoding="utf-8") + report = doctor.inspect(cfg) + mtp = [c for c in report["components"] if c["name"] == "mtp"] + self.assertEqual(len(mtp), 1) + self.assertEqual(mtp[0]["status"], "missing") + + def test_launch_files_present_ignores_a_depth_number(self): + from strata_cli.launch.runner import files_present + model = self.root / "m.gguf" + model.write_bytes(b"x") + self.assertEqual(files_present({"args": ["--native", str(model), "--mtp", "2"]}), []) + self.assertEqual(files_present({"args": ["--mtp", str(self.root / "gone")]}), [str(self.root / "gone")]) + + +class Issue3403MacBuildTools(unittest.TestCase): + """The Mac setup compiles without setup.cmake_build(), so cmake and ninja must be installed for it too.""" + + def test_missing_build_tools_are_installed_before_the_mac_compile(self): + from unittest import mock + import setup + sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "metal")) + import setup_mac as M + installed = {"cmake": None, "ninja": None} + + def find(name): + return installed[name] + + def pip(packages, what): + self.assertTrue(all(p.split("==")[0] in ("cmake", "ninja") for p in packages), packages) + for p in packages: + installed[p.split("==")[0]] = "/venv/bin/" + p.split("==")[0] + + with mock.patch.object(setup, "find_tool", side_effect=find), mock.patch.object(setup, "pip_install", side_effect=pip) as pi: + self.assertEqual(setup.ensure_build_tools(), ("/venv/bin/cmake", "/venv/bin/ninja")) + self.assertEqual(pi.call_count, 1) + setup.ensure_build_tools() # present now: nothing more is installed + self.assertEqual(pi.call_count, 1) + + def test_both_mac_builds_ask_for_the_tools_first(self): + import inspect + sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "metal")) + import setup_mac as M + for fn in (M.build_engine, M.build_vision): + self.assertIn("S.ensure_build_tools()", inspect.getsource(fn), fn.__name__) + + +@unittest.skipUnless(sys.platform == "win32", "ACLs are Windows only") +class WindowsRuntimeFolderRefused(unittest.TestCase): + """The owner's fresh Windows PC: `strata launch` stopped with "runtime directory must be owner-only" on a folder that was already + there with another account in its ACL. Fake SDDL strings for each way an ACL can look.""" + + def setUp(self): + from unittest import mock + from strata_control import private_files as pf + self.pf, self.mock = pf, mock + self.me = "S-1-5-21-1-2-3-1001" + patch = mock.patch.object(pf, "current_user_sid", return_value=self.me) + patch.start() + self.addCleanup(patch.stop) + + def offenders(self, sddl): + return self.pf.unshared_offenders(sddl) + + def test_the_usual_acls_are_fine(self): + for sddl in ("D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)", + "D:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;FA;;;S-1-5-21-1-2-3-1001)", + "D:PAI(A;OICI;FA;;;LA)(A;OICI;FA;;;SY)", # the built-in Administrator's alias + "D:P(A;OICI;FA;;;S-1-5-18)(A;OICI;FA;;;S-1-5-32-544)(A;OICIIO;GA;;;CO)(A;OICI;FA;;;OW)"): + self.assertEqual(self.offenders(sddl), [], sddl) + + def test_another_account_is_named(self): + self.assertEqual(self.offenders("D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)(A;OICI;FR;;;BU)"), ["BU"]) + self.assertEqual(self.offenders("D:PAI(A;;FA;;;WD)(A;;FA;;;AU)"), ["WD", "AU"]) + self.assertEqual(self.offenders("D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1002)"), ["S-1-5-21-1-2-3-1002"]) + + def test_an_inherit_only_entry_is_not_for_the_folder_itself(self): + self.assertEqual(self.offenders("D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)(A;OICIIO;FR;;;BU)(A;CIIO;GR;;;WD)"), []) + # the same entry without the IO flag does apply + self.assertEqual(self.offenders("D:PAI(A;OICI;FR;;;BU)"), ["BU"]) + + def test_deny_entries_do_not_make_it_reachable(self): + self.assertEqual(self.offenders("D:PAI(D;;FA;;;BU)(A;OICI;FA;;;S-1-5-21-1-2-3-1001)"), []) + + def test_plain_names(self): + self.assertEqual(self.pf.account_name("BU"), "Users") + self.assertEqual(self.pf.account_name("WD"), "Everyone") + self.assertEqual(self.pf.account_name("S-1-5-32-545"), "Users") + + def test_runtime_dir_repairs_a_folder_that_names_other_accounts(self): + from strata_control import runtime + pf = self.pf + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) / "runtime" + base.mkdir() + state = {"fixed": False} + + def sddl(_path): + return "D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)" if state["fixed"] else \ + "D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)(A;OICI;0x1200a9;;;BU)" + + def restrict(path, directory=None): + state["fixed"] = True + + env = {"STRATA_RUNTIME_DIR": str(base)} + with self.mock.patch.dict(os.environ, env), self.mock.patch.object(pf, "dacl_sddl", side_effect=sddl), \ + self.mock.patch.object(pf, "restrict_to_current_user", side_effect=restrict) as r, \ + self.mock.patch.object(pf, "private_mkdir"), self.mock.patch.object(runtime, "_private_mkdir"): + self.assertEqual(runtime.runtime_dir(), base) + self.assertEqual(r.call_count, 1) + + def test_runtime_dir_still_refuses_and_says_who_when_the_repair_fails(self): + from strata_control import profiles, runtime + pf = self.pf + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) / "runtime" + base.mkdir() + with self.mock.patch.dict(os.environ, {"STRATA_RUNTIME_DIR": str(base)}), \ + self.mock.patch.object(pf, "dacl_sddl", return_value="D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)(A;OICI;FR;;;BU)"), \ + self.mock.patch.object(pf, "restrict_to_current_user", side_effect=OSError("denied")), \ + self.mock.patch.object(runtime, "_private_mkdir"): + with self.assertRaises(profiles.ProfileError) as cm: + runtime.runtime_dir() + self.assertIn("Users", str(cm.exception)) + self.assertIn(str(base), str(cm.exception)) + self.assertIn("Properties", str(cm.exception)) + + +@unittest.skipUnless(sys.platform == "win32", "ACLs are Windows only") +class WindowsRuntimeFolderMoreCases(unittest.TestCase): + """The cases beyond the first repair (audit-refusals-022.md item 5): a data drive's inherited Users entries, an ACL that cannot be + read, a folder made by an elevated run, a drive without permissions, and a message in plain words.""" + + ME = "S-1-5-21-1-2-3-1001" + + def run_dir(self, *, sddl, restrict=None, repair=None, acls=True): + from unittest import mock + from strata_control import private_files as pf, runtime + with tempfile.TemporaryDirectory() as tmp: + base = Path(tmp) / "runtime" + base.mkdir() + calls = {"restrict": 0, "repair": 0} + + def r(path, directory=None): + calls["restrict"] += 1 + if restrict: + return restrict(calls) + def rp(path, tree=True): + calls["repair"] += 1 + return repair(calls) if repair else False + with mock.patch.dict(os.environ, {"STRATA_RUNTIME_DIR": str(base)}), \ + mock.patch.object(pf, "current_user_sid", return_value=self.ME), \ + mock.patch.object(pf, "dacl_sddl", side_effect=sddl), \ + mock.patch.object(pf, "restrict_to_current_user", side_effect=r), \ + mock.patch.object(pf, "repair_access", side_effect=rp), \ + mock.patch.object(pf, "volume_has_acls", return_value=acls), \ + mock.patch.object(runtime, "_private_mkdir"), mock.patch.object(runtime, "_NO_ACL_WARNED", set()), \ + mock.patch("sys.stderr", new_callable=lambda: __import__("io").StringIO()) as err: + try: + return runtime.runtime_dir(), calls, None, err.getvalue() + except Exception as exc: # noqa: BLE001 - the test looks at the ProfileError text + return None, calls, exc, err.getvalue() + + def test_a_data_drive_folder_with_users_and_authenticated_users_is_repaired_once(self): + state = {"fixed": False} + def sddl(_): + return f"D:PAI(A;OICI;FA;;;{self.ME})" if state["fixed"] else \ + f"D:PAI(A;OICI;FA;;;{self.ME})(A;OICI;0x1301bf;;;AU)(A;OICI;0x1200a9;;;BU)" + base, calls, exc, _ = self.run_dir(sddl=sddl, restrict=lambda c: state.update(fixed=True)) + self.assertIsNone(exc) + self.assertEqual(calls["restrict"], 1) + + def test_an_acl_that_cannot_be_read_is_repaired_then_refused_in_plain_words(self): + def sddl(_): + raise OSError("access denied") + base, calls, exc, _ = self.run_dir(sddl=sddl) + self.assertIsNotNone(exc) + self.assertEqual((calls["restrict"], calls["repair"]), (1, 1)) # tried both, once each + self.assertIn("cannot read the permissions", str(exc)) + self.assertNotIn("0700", str(exc)) + + def test_a_folder_made_by_an_elevated_run_gets_ownership_taken_back(self): + state = {"fixed": False} + def sddl(_): + if not state["fixed"]: + raise OSError("access denied") + return f"D:PAI(A;OICI;FA;;;{self.ME})" + def restrict(calls): + raise PermissionError("denied") + base, calls, exc, _ = self.run_dir(sddl=sddl, restrict=restrict, repair=lambda c: state.update(fixed=True) or True) + self.assertIsNone(exc) + self.assertEqual((calls["restrict"], calls["repair"]), (1, 1)) + + def test_a_drive_without_permissions_is_used_with_one_warning(self): + def sddl(_): + raise AssertionError("FAT has no ACL to read") + base, calls, exc, err = self.run_dir(sddl=sddl, acls=False) + self.assertIsNone(exc) + self.assertEqual((calls["restrict"], calls["repair"]), (0, 0)) + self.assertIn("no file permissions", err) + + def test_the_refusal_names_the_accounts_and_never_says_mode_0700(self): + sddl = lambda _: f"D:PAI(A;OICI;FA;;;{self.ME})(A;OICI;FR;;;AU)(A;OICI;FR;;;WD)" # noqa: E731 + base, calls, exc, _ = self.run_dir(sddl=sddl) + text = str(exc) + self.assertIn("Authenticated Users", text) + self.assertIn("Everyone", text) + self.assertNotIn("0700", text) + self.assertEqual(calls["restrict"], 1) + + def test_the_real_system_drive_has_permissions(self): + from strata_control import private_files as pf + self.assertTrue(pf.volume_has_acls(os.environ.get("SystemRoot", "C:\\Windows"))) + + +class Issue3410TrashIsNotAnInstall(unittest.TestCase): + def test_trash_folders_are_recognised(self): + from strata_control.discovery import in_trash + for p in ("/home/u/.local/share/Trash/files/strata", "/mnt/d/.Trash-1000/files/Strata", "/Users/u/.Trash/Strata", + "C:\\$Recycle.Bin\\S-1-5-21\\$R123\\Strata", "/home/u/.local/share/trash/files/strata/x"): + self.assertTrue(in_trash(p), p) + for p in ("/home/u/bin/strata", "/home/u/Trash-talk/strata", "/home/u/trash/strata", "/opt/Strata", + "C:\\Users\\u\\Strata"): + self.assertFalse(in_trash(p), p) + + def test_remembered_installs_in_the_trash_are_not_listed(self): + from strata_control import discovery + with tempfile.TemporaryDirectory() as tmp: + good = Path(tmp) / "bin" / "strata" + trash = Path(tmp) / ".local" / "share" / "Trash" / "files" / "strata" + got = discovery._installs_in({"installs": [str(trash), str(good)]}) + self.assertEqual(got, [good]) + + def test_setup_does_not_pass_a_trash_folder_on(self): + import setup + with tempfile.TemporaryDirectory() as tmp: + trash = Path(tmp) / ".local" / "share" / "Trash" / "files" / "strata" + trash.mkdir(parents=True) + (trash / "setup.py").write_text("x") + from unittest import mock + nowhere = Path(tmp) / "none" / "none" / "home" # no Strata* folders beside it on this PC + with mock.patch.object(setup, "home", return_value=nowhere): + self.assertEqual(setup.other_installs({"installs": [str(trash)]}), []) + self.assertEqual(setup.other_installs({"installs": [str(trash)] + [str(trash.parent.parent)]}), []) + + +class Issue2971WebToolRowFitsPhones(unittest.TestCase): + """A tool row widened the whole page on a phone (752 px page at a 412 px viewport, measured in Chrome). The three rules + that keep it inside the viewport; a long tool name is cut with an ellipsis instead of pushing the page.""" + + def test_the_rules_are_in_the_stylesheet(self): + import re + css = (Path(__file__).resolve().parents[2] / "serve" / "web" / "app.css").read_text(encoding="utf-8") + + def rule(selector): + m = re.search(r"(?m)^" + re.escape(selector) + r"\s*\{([^}]*)\}", css) + self.assertIsNotNone(m, selector) + return m.group(1) + + self.assertIn("min-width: 0", rule(".view")) + self.assertIn("overflow: hidden", rule(".tool-call > summary")) + name = rule(".tool-call__name") + for part in ("min-width: 0", "overflow: hidden", "text-overflow: ellipsis"): + self.assertIn(part, name) + + +class Issue3188BenchStartsItsOwnServer(unittest.TestCase): + """tools/strata_bench.py named `port` in the start-a-server branch without ever setting it.""" + + def test_the_start_branch_runs_with_the_config_port(self): + from unittest import mock + from tools import strata_bench as sb + import io + from contextlib import redirect_stdout + with tempfile.TemporaryDirectory() as tmp: + cfg = Path(tmp) / "run.json" + cfg.write_text(json.dumps({"port": 18999, "args": []}), encoding="utf-8") + started = [] + with mock.patch.object(sb, "is_strata", return_value=False), \ + mock.patch.object(sb, "try_json", return_value=None), \ + mock.patch.object(sb, "start_server", side_effect=lambda c, p, g, log: started.append(p) or object()), \ + mock.patch.object(sb, "wait_ready", return_value=False), \ + mock.patch.object(sb, "stop_server"): + out = io.StringIO() + with redirect_stdout(out), mock.patch("sys.stderr", io.StringIO()): + code = sb.main(["--config", str(cfg)]) + self.assertEqual(code, 1) + self.assertEqual(started, [18999]) + self.assertIn("on port 18999", out.getvalue()) + started.clear() + with redirect_stdout(io.StringIO()), mock.patch("sys.stderr", io.StringIO()): + sb.main(["--config", str(cfg), "--port", "18777"]) + self.assertEqual(started, [18777]) + + +@unittest.skipUnless(sys.platform == "win32", "SDDL aliases exist on Windows only") +class Issue3302AdministratorAlias(unittest.TestCase): + """SDDL prints the built-in Administrator (RID 500) as `LA`; the owner-only checks must still accept it.""" + + def setUp(self): + from unittest import mock + from strata_control import private_files as pf + self.pf = pf + self.mock = mock + # the built-in Administrator's string SID on this machine: resolve the alias the same way the fix does + import ctypes + from ctypes import wintypes + pointer = ctypes.c_void_p() + pf._advapi.ConvertStringSidToSidW("LA", ctypes.byref(pointer)) + text = wintypes.LPWSTR() + pf._advapi.ConvertSidToStringSidW(pointer.value, ctypes.byref(text)) + self.admin_sid = text.value + self.assertTrue(self.admin_sid.endswith("-500")) + + def test_alias_matches_the_account_it_names(self): + self.assertTrue(self.pf._same_sid("LA", self.admin_sid)) + self.assertTrue(self.pf._same_sid(self.admin_sid, self.admin_sid)) + self.assertFalse(self.pf._same_sid("LA", "S-1-5-21-1-2-3-1001")) + self.assertFalse(self.pf._same_sid("WD", self.admin_sid)) + self.assertFalse(self.pf._same_sid("S-1-5-21-1-2-3-1001", self.admin_sid)) + + def test_private_and_unshared_hold_for_the_built_in_administrator(self): + pf = self.pf + with self.mock.patch.object(pf, "current_user_sid", return_value=self.admin_sid), \ + self.mock.patch.object(pf, "dacl_sddl", return_value="D:PAI(A;OICI;FA;;;LA)"): + self.assertTrue(pf.is_private("x")) + self.assertTrue(pf.is_unshared("x")) + with self.mock.patch.object(pf, "current_user_sid", return_value=self.admin_sid), \ + self.mock.patch.object(pf, "dacl_sddl", return_value="D:PAI(A;OICI;FA;;;S-1-5-21-1-2-3-1001)"): + self.assertFalse(pf.is_private("x")) + self.assertFalse(pf.is_unshared("x")) + with self.mock.patch.object(pf, "current_user_sid", return_value=self.admin_sid), \ + self.mock.patch.object(pf, "dacl_sddl", return_value="D:PAI(A;OICI;FA;;;LA)(A;OICI;FR;;;WD)"): + self.assertFalse(pf.is_private("x")) + self.assertFalse(pf.is_unshared("x")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/terminal/test_runtime.py b/tests/terminal/test_runtime.py index 9351195d..1b7a2a27 100644 --- a/tests/terminal/test_runtime.py +++ b/tests/terminal/test_runtime.py @@ -1167,7 +1167,17 @@ class RuntimeTests(unittest.TestCase): if done.returncode != 0: self.skipTest("icacls could not widen the test directory") with mock.patch.dict(os.environ, {"STRATA_RUNTIME_DIR": str(shared)}): - with self.assertRaisesRegex(profiles.ProfileError, "owner-only"): + # a folder that names Everyone is the user's own state folder: it is locked down once and used (never a stop) + self.assertEqual(runtime.runtime_dir(), shared) + self.assertTrue(private_files.is_unshared(shared)) + again = Path(self.temp.name) / "shared-runtime-2" + again.mkdir() + subprocess.run(["icacls", str(again), "/grant", "*S-1-1-0:(OI)(CI)R"], capture_output=True) + with mock.patch.dict(os.environ, {"STRATA_RUNTIME_DIR": str(again)}), \ + mock.patch.object(private_files, "restrict_to_current_user"), \ + mock.patch.object(private_files, "repair_access", return_value=False): + # when the lock-down does not happen it still refuses, in plain words and naming who can open it + with self.assertRaisesRegex(profiles.ProfileError, "Everyone"): runtime.runtime_dir() def test_exclusive_lease_waits_for_shared_holders_and_shared_holders_coexist(self): diff --git a/tools/strata_bench.py b/tools/strata_bench.py index 3a9877fc..93d92ee1 100644 --- a/tools/strata_bench.py +++ b/tools/strata_bench.py @@ -975,7 +975,8 @@ def main(argv=None) -> int: if a.url: base = a.url.rstrip("/") else: - base = server_base(cfg.get("host"), a.port or int(cfg.get("port", 8080))) + port = a.port or int(cfg.get("port", 8080)) + base = server_base(cfg.get("host"), port) red = redactor(key=key) started = False try: diff --git a/tools/test_setup_amd.py b/tools/test_setup_amd.py index 7198d65c..bd557b64 100644 --- a/tools/test_setup_amd.py +++ b/tools/test_setup_amd.py @@ -480,6 +480,22 @@ class CalibrationKey(unittest.TestCase): "NVIDIA GeForce RTX 5070 + NVIDIA GeForce RTX 5070|24GB|AMD Ryzen 9 7950X|64GB|" "qwen3.8-flash-next-iq3_xxs|32768|text") + def test_nvidia_string_dual_keys_like_the_list(self): + """A dual config's string "0,1" keys like [0, 1] (calibrate died with "there is no GPU 0,1").""" + def amd(*a, **k): + raise AssertionError("amd_gpus called for an NVIDIA config") + with mock.patch.object(setup, "amd_gpus", amd), \ + mock.patch.object(setup, "gpu_info", lambda i=None: {"name": "NVIDIA GeForce RTX 5070", "vram_gb": 11.94}): + self.assertEqual(setup.hardware_key(self.cfg("0,1", backend="cuda")), + setup.hardware_key(self.cfg([0, 1], backend="cuda"))) + self.assertEqual(setup.gpu_sel("0,1"), [0, 1]) + self.assertEqual(setup.gpu_sel("0"), [0]) + asked = [] + with mock.patch.object(setup, "amd_gpus", amd), \ + mock.patch.object(setup, "gpu_info", lambda i=None: asked.append(i) or {"name": "NVIDIA GeForce RTX 5070", "vram_gb": 11.94}): + setup.hardware_key(self.cfg(1, backend="cuda")) # a single card given as a number still asks for that card + self.assertEqual(asked, [1]) + def test_setup_reuses_a_saved_calibration_on_linux_hip(self): cfg = self.cfg(1) saved = {"settings": {"pcie_frac": 0.0}, "tok_s": 40.1, "date": "2026-10-03"} diff --git a/tools/vision/CMakeLists.txt b/tools/vision/CMakeLists.txt index 7d8a3479..4d16da55 100644 --- a/tools/vision/CMakeLists.txt +++ b/tools/vision/CMakeLists.txt @@ -86,6 +86,9 @@ if(STRATA_VISION_HIP) set(AMDGPU_TARGETS "${STRATA_VISION_HIP_ARCHS}" CACHE STRING "" FORCE) set(GPU_TARGETS "${STRATA_VISION_HIP_ARCHS}" CACHE STRING "" FORCE) set(CMAKE_HIP_ARCHITECTURES "${STRATA_VISION_HIP_ARCHS}" CACHE STRING "" FORCE) + # #3359: a Linux toolchain links a PIE; ggml-hip's objects must be position independent (the engine's HIP build says the same in + # cmake/hip_backend.cmake). Only for the HIP reader: the other readers' builds stay as they were. + set(CMAKE_POSITION_INDEPENDENT_CODE ON) endif() add_subdirectory(${LLAMA_DIR} llama EXCLUDE_FROM_ALL)