okami.mom/strata

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

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
52.4 KiB846 linesraw
1"""A Qwen4 model of its own shape runs on its own engine component (strata_control/shape_engine.py), picked by the model, beside the Strata engine.
2
3What these tests pin:
4  * the names: shape q4_lite, component strata-q4-lite, feed model family qwen4exp_q4_lite, run config reference component:strata-q4-lite;
5  * packaging: package_engine --shape makes a package whose manifest id is the shape's component; read as the Strata engine it is refused, so an older Control (which reads only
6    strata-engine) ignores one put into its engine folder by hand; a normal package never claims a shape;
7  * the feed: member shape_engines, parsed, never mixed into ``engine``; feed_tool packs and lists it and refuses a model of a shape that has no engine;
8  * the install (a local signed feed over loopback, a stub engine, a throwaway key): the package is fetched, checked (signature, hashes, shape), placed in
9    <components>/shapes/<shape>/engine/, started once, and the Strata engine's files are byte for byte what they were; a bad package or a failed start changes nothing;
10  * use: component:strata-q4-lite resolves to that engine, component:strata-engine still to the Strata engine; a missing shape engine is a plain refusal, not a fetch;
11  * update: `strata update` brings an installed shape engine up to date beside the older one and prunes beyond two; a PC with none has no such step;
12  * older Controls: the feed.py of the Control before this (git) reads the same feed as one without the new member and does not offer the model.
13"""
14from __future__ import annotations
15
16import base64
17import hashlib
18import importlib.util
19import json
20import os
21import shutil
22import subprocess
23import sys
24import tempfile
25import unittest
26from pathlib import Path
27from unittest import mock
28
29ROOT = Path(__file__).resolve().parents[2]
30sys.path.insert(0, str(ROOT))
31sys.path.insert(0, str(ROOT / "packaging"))
32
33import feed_tool  # noqa: E402
34import package_engine  # noqa: E402
35from strata_control import components, engine_component as ec, feed as feedmod, shape_engine, signing, updater  # noqa: E402
36from strata_control.targets import host_platform  # noqa: E402
37from tests.terminal import update_fixture as fx  # noqa: E402
38
39REV = "0123456789abcdef0123456789abcdef01234567"
40SHAPE = "q4_lite"
41COMP = "strata-q4-lite"
42EXE = shape_engine.exe_name()
43
44
45def stub_source(parent: Path, version: str, *, text: str = "stub strata", padding: int = 0) -> Path:
46    src = parent / f"src-{version}"
47    src.mkdir(parents=True)
48    (src / EXE).write_bytes(f"{text} {version} ".encode() + (os.urandom(padding) if padding else b"x" * 100))
49    (src / ("cudart64_13.dll" if os.name == "nt" else "libcudart.so.13")).write_bytes(b"a runtime library " * 50)
50    return src
51
52
53def build(parent: Path, version: str, key: dict | None, *, shape: str = SHAPE, padding: int = 0, min_runtime: str | None = None) -> Path:
54    out = parent / "built"
55    out.mkdir(parents=True, exist_ok=True)
56    folder = package_engine.build(stub_source(parent, version, padding=padding), "cuda", version, components.host_platform(), out, entry=EXE, archs=("sm_86",),
57                                  min_driver={"nvidia": "580.65"}, build_id=f"{shape or 'plain'}-{version}", variant="cuda13", shape=shape, min_runtime=min_runtime)
58    if key is not None:
59        feed_tool.sign_package(folder, key)
60    return folder
61
62
63def tree(d: Path) -> str:
64    h = hashlib.sha256()
65    for p in sorted(Path(d).rglob("*")):
66        if p.is_file():
67            h.update(str(p.relative_to(d)).encode() + p.read_bytes())
68    return h.hexdigest()
69
70
71def model_entry(**kw) -> dict:
72    m = {"id": "q4lite-test", "title": "Qwen4 Lite Test", "by": "Qwen", "about": "a test model", "licence": "Apache 2.0",
73         "licence_url": "https://huggingface.co/test/q4lite", "family": shape_engine.family_of(SHAPE), "repo": "test/Q4Lite-GGUF", "revision": REV,
74         "drafter": "none", "context": 131072,
75         "quants": [{"name": "Q4_K_M", "about": "4-bit", "ram_gb": 8, "arena_gb": 2.5,
76                     "files": [{"name": "Q4Lite-Q4_K_M.gguf", "size": 1000, "sha256": "a" * 64}]}]}
77    m.update(kw)
78    return m
79
80
81class Base(unittest.TestCase):
82    def setUp(self):
83        self.tmp = tempfile.TemporaryDirectory(prefix="strata-shape-")
84        self.addCleanup(self.tmp.cleanup)
85        self.root = Path(self.tmp.name)
86        self.key = fx.make_key()
87        trust = self.root / "trust.json"
88        trust.write_text(json.dumps({"keys": [signing.public_part(self.key)]}))
89        self.comp = self.root / "c"
90        for p in (mock.patch.dict(os.environ, {"STRATA_UPDATE_TRUSTED_KEYS": str(trust), "STRATA_COMPONENTS_DIR": str(self.comp)}),
91                  mock.patch.object(signing, "BUILTIN_KEYS", self.root / "none.json"),
92                  mock.patch.object(ec, "cuda_archs_present", return_value=["sm_86"]),
93                  mock.patch.object(ec, "nvidia_driver_version", return_value="610.47"),
94                  mock.patch.object(ec, "detect_backend", return_value=("cuda", "test"))):
95            p.start()
96            self.addCleanup(p.stop)
97        self.addCleanup(ec.register_signature_verifier, None)
98        self.hw = {"platform": host_platform(), "backend": "cuda", "runtime": None, "nvidia_driver": "610.47", "cuda_archs": ["sm_86"], "gfx": []}
99        self.release = self.root / "release"
100        self.release.mkdir()
101        self.server = fx.FeedServer(self.release)
102        self.server.__enter__()
103        self.addCleanup(self.server.__exit__)
104        self.url = self.server.url + "/strata-feed.json"
105        # the Strata engine of this PC: a signed stub package in <components>/engine, whose bytes must never change
106        plain = build(self.root / "plain", "0.1.58", self.key, shape="")
107        (self.comp / "engine").mkdir(parents=True)
108        shutil.copytree(plain, self.comp / "engine" / plain.name)
109        self.strata_before = tree(self.comp / "engine")
110
111    def publish(self, *versions, shape: str = SHAPE, models=None, sequence=1, key=None, extra_members=None):
112        shutil.rmtree(self.release, ignore_errors=True)
113        (self.release / "shapes").mkdir(parents=True)
114        self.published = getattr(self, "published", 0) + 1
115        for v in versions:
116            folder = build(self.root / f"pub-{shape}-{v}-{self.published}", v, key or self.key, shape=shape)
117            feed_tool.pack_engine(folder, self.release / "shapes", url_prefix="shapes/")
118        if models:
119            (self.release / "models").mkdir()
120            for m in models:
121                (self.release / "models" / f"{m['id']}.entry.json").write_text(json.dumps(m))
122        return feed_tool.build_feed(self.release, key=self.key, sequence=sequence, shapes_dir=self.release / "shapes" if versions else None,
123                                    models_dir=self.release / "models" if models else None)
124
125    def ensure(self, lines=None, **kw):
126        out = [] if lines is None else lines
127        return shape_engine.ensure(SHAPE, self.url, components=self.comp, hardware=self.hw, emit=out.append, **kw)
128
129    def folders(self):
130        return sorted(p.name.split("-")[0] for p in (self.comp / "shapes" / SHAPE / "engine").iterdir() if p.is_dir())
131
132
133class Names(unittest.TestCase):
134    def test_a_shape_has_one_component_one_family_one_reference(self):
135        self.assertEqual(shape_engine.component_id("q4_lite"), "strata-q4-lite")
136        self.assertEqual(shape_engine.shape_of_component("strata-q4-lite"), "q4_lite")
137        self.assertEqual(shape_engine.family_of("q4_lite"), "qwen4exp_q4_lite")
138        self.assertEqual(shape_engine.shape_of_family("qwen4exp_q4_lite"), "q4_lite")
139        self.assertEqual(shape_engine.reference("q4_lite"), "component:strata-q4-lite")
140        self.assertEqual(ec.REFERENCE_PREFIX + COMP, shape_engine.reference(SHAPE))
141
142    def test_what_is_not_a_shape_is_none(self):
143        for family in ("qwen4exp", "qwen35moe", "qwen4exp_", "qwen4exp_Q4", "qwen4exp_q4-lite", "qwen4exp_" + "x" * 30, None, 7):
144            self.assertIsNone(shape_engine.shape_of_family(family), family)
145        for comp in ("strata-engine", "strata-dsv41", "strata-control", "engine", "strata-", "strata-q4_lite", "strata-Q4-lite", None):
146            self.assertIsNone(shape_engine.shape_of_component(comp), comp)
147
148    def test_a_shape_never_becomes_a_component_that_means_something_else(self):
149        for shape in ("engine", "dsv41", "control", "vision", "device"):
150            self.assertFalse(shape_engine.valid(shape), shape)
151        for shape in ("", "q", "Q4_lite", "q4-lite", "q4__lite", "q4_lite_", "1q4", "q4 lite", "q4/lite", "x" * 24):
152            self.assertFalse(shape_engine.valid(shape), repr(shape))
153        for shape in ("q4_lite", "q4_mid", "q4_deep", "q4_big", "qwen4_a", "x" * 23):
154            self.assertTrue(shape_engine.valid(shape), shape)
155        self.assertLessEqual(len(shape_engine.family_of("x" * 23)), 32, "a family name must fit the feed's family pattern")
156
157
158class Packaging(Base):
159    def test_a_shape_package_is_its_own_component(self):
160        folder = build(self.root / "p", "0.1.59", self.key)
161        raw = json.loads((folder / ec.MANIFEST).read_text())
162        self.assertEqual((raw["id"], raw["name"], raw["shape"]), (COMP, COMP, SHAPE))
163        comp = ec.read_manifest(folder, COMP)
164        self.assertEqual((comp.shape, comp.id), (SHAPE, COMP))
165        self.assertEqual(ec.read_manifest_any(folder).shape, SHAPE)
166        self.assertEqual(comp.to_dict()["shape"], SHAPE)
167
168    def test_it_is_not_read_as_the_strata_engine_so_an_older_control_ignores_it(self):
169        folder = build(self.root / "p", "0.1.59", self.key)
170        with self.assertRaises(ec.ComponentProblem) as ctx:
171            ec.read_manifest(folder)                                   # what a Control from before this reads, and what the Strata engine's scan reads
172        self.assertIn("not an engine component", str(ctx.exception))
173        wrong = shape_engine.component_id("q4_mid")
174        with self.assertRaises(ec.ComponentProblem):
175            ec.read_manifest(folder, wrong)                            # the id and the shape must agree
176        (self.comp / "engine" / folder.name).parent.mkdir(parents=True, exist_ok=True)
177        shutil.copytree(folder, self.comp / "engine" / folder.name)    # copied into the Strata engine's folder by hand
178        found, problems = ec.scan(self.comp)
179        self.assertEqual([c.version for c in found], ["0.1.58"])
180        self.assertEqual(len(problems), 1)
181        self.assertEqual(ec.resolve(self.comp, backend="cuda").version, "0.1.58")
182
183    def test_a_strata_engine_never_claims_a_shape(self):
184        plain = build(self.root / "p2", "0.1.60", self.key, shape="")
185        raw = json.loads((plain / ec.MANIFEST).read_text())
186        self.assertEqual(raw["id"], "strata-engine")
187        self.assertNotIn("shape", raw)
188        raw["shape"] = SHAPE
189        (plain / ec.MANIFEST).write_text(json.dumps(raw))
190        with self.assertRaises(ec.ComponentProblem):
191            ec.read_manifest(plain)
192
193    def test_a_bad_shape_name_stops_the_packager(self):
194        with self.assertRaises(SystemExit):
195            build(self.root / "p3", "0.1.59", None, shape="Not A Shape")
196        with self.assertRaises(SystemExit):
197            build(self.root / "p4", "0.1.59", None, shape="engine")
198
199    def test_the_command_line_makes_and_verifies_one(self):
200        src = stub_source(self.root / "cli", "0.1.59")
201        out = self.root / "cli-out"
202        done = subprocess.run([sys.executable, str(ROOT / "packaging" / "package_engine.py"), "--src", str(src), "--backend", "cuda", "--version", "0.1.59",
203                               "--out", str(out), "--arch", "sm_86", "--entrypoint", EXE, "--shape", SHAPE, "--build-id", "x"], capture_output=True, text=True)
204        self.assertEqual(done.returncode, 0, done.stdout + done.stderr)
205        folder = next(out.iterdir())
206        verified = subprocess.run([sys.executable, str(ROOT / "packaging" / "package_engine.py"), "--verify", str(folder)], capture_output=True, text=True)
207        self.assertEqual(verified.returncode, 0, verified.stdout)
208        self.assertEqual(json.loads((folder / ec.MANIFEST).read_text())["id"], COMP)
209
210
211class Feed(Base):
212    def test_the_member_is_parsed_and_kept_apart_from_engine(self):
213        doc = self.publish("0.1.59")
214        self.assertEqual(doc["shape_engines"]["packages"][0]["shape"], SHAPE)
215        loaded = feedmod.fetch(self.url, signing.load_trusted_keys())
216        self.assertEqual([(p.shape, p.version) for p in loaded.shape_engines], [(SHAPE, "0.1.59")])
217        self.assertEqual(loaded.engine, ())
218        self.assertTrue(loaded.shape_engines[0].url.startswith("shapes/strata-q4-lite-0.1.59-"))
219        self.assertEqual(loaded.shape_engines[0].to_dict()["shape"], SHAPE)
220
221    def test_a_feed_without_the_member_is_what_it_was(self):
222        shutil.rmtree(self.release, ignore_errors=True)
223        feed_tool.build_feed(self.release, key=self.key, sequence=1)
224        loaded = feedmod.fetch(self.url, signing.load_trusted_keys())
225        self.assertEqual(loaded.shape_engines, ())
226        self.assertNotIn("shape_engines", json.loads((self.release / feedmod.FEED_NAME).read_text()))
227
228    def test_an_entry_with_a_shape_this_control_does_not_accept_is_left_out_with_a_line(self):
229        doc = self.publish("0.1.59")
230        doc["shape_engines"]["packages"].append({**doc["shape_engines"]["packages"][0], "shape": "Not Valid"})
231        parsed = feedmod.parse(json.dumps(doc).encode(), source="x", key_id="k")
232        self.assertEqual(len(parsed.shape_engines), 1)
233        self.assertTrue(any("shape" in line for line in parsed.skipped), parsed.skipped)
234
235    def test_the_same_shape_and_version_twice_is_refused(self):
236        doc = self.publish("0.1.59")
237        doc["shape_engines"]["packages"].append(dict(doc["shape_engines"]["packages"][0]))
238        with self.assertRaises(feedmod.FeedError):
239            feedmod.parse(json.dumps(doc).encode(), source="x", key_id="k")
240
241    def test_a_model_of_a_shape_is_parsed_with_its_shape(self):
242        self.publish("0.1.59", models=[model_entry()])
243        loaded = feedmod.fetch(self.url, signing.load_trusted_keys())
244        (m,) = loaded.models
245        self.assertEqual((m.family, m.shape), (shape_engine.family_of(SHAPE), SHAPE))
246        self.assertIsNone(feedmod.parse(json.dumps({"schema_version": 1, "channel": "stable", "generated_at": "2026-11-08T00:00:00Z", "sequence": 1,
247                                                    "models": {"packages": [model_entry(id="plain-one", family="qwen4exp")]}}).encode(), source="x", key_id="k").models[0].shape)
248
249    def test_a_model_with_a_broken_shape_name_is_dropped_with_a_line(self):
250        doc = {"schema_version": 1, "channel": "stable", "generated_at": "2026-11-08T00:00:00Z", "sequence": 1,
251               "models": {"packages": [model_entry(family="qwen4exp_Q4-bad")]}}
252        parsed = feedmod.parse(json.dumps(doc).encode(), source="x", key_id="k")
253        self.assertEqual((parsed.models, len(parsed.models_dropped)), ((), 1))
254
255    def test_build_feed_refuses_a_model_of_a_shape_with_no_engine(self):
256        (self.release / "models").mkdir(parents=True)
257        (self.release / "models" / "q4lite-test.entry.json").write_text(json.dumps(model_entry()))
258        with self.assertRaises(SystemExit) as ctx:
259            feed_tool.build_feed(self.release, key=self.key, sequence=1, models_dir=self.release / "models")
260        self.assertIn("q4_lite", str(ctx.exception))
261        with self.assertRaises(SystemExit):
262            self.publish("0.1.59", shape="q4_mid", models=[model_entry()])       # an engine for another shape does not do
263
264    def test_pack_engine_names_the_archive_by_the_component_and_the_entry_by_the_shape(self):
265        folder = build(self.root / "pk", "0.1.59", self.key)
266        out = self.root / "pk-out"
267        out.mkdir()
268        entry = feed_tool.pack_engine(folder, out, url_prefix="")
269        self.assertEqual(entry["shape"], SHAPE)
270        self.assertTrue(entry["url"].startswith("strata-q4-lite-0.1.59-"), entry["url"])
271        plain = build(self.root / "pk2", "0.1.60", self.key, shape="")
272        self.assertNotIn("shape", feed_tool.pack_engine(plain, out, url_prefix=""))
273        self.assertTrue(next(p for p in out.glob("*.entry.json") if "strata-engine" in p.name))
274
275    def test_verify_feed_lists_the_shape_engines(self):
276        self.publish("0.1.59", models=[model_entry()])
277        pub = self.root / "pub.json"
278        pub.write_text(json.dumps({"keys": [signing.public_part(self.key)]}))
279        done = subprocess.run([sys.executable, str(ROOT / "packaging" / "feed_tool.py"), "verify-feed", str(self.release), "--pub", str(pub)], capture_output=True, text=True)
280        self.assertEqual(done.returncode, 0, done.stdout + done.stderr)
281        self.assertIn("1 shape engines (q4_lite)", done.stdout)
282
283
284class Install(Base):
285    def test_the_engine_of_the_shape_is_fetched_beside_the_strata_engine(self):
286        self.publish("0.1.59")
287        lines = []
288        with mock.patch.object(shape_engine, "_test_start", return_value=(True, "strata 0.1.59")):
289            exe = self.ensure(lines)
290        self.assertIsNotNone(exe, lines)
291        self.assertEqual(exe.parent.parent.parent, self.comp / "shapes" / SHAPE)
292        self.assertTrue(exe.is_file())
293        self.assertEqual(self.strata_before, tree(self.comp / "engine"), "the Strata engine's files must not change")
294        self.assertEqual(ec.resolve(self.comp, backend="cuda").version, "0.1.58")
295        self.assertIn("0.1.59", " ".join(lines))
296        self.assertEqual(shape_engine.newest_version(SHAPE, self.comp), "0.1.59")
297        self.assertEqual(shape_engine.installed_shapes(self.comp), [SHAPE])
298        self.assertEqual(json.loads((exe.parent / ec.MANIFEST).read_text())["shape"], SHAPE)
299
300    def test_the_reference_resolves_to_the_shape_engine_and_the_other_to_the_strata_engine(self):
301        self.publish("0.1.59")
302        with mock.patch.object(shape_engine, "_test_start", return_value=(True, "x")):
303            exe = self.ensure()
304        self.assertEqual(Path(ec.expand("component:strata-q4-lite", {"backend": "cuda"})), exe)
305        strata = Path(ec.expand("component:strata-engine", {"backend": "cuda"}))
306        self.assertEqual(strata.parent.parent.name, "engine")
307        self.assertNotEqual(strata, exe)
308        self.assertEqual(ec.expand("/some/path/strata"), "/some/path/strata")
309
310    def test_a_shape_with_no_engine_installed_is_a_plain_refusal_and_never_a_fetch(self):
311        with self.assertRaises(shape_engine.ShapeEngineMissing) as ctx:
312            ec.expand("component:strata-q4-lite", {"backend": "cuda"})
313        self.assertIsInstance(ctx.exception, ec.EngineMissing)
314        self.assertEqual(ctx.exception.exit_code, 5)
315        self.assertIn("q4_lite", str(ctx.exception))
316        self.assertIn("never downloads", str(ctx.exception))
317        with self.assertRaises(ec.EngineMissing):
318            ec.expand("component:strata-nonsense", {})
319        self.assertFalse((self.comp / "shapes").exists())
320
321    def test_a_changed_file_stops_the_start_of_that_engine_only(self):
322        self.publish("0.1.59")
323        with mock.patch.object(shape_engine, "_test_start", return_value=(True, "x")):
324            exe = self.ensure()
325        exe.write_bytes(exe.read_bytes() + b"changed")
326        with self.assertRaises(ec.EngineMissing):
327            ec.expand("component:strata-q4-lite", {"backend": "cuda"})
328        self.assertTrue(Path(ec.expand("component:strata-engine", {"backend": "cuda"})).is_file())
329
330    def test_an_installed_engine_that_is_current_is_not_fetched_again_and_says_nothing(self):
331        self.publish("0.1.59")
332        with mock.patch.object(shape_engine, "_test_start", return_value=(True, "x")):
333            self.assertIsNotNone(self.ensure())
334            self.server.requests.clear()
335            lines = []
336            self.assertIsNotNone(self.ensure(lines))
337        self.assertEqual(lines, [])
338        self.assertFalse([r for r in self.server.requests if r[1].endswith(".tar.gz")], self.server.requests)
339
340    def test_a_cut_download_resumes(self):
341        self.publish("0.1.59")
342        shutil.rmtree(self.release)
343        (self.release / "shapes").mkdir(parents=True)
344        folder = build(self.root / "big", "0.1.59", self.key, padding=3_000_000)
345        feed_tool.pack_engine(folder, self.release / "shapes", url_prefix="shapes/")
346        feed_tool.build_feed(self.release, key=self.key, sequence=1, shapes_dir=self.release / "shapes")
347        self.server.cut[next((self.release / "shapes").glob("*.tar.gz")).name] = 800_000
348        lines = []
349        with mock.patch.object(shape_engine, "_test_start", return_value=(True, "x")):
350            self.assertIsNotNone(self.ensure(lines), lines)           # cut part-way: the same run continues from the byte it reached
351        ranges = [r[2] for r in self.server.requests if r[1].endswith(".tar.gz")]
352        self.assertEqual(ranges, [None, "bytes=800000-"], "exactly one more request, from the byte the cut reached: no byte twice")
353        self.assertEqual(self.strata_before, tree(self.comp / "engine"))
354
355    def test_the_feed_has_no_engine_for_the_shape(self):
356        self.publish("0.1.59", shape="q4_mid")
357        lines = []
358        self.assertIsNone(self.ensure(lines))
359        self.assertIn("The update feed has no engine for q4_lite for this computer.", " ".join(lines))
360        self.assertFalse((self.comp / "shapes" / SHAPE).exists())
361        self.assertEqual(self.strata_before, tree(self.comp / "engine"))
362
363    def test_no_engine_for_this_pc_is_a_plain_line(self):
364        self.publish("0.1.59")
365        self.hw = {**self.hw, "cuda_archs": ["sm_61"]}
366        lines = []
367        with mock.patch.object(ec, "cuda_archs_present", return_value=["sm_61"]):
368            self.assertIsNone(self.ensure(lines))
369        self.assertTrue(lines)
370        self.assertFalse((self.comp / "shapes" / SHAPE).exists())
371
372    def test_a_package_signed_with_another_key_is_refused(self):
373        self.publish("0.1.59", key=fx.make_key())
374        lines = []
375        self.assertIsNone(self.ensure(lines))
376        self.assertTrue(lines)
377        self.assertFalse((self.comp / "shapes" / SHAPE / "engine").exists() and list((self.comp / "shapes" / SHAPE / "engine").iterdir()))
378        self.assertEqual(self.strata_before, tree(self.comp / "engine"))
379
380    def test_a_feed_that_names_another_shape_than_the_package_says_is_refused(self):
381        doc = self.publish("0.1.59")
382        entry_file = next((self.release / "shapes").glob("*.entry.json"))
383        item = json.loads(entry_file.read_text())
384        item["shape"] = "q4_mid"                                       # the feed says q4_mid, the signed manifest says q4_lite
385        entry_file.write_text(json.dumps(item))
386        feed_tool.build_feed(self.release, key=self.key, sequence=2, shapes_dir=self.release / "shapes")
387        lines = []
388        with mock.patch.object(shape_engine, "_test_start", return_value=(True, "x")):
389            self.assertIsNone(shape_engine.ensure("q4_mid", self.url, components=self.comp, hardware=self.hw, emit=lines.append))
390        self.assertIn("not an engine component", " ".join(lines))
391        self.assertFalse((self.comp / "shapes" / "q4_mid" / "engine").exists() and list((self.comp / "shapes" / "q4_mid" / "engine").iterdir()))
392
393    def test_a_package_that_does_not_start_is_removed(self):
394        self.publish("0.1.59")
395        lines = []
396        with mock.patch.object(shape_engine, "_test_start", return_value=(False, "libcudart.so.13: not found")):
397            self.assertIsNone(self.ensure(lines))
398        self.assertIn("was not installed because it did not start correctly", " ".join(lines))
399        self.assertFalse([l for l in lines if "could not be downloaded" in l], "the approved line is said as it is, not inside another one")
400        self.assertIn("The Strata engine is unchanged", " ".join(lines))
401        self.assertEqual(shape_engine.installed(SHAPE, self.comp), [])
402        self.assertEqual(self.strata_before, tree(self.comp / "engine"))
403
404    def test_the_real_start_test_runs_the_program_and_wants_its_name(self):
405        src = self.root / "prog"
406        src.mkdir()
407        script = src / "strata"
408        script.write_text(f'#!{sys.executable}\nimport sys\nprint("strata 0.1.59" if "--version" in sys.argv else "no")\n')
409        script.chmod(0o755)
410        if os.name == "nt":
411            self.skipTest("a script is not a Windows program")
412        self.assertEqual(shape_engine._test_start(script), (True, "strata 0.1.59"))
413        script.write_text(f'#!{sys.executable}\nprint("hello")\n')
414        self.assertFalse(shape_engine._test_start(script)[0])
415
416    def _program(self, geometry):
417        """A stand-in engine program: `--version` names it, `--geometry` prints `geometry` (None: an engine from before the flag, which exits 2)."""
418        src = self.root / f"prog-{geometry}"
419        src.mkdir(exist_ok=True)
420        script = src / "strata"
421        answer = f'print({geometry!r})' if geometry else 'sys.exit(2)'
422        script.write_text(f'#!{sys.executable}\nimport sys\nif "--version" in sys.argv:\n    print("strata 0.2.13")\nelif "--geometry" in sys.argv:\n    {answer}\nelse:\n    sys.exit(3)\n')
423        script.chmod(0o755)
424        return script
425
426    def test_the_engine_must_be_built_for_the_shape_the_signed_manifest_names(self):
427        if os.name == "nt":
428            self.skipTest("a script is not a Windows program")
429        self.assertEqual(shape_engine._test_start(self._program("q4_lite"), shape="q4_lite"), (True, "strata 0.2.13"))
430        self.assertEqual(shape_engine._test_start(self._program(None), shape="q4_lite"), (False, "it does not say which model shape it was built for"),
431                         "a shape engine that cannot answer --geometry is refused (owner, 11-09)")
432        ok, why = shape_engine._test_start(self._program("flash_next"), shape="q4_lite")
433        self.assertEqual((ok, why), (False, "it was built for a different model shape (flash_next)"))
434        self.assertEqual(shape_engine._test_start(self._program("flash_next")), (True, "strata 0.2.13"), "no shape asked for: the flag is not read")
435
436    def test_the_plain_strata_engine_is_never_asked_for_its_shape(self):
437        if os.name == "nt":
438            self.skipTest("a script is not a Windows program")
439        self.assertEqual(shape_engine._test_start(self._program(None)), (True, "strata 0.2.13"), "an engine with no --geometry still installs as the Strata engine")
440        with mock.patch.object(shape_engine, "check_geometry", side_effect=AssertionError("asked")):
441            self.assertEqual(shape_engine._test_start(self._program("flash_next")), (True, "strata 0.2.13"))
442
443    def test_a_shape_engine_with_no_answer_is_refused_at_install_with_the_owners_reason(self):
444        if os.name == "nt":
445            self.skipTest("a script is not a Windows program")
446        self.publish("0.1.59")
447        with mock.patch.object(shape_engine, "_test_start", return_value=(False, shape_engine.NO_SHAPE_ANSWER)):
448            lines = []
449            self.assertIsNone(self.ensure(lines, title="Q4 Lite Shape"))
450        self.assertIn("The engine for Q4 Lite Shape 0.1.59 was not installed because it did not start correctly (it does not say which model shape it was built for). "
451                      "The Strata engine is unchanged.", " ".join(lines))
452        self.assertEqual(shape_engine.installed(SHAPE, self.comp), [])
453        self.assertEqual(self.strata_before, tree(self.comp / "engine"))
454
455    def test_the_owners_reason_for_no_answer(self):
456        self.assertEqual(shape_engine.NO_SHAPE_ANSWER, "it does not say which model shape it was built for")      # owner, 11-09
457
458    def test_a_package_built_for_another_shape_is_refused_at_install_with_the_approved_line(self):
459        if os.name == "nt":
460            self.skipTest("a script is not a Windows program")
461        self.publish("0.1.59")
462        with mock.patch.object(shape_engine, "_test_start", return_value=(False, "it was built for a different model shape (flash_next)")):
463            lines = []
464            self.assertIsNone(self.ensure(lines, title="Q4 Lite Shape"))
465        self.assertIn("The engine for Q4 Lite Shape 0.1.59 was not installed because it did not start correctly (it was built for a different model shape (flash_next)). "
466                      "The Strata engine is unchanged.", " ".join(lines))
467        self.assertEqual(shape_engine.installed(SHAPE, self.comp), [])
468        self.assertEqual(self.strata_before, tree(self.comp / "engine"))
469
470    def test_min_runtime_newer_than_this_control_keeps_it_from_starting(self):
471        shutil.rmtree(self.release, ignore_errors=True)
472        (self.release / "shapes").mkdir(parents=True)
473        folder = build(self.root / "mr", "0.1.59", self.key, min_runtime="9.9.9")
474        feed_tool.pack_engine(folder, self.release / "shapes", url_prefix="shapes/")
475        feed_tool.build_feed(self.release, key=self.key, sequence=1, shapes_dir=self.release / "shapes")
476        self.hw = {**self.hw, "runtime": "0.1.58"}
477        lines = []
478        self.assertIsNone(self.ensure(lines))
479        self.assertIn("The update feed has no engine for q4_lite for this computer.", " ".join(lines))     # the reason (needs control 9.9.9) is in the row, not in the line
480        feed = feedmod.fetch(self.url, signing.load_trusted_keys())
481        ctx = updater.Context(components=self.comp, source=self.url, trusted=signing.load_trusted_keys(), hardware=self.hw)
482        self.assertIn("9.9.9", " ".join(shape_engine.update_one(ctx, feed, SHAPE)["reasons"]))
483
484
485class Update(Base):
486    def installed(self, *versions):
487        for i, v in enumerate(versions):
488            self.publish(*versions[: i + 1], sequence=i + 1)
489            with mock.patch.object(shape_engine, "_test_start", return_value=(True, "x")):
490                self.assertIsNotNone(self.ensure(), v)
491
492    def test_a_newer_package_goes_next_to_the_old_and_the_oldest_beyond_two_goes(self):
493        self.publish("0.1.59")
494        with mock.patch.object(shape_engine, "_test_start", return_value=(True, "x")):
495            self.assertIsNotNone(self.ensure())
496        self.publish("0.1.59", "0.1.60", sequence=2)
497        lines = []
498        with mock.patch.object(shape_engine, "_test_start", return_value=(True, "x")):
499            exe = self.ensure(lines)
500        self.assertEqual(self.folders(), ["0.1.59", "0.1.60"], "the older engine stays")
501        self.assertIn("updated from 0.1.59 to 0.1.60", " ".join(lines))
502        self.assertEqual(Path(ec.expand("component:strata-q4-lite", {"backend": "cuda"})), exe)
503        self.publish("0.1.59", "0.1.60", "0.1.61", sequence=3)
504        with mock.patch.object(shape_engine, "_test_start", return_value=(True, "x")), mock.patch("strata_control.folder_use.in_use", return_value=False):
505            self.ensure()
506        self.assertEqual(self.folders(), ["0.1.60", "0.1.61"])
507        self.assertEqual(self.strata_before, tree(self.comp / "engine"))
508
509    def test_an_older_package_in_the_feed_changes_nothing(self):
510        self.installed("0.1.60")
511        self.publish("0.1.59", sequence=5)
512        self.assertIsNotNone(self.ensure())
513        self.assertEqual(self.folders(), ["0.1.60"])
514
515    def test_a_failed_start_of_the_newer_one_keeps_the_old(self):
516        self.installed("0.1.59")
517        self.publish("0.1.59", "0.1.60", sequence=9)
518        lines = []
519        with mock.patch.object(shape_engine, "_test_start", return_value=(False, "boom")):
520            exe = self.ensure(lines)
521        self.assertEqual(self.folders(), ["0.1.59"])
522        self.assertTrue(exe.is_file(), "the installed engine still runs the model")
523        self.assertEqual(shape_engine.newest_version(SHAPE, self.comp), "0.1.59")
524        self.assertIn("A newer engine for q4_lite is available but could not be installed", " ".join(lines))
525        self.assertIn("Still using 0.1.59.", " ".join(lines))
526        self.assertIn("(boom). Still using 0.1.59.", " ".join(lines), "the plain reason, not the whole refusal line, is in the newer-engine line")
527
528    def test_a_refused_acquisition_with_an_engine_installed_never_stops_a_launch(self):
529        self.installed("0.1.59")
530        from strata_control import acquisition
531        with mock.patch.object(updater, "open_feed", side_effect=acquisition.AcquisitionRefused("no")):
532            lines = []
533            self.assertTrue(self.ensure(lines).is_file())
534        self.assertEqual(lines, [])
535
536    def test_an_unreachable_feed_leaves_an_installed_engine_alone_and_says_nothing(self):
537        from tests.terminal import net_dead
538        self.installed("0.1.59")
539        for kind in net_dead.KINDS:                                   # no network at all / a refused port / a server that never answers
540            with net_dead.dead_feed(kind) as dead:
541                lines = []
542                exe = shape_engine.ensure(SHAPE, dead, components=self.comp, hardware=self.hw, emit=lines.append)
543                self.assertTrue(exe.is_file(), kind)
544                self.assertEqual(lines, [], kind)
545        with net_dead.dead_feed("refused") as dead:                   # a shape with no engine yet has nothing to fall back on: that one is said
546            lines = []
547            self.assertIsNone(shape_engine.ensure("q4_mid", dead, components=self.comp, hardware=self.hw, emit=lines.append))
548            self.assertTrue(any("could not be downloaded" in line for line in lines), lines)
549
550    def test_a_refused_feed_is_asked_once_by_the_launch_check_then_not_for_six_hours(self):
551        """netpolicy rule 4b: `strata launch` (automatic=True) with an engine installed reads the refusal note; setup (no flag) and a shape
552        with no engine yet always read the feed."""
553        from strata_control import netpolicy, transfer
554        from tests.terminal.test_netpolicy import refused_port
555        self.installed("0.1.59")
556        # the product's own windows (5 s with an engine installed), not net_dead's scaled 0.3 s: Windows reports a refusal only after about 2 s,
557        # so a scaled window would see a timeout there, not a refusal
558        dead = f"http://127.0.0.1:{refused_port()}/strata-feed.json"
559        note = netpolicy.RefusalNote(path=self.root / "state" / "net" / netpolicy.REFUSED_NOTE_NAME)
560        calls = []
561        real = transfer._open_small
562
563        def counting(request, timeout, limit):
564            calls.append(request.full_url)
565            return real(request, timeout, limit)
566        with mock.patch.object(netpolicy, "REFUSALS", note), mock.patch.object(transfer, "_open_small", counting):
567            lines = []
568            self.assertTrue(shape_engine.ensure(SHAPE, dead, components=self.comp, hardware=self.hw, emit=lines.append, automatic=True).is_file())
569            self.assertEqual(lines, [])
570            self.assertEqual(len(calls), 1, "one try: a refusal is clear at once")
571            port = dead.split("/")[2]
572            self.assertEqual(list(json.loads(note.path().read_text(encoding="utf-8"))), [port], "host:port only")
573            self.assertTrue(shape_engine.ensure(SHAPE, dead, components=self.comp, hardware=self.hw, emit=lines.append, automatic=True).is_file())
574            self.assertEqual((len(calls), lines), (1, []), "the next launch check does not connect and says nothing")
575            self.assertTrue(shape_engine.ensure(SHAPE, dead, components=self.comp, hardware=self.hw, emit=lines.append).is_file())
576            self.assertEqual(len(calls), 2, "setup's call (no flag) reads the feed")
577            self.assertIsNone(shape_engine.ensure("q4_mid", dead, components=self.comp, hardware=self.hw, emit=lines.append, automatic=True))
578            self.assertEqual(len(calls), 3, "no engine installed: the feed is always read")
579
580    def test_the_launch_asks_as_an_automatic_check_and_setup_does_not(self):
581        runner_src = (ROOT / "strata_cli" / "launch" / "runner.py").read_text(encoding="utf-8")
582        call = runner_src[runner_src.index("exe = shape_engine.ensure("):]
583        self.assertIn("automatic=True", call[:call.index("\n\n")])
584        setup_src = (ROOT / "setup.py").read_text(encoding="utf-8")
585        call = setup_src[setup_src.index("exe = shape_engine.ensure("):]
586        self.assertNotIn("automatic", call[:call.index("\n")])
587
588    def test_the_explicit_update_has_a_step_only_for_an_installed_shape(self):
589        self.publish("0.1.59")
590        ctx = updater.Context(components=self.comp, source=self.url, trusted=signing.load_trusted_keys(), hardware=self.hw)
591        feed = feedmod.fetch(self.url, ctx.trusted)
592        self.assertEqual(updater._shape_steps(ctx, feed, True), [], "nothing installed: no step, an update never installs a shape engine by itself")
593        with mock.patch.object(shape_engine, "_test_start", return_value=(True, "x")):
594            self.assertIsNotNone(self.ensure())
595            self.publish("0.1.59", "0.1.60", sequence=2)
596            feed = feedmod.fetch(self.url, ctx.trusted)
597            steps = updater._shape_steps(ctx, feed, True)
598            self.assertEqual([name for name, _ in steps], [COMP])
599            self.assertEqual(updater._shape_steps(ctx, feed, False), [])
600            result = steps[0][1]()
601        self.assertEqual((result["status"], result["installed_before"], result["installed_after"], result["shape"]), ("updated", "0.1.59", "0.1.60", SHAPE))
602        self.assertEqual(self.strata_before, tree(self.comp / "engine"))
603
604    def test_run_update_runs_that_step_and_reports_it(self):
605        self.publish("0.1.59")
606        with mock.patch.object(shape_engine, "_test_start", return_value=(True, "x")):
607            self.assertIsNotNone(self.ensure())
608        self.publish("0.1.59", "0.1.60", sequence=2)
609        ctx = updater.Context(components=self.comp, source=self.url, trusted=signing.load_trusted_keys(), hardware=self.hw)
610        with mock.patch.object(shape_engine, "_test_start", return_value=(True, "x")), \
611                mock.patch.object(updater, "update_engine", return_value={"component": "engine", "status": "current", "changed": False}):
612            out = updater.run_update(ctx, control=False)
613        row = next(r for r in out["results"] if r.get("component") == COMP)
614        self.assertEqual((row["status"], row["installed_after"]), ("updated", "0.1.60"))
615        self.assertEqual(out["exit_code"], 0)
616        from strata_cli import update_cmd
617        self.assertEqual(update_cmd._line("Strata-q4-lite", row), "Model engine  Engine for q4_lite updated from 0.1.59 to 0.1.60.")
618
619    def test_the_components_report_lists_a_shape_engine_only_when_there_is_one(self):
620        self.assertNotIn("shapes", ec.status(self.comp))
621        self.publish("0.1.59")
622        with mock.patch.object(shape_engine, "_test_start", return_value=(True, "x")):
623            self.assertIsNotNone(self.ensure())
624        rows = ec.status(self.comp)["shapes"]
625        self.assertEqual([(r["shape"], r["usable"], r["engine"]["shape"]) for r in rows], [(SHAPE, True, SHAPE)])
626        self.assertNotIn("shape", ec.status(self.comp)["engine"], "the Strata engine's own report is what it was")
627
628
629class TitleInLines(Base):
630    """A person reads the model's title ("Qwen4 Lite Test"), not the geometry's name (q4_lite), in every line; the shape stays in the keys, the JSON and `strata components engine`.
631    shape_engine.USE_TITLE is the one switch back."""
632    TITLE = "Qwen4 Lite Test"
633
634    def test_the_fetch_lines_name_the_title(self):
635        self.publish("0.1.59")
636        lines = []
637        with mock.patch.object(shape_engine, "_test_start", return_value=(True, "x")):
638            exe = self.ensure(lines, title=self.TITLE)
639        text = " ".join(lines)
640        self.assertIsNotNone(exe, lines)
641        self.assertIn(f"{self.TITLE} needs its own engine.", text)
642        self.assertIn(f"Engine for {self.TITLE} 0.1.59", text)
643        self.assertNotIn("q4_lite needs", text)
644        self.assertNotIn("for q4_lite", text)
645
646    def test_the_refusals_name_the_title(self):
647        self.publish("0.1.59", shape="q4_mid")
648        lines = []
649        self.assertIsNone(self.ensure(lines, title=self.TITLE))
650        self.assertIn(f"The update feed has no engine for {self.TITLE} for this computer.", " ".join(lines))
651        with mock.patch.object(shape_engine, "_test_start", return_value=(False, "boom")):
652            self.publish("0.1.59")
653            lines = []
654            self.assertIsNone(self.ensure(lines, title=self.TITLE))
655        self.assertIn(f"The engine for {self.TITLE} 0.1.59 was not installed because it did not start correctly (boom).", " ".join(lines))
656
657    def test_a_start_without_the_engine_names_the_title_from_the_run_config(self):
658        with self.assertRaises(shape_engine.ShapeEngineMissing) as ctx:
659            ec.expand("component:strata-q4-lite", {"backend": "cuda", "shape_title": self.TITLE})
660        self.assertTrue(str(ctx.exception).startswith(f"{self.TITLE} needs its own engine"), str(ctx.exception))
661        self.assertNotIn("q4_lite", str(ctx.exception))
662        self.assertEqual(ctx.exception.shape, "q4_lite")
663        with self.assertRaises(shape_engine.ShapeEngineMissing) as ctx:            # a config without a title (an older one): the shape's name
664            ec.expand("component:strata-q4-lite", {"backend": "cuda"})
665        self.assertTrue(str(ctx.exception).startswith("q4_lite needs its own engine"), str(ctx.exception))
666
667    def test_the_explicit_update_finds_the_title_in_the_feeds_model(self):
668        self.publish("0.1.59", models=[model_entry(title=self.TITLE)])
669        with mock.patch.object(shape_engine, "_test_start", return_value=(True, "x")):
670            self.assertIsNotNone(self.ensure())
671            self.publish("0.1.59", "0.1.60", sequence=2, models=[model_entry(title=self.TITLE)])
672            ctx = updater.Context(components=self.comp, source=self.url, trusted=signing.load_trusted_keys(), hardware=self.hw)
673            feed = feedmod.fetch(self.url, ctx.trusted)
674            row = updater._shape_steps(ctx, feed, True)[0][1]()
675        self.assertEqual(row["note"], f"Engine for {self.TITLE} updated from 0.1.59 to 0.1.60.")
676        self.assertEqual((row["shape"], row["component"]), ("q4_lite", COMP), "the keys keep the geometry's name")
677        self.assertEqual(shape_engine.title_from_feed(feed, "q4_lite"), self.TITLE)
678        self.assertIsNone(shape_engine.title_from_feed(feed, "q4_mid"))
679
680    def test_one_switch_puts_the_geometry_name_back(self):
681        self.publish("0.1.59")
682        lines = []
683        with mock.patch.object(shape_engine, "USE_TITLE", False), mock.patch.object(shape_engine, "_test_start", return_value=(True, "x")):
684            self.assertIsNotNone(self.ensure(lines, title=self.TITLE))
685        self.assertIn("q4_lite needs its own engine.", " ".join(lines))
686        self.assertNotIn(self.TITLE, " ".join(lines))
687        self.assertEqual(shape_engine.shown("q4_lite", self.TITLE), self.TITLE)
688        self.assertEqual(shape_engine.shown("q4_lite", None), "q4_lite")
689        self.assertEqual(shape_engine.shown("q4_lite", "  "), "q4_lite")
690
691    def test_the_components_report_keeps_the_geometry_name(self):
692        self.publish("0.1.59")
693        with mock.patch.object(shape_engine, "_test_start", return_value=(True, "x")):
694            self.assertIsNotNone(self.ensure(title=self.TITLE))
695        self.assertEqual([r["shape"] for r in ec.status(self.comp)["shapes"]], ["q4_lite"])
696
697
698class ApprovedWords(unittest.TestCase):
699    """The owner approved these exact lines (11-08, "A ok"). {model} is the model's title. A change of a word is a change of this test, which the owner approves first."""
700
701    def test_the_lines_are_the_approved_ones(self):
702        W, M = shape_engine.WORDS, "Q4 Lite Shape"
703        self.assertEqual(W["checking"].format(model=M), "Checking the engine for Q4 Lite Shape…")
704        self.assertEqual(W["fetching"].format(model=M), "Q4 Lite Shape needs its own engine. It downloads separately, and the Strata engine stays as it is.")
705        self.assertEqual(W["installed"].format(model=M, version="0.1.59", backend="cuda"), "Engine for Q4 Lite Shape 0.1.59 (cuda) is installed.")
706        self.assertEqual(W["ready"], W["installed"])
707        self.assertEqual(W["updated"].format(model=M, old="0.1.59", new="0.1.60"), "Engine for Q4 Lite Shape updated from 0.1.59 to 0.1.60.")
708        self.assertEqual(W["not_in_feed"].format(model=M), "The update feed has no engine for Q4 Lite Shape for this computer.")
709        self.assertEqual(W["start_failed"].format(model=M, version="0.1.59", why="no library"),
710                         "The engine for Q4 Lite Shape 0.1.59 was not installed because it did not start correctly (no library). The Strata engine is unchanged.")
711        self.assertEqual(W["fetch_failed"].format(model=M, why="no network"), "The engine for Q4 Lite Shape could not be downloaded: no network")
712        self.assertEqual(W["newer_failed"].format(model=M, why="bad hash", have="0.1.59"),
713                         "A newer engine for Q4 Lite Shape is available but could not be installed (bad hash). Still using 0.1.59.")
714        self.assertEqual(W["missing"].format(model=M, reason="nothing matched"),
715                         "Q4 Lite Shape needs its own engine, which is not installed or does not fit this PC: nothing matched. Run `strata launch` again, or Download / repair in "
716                         "the app, to fetch it. Starting a model never downloads an engine.")
717        self.assertEqual(W["setup_failed"].format(model=M), "the engine for Q4 Lite Shape could not be installed")
718        self.assertEqual(W["setup_failed_hint"], "See the line above. Nothing was downloaded for the model. Run this again when the update feed has it.")
719        self.assertEqual(W["setup_ok"].format(model=M, version="0.1.59", folder="/x/y"), "engine for Q4 Lite Shape: 0.1.59 in /x/y")
720        self.assertEqual(W["update_label"], "Model engine")
721
722    def test_no_reasons_or_platform_names_reach_the_lines(self):
723        """The reasons list and the platform-backend stay in the result rows (and the JSON), not in the line a person reads."""
724        pkgs = [p for p in feedmod.parse(json.dumps({"schema_version": 1, "channel": "stable", "generated_at": "2026-11-08T00:00:00Z", "sequence": 1,
725                                                     "shape_engines": {"packages": [dict(shape="q4_mid", version="0.1.59", platform="linux-x86_64", backend="cuda", variant="", archs=["sm_86"],
726                                                                                         min_driver={}, min_runtime=None, build_id="b", format="tar.gz", url="x", size=1, sha256="a" * 64,
727                                                                                         manifest_sha256="b" * 64, installed_bytes=1)]}}).encode(), source="s", key_id="k").shape_engines]
728        feed = mock.Mock(shape_engines=pkgs, models=())
729        ctx = mock.Mock(components=Path(tempfile.mkdtemp()), hardware={"platform": host_platform(), "backend": "cuda"})
730        row = shape_engine.update_one(ctx, feed, "q4_lite", title="Q4 Lite Shape")
731        self.assertEqual(row["note"], "The update feed has no engine for Q4 Lite Shape for this computer.")
732        self.assertTrue(row["reasons"], "the reasons are in the row")
733        self.assertEqual((row["shape"], row["component"]), ("q4_lite", "strata-q4-lite"))
734
735
736class NoAcquisitionOnStart(unittest.TestCase):
737    def test_only_setup_launch_and_the_explicit_update_fetch_a_shape_engine(self):
738        """Starting and serving never download: the code that fetches (shape_engine.ensure / update_one) is called from setup.py, the Terminal's launch and the updater only."""
739        allowed = {"setup.py", "strata_cli/launch/runner.py", "strata_control/updater.py", "strata_control/shape_engine.py"}
740        found = set()
741        for folder in ("serve", "strata_cli", "strata_control"):
742            for p in (ROOT / folder).rglob("*.py"):
743                if p.name.startswith("test_"):
744                    continue
745                text = p.read_text(encoding="utf-8")
746                if "shape_engine.ensure(" in text or "shape_engine.update_one(" in text or "update_one(ctx" in text:
747                    found.add(p.relative_to(ROOT).as_posix())
748        for p in (ROOT / "strata.py", ROOT / "setup.py"):
749            if "shape_engine.ensure(" in p.read_text(encoding="utf-8"):
750                found.add(p.relative_to(ROOT).as_posix())
751        self.assertEqual(sorted(found - allowed), [])
752        self.assertTrue(found, "the scan found nothing: the check is broken")
753
754    def test_resolving_a_shape_engine_for_a_start_reaches_no_network_code(self):
755        code = ("import sys\nsys.path.insert(0, %r)\nfrom strata_control import engine_component as ec\n"
756                "try:\n    ec.expand('component:strata-q4-lite', {})\nexcept ec.EngineMissing:\n    pass\n"
757                "bad = [m for m in ('strata_control.updater', 'strata_control.transfer', 'urllib.request') if m in sys.modules]\nprint(bad)\n" % str(ROOT))
758        out = subprocess.run([sys.executable, "-I", "-c", code], capture_output=True, text=True, env={**os.environ, "STRATA_COMPONENTS_DIR": tempfile.mkdtemp()})
759        self.assertEqual(out.stdout.strip(), "[]", out.stdout + out.stderr)
760
761
762class OlderControls(Base):
763    """A Control from before the member reads the same feed as one without it, and never offers the model."""
764
765    def _old_feed_module(self, ref: str):
766        shown = subprocess.run(["git", "-C", str(ROOT), "show", f"{ref}:strata_control/feed.py"], capture_output=True)
767        if shown.returncode != 0:
768            self.skipTest(f"{ref} is not in this clone")
769        path = self.root / f"feed_{ref.replace('.', '_')}.py"
770        path.write_bytes(shown.stdout)
771        spec = importlib.util.spec_from_file_location(path.stem, path)
772        mod = importlib.util.module_from_spec(spec)
773        sys.modules[path.stem] = mod
774        try:
775            spec.loader.exec_module(mod)
776        finally:
777            sys.modules.pop(path.stem, None)
778        return mod
779
780    def _check(self, ref: str, has_models: bool):
781        old = self._old_feed_module(ref)
782        self.publish("0.1.59", models=[model_entry()])
783        payload = (self.release / feedmod.FEED_NAME).read_bytes()
784        new = feedmod.parse(payload, source="s", key_id="k")
785        before = old.parse(json.dumps({k: v for k, v in json.loads(payload).items() if k not in ("shape_engines", "models")}).encode(), source="s", key_id="k")
786        got = old.parse(payload, source="s", key_id="k")
787        self.assertEqual(got.engine, before.engine, "no shape engine is ever an engine for an older Control")
788        self.assertEqual(got.dsv41, before.dsv41)
789        self.assertEqual((got.sequence, got.channel, got.app, got.control), (before.sequence, before.channel, before.app, before.control))
790        self.assertEqual(len(new.shape_engines), 1)
791        if has_models:
792            (m,) = got.models
793            self.assertEqual(m.family, "qwen4exp_q4_lite")
794            self.assertNotIn(m.family, old.MODEL_FAMILIES_INSTALLABLE, "a family an older Control does not know is never offered to install")
795        else:
796            self.assertFalse(hasattr(got, "models"))
797
798    def test_the_control_before_this_one_reads_the_feed_and_does_not_offer_the_model(self):
799        self._check("3289d8280", True)
800
801    def test_control_0211_ignores_the_new_members(self):
802        self._check("v0.2.11", False)
803
804    def test_an_older_scan_does_not_see_the_shape_engine_even_in_its_own_folder_layout(self):
805        self.publish("0.1.59")
806        with mock.patch.object(shape_engine, "_test_start", return_value=(True, "x")):
807            self.assertIsNotNone(self.ensure())
808        # an older Control scans <components>/engine only, and reads strata-engine manifests only
809        found, problems = ec.scan(self.comp)
810        self.assertEqual([c.version for c in found], ["0.1.58"])
811        self.assertEqual(problems, [])
812        shape_folder = next((self.comp / "shapes" / SHAPE / "engine").iterdir())
813        with self.assertRaises(ec.ComponentProblem):
814            ec.read_manifest(shape_folder)
815
816
817class EveryEngineProgramAnswersTheShapeFlags(unittest.TestCase):
818    """`strata --geometry` and `strata --families` are answered by every engine program before any device is touched: the CUDA/HIP/Metal
819    program (src/program/generate.cpp) and the Intel one (sycl/src/program/generate.cpp, its own program). Without them a SYCL shape engine
820    was installed with no geometry check (an engine that does not know the flag is accepted as one from before it)."""
821
822    PROGRAMS = ("src/program/generate.cpp", "sycl/src/program/generate.cpp")
823
824    def _early_block(self, rel):
825        src = (ROOT / rel).read_text(encoding="utf-8")
826        start = src.index('std::strcmp(argv[i], "--version") == 0')
827        end = src.index("\n    }\n", start)            # the end of the early `for (int i = 1; i < argc && i < 3; ++i)` loop
828        return src[start:end]
829
830    def test_both_flags_are_in_the_early_loop_of_every_program(self):
831        for rel in self.PROGRAMS:
832            with self.subTest(program=rel):
833                block = self._early_block(rel)
834                self.assertIn('std::strcmp(argv[i], "--geometry") == 0', block)
835                self.assertIn('std::printf("%s\\n", strata::core::kGeometryName);', block)
836                self.assertIn('std::strcmp(argv[i], "--families") == 0', block)
837                self.assertIn('std::printf("qwen4exp\\n");', block)
838
839    def test_the_intel_program_names_no_qwen35_family(self):
840        block = self._early_block("sycl/src/program/generate.cpp")
841        printed = [ln for ln in block.splitlines() if "std::printf(" in ln]
842        self.assertFalse([ln for ln in printed if "qwen35moe" in ln], "the Intel engine has no qwen35moe path")
843
844
845if __name__ == "__main__":
846    unittest.main()