okami.mom/strata

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

Niko1221Merge f-par-df2 f4accc5f4 into the batch 16 candidate (parallel requests with the second drafter)9a62d969f

main
66.6 KiB1061 linesraw
1"""Which drafter a model uses (MTP, DFlash2 or none): the suggestion table, the Terminal flag, the engine arguments, the download and the
2fallback words. strata_control/drafting.py is the one place; the Terminal and the app read it."""
3
4from __future__ import annotations
5
6import http.server
7import importlib.util
8import json
9import sys
10import tempfile
11import threading
12import unittest
13from pathlib import Path
14from unittest import mock
15
16from strata_cli.launch import settings as S
17from strata_cli.launch.runner import derive_config
18from strata_control import acquisition, drafting, drafting_fetch
19from tests.terminal.launch_support import run_cli
20
21ROOT = Path(__file__).resolve().parents[2]
22GYRO = "qwen3.8-flash-next-gyro-gyro-s"
23_HARDWARE = mock.patch.object(drafting, "detect_hardware", return_value=("cuda", ["sm_120"]))
24
25
26def setUpModule():
27    """These tests are about the table, the flags and the download, on a computer whose engine can run DFlash2 (the box that runs them may have an Intel or no card;
28    tests/terminal/test_drafting_hardware.py has the hardware matrix)."""
29    _HARDWARE.start()
30
31
32def tearDownModule():
33    _HARDWARE.stop()
34
35
36def serving_dflash2():
37    """The tests turn the switch on explicitly (drafting.ENGINE_SERVES_DFLASH2)."""
38    return mock.patch.object(drafting, "ENGINE_SERVES_DFLASH2", True)
39
40
41class AutoAndTheBackends(unittest.TestCase):
42    def test_auto_is_dflash2_where_the_engine_has_it(self):
43        """Owner 2026-11-02: DFlash2 is the primary drafter on every system whose engine has it (CUDA, HIP, Metal, Intel SYCL since the DF2-SYCL engine)."""
44        self.assertEqual(drafting.DFLASH2_BACKENDS, ("cuda", "hip", "metal", "sycl"))
45        for backend in ("cuda", "hip", "metal", "sycl"):
46            for family in ("qwen", "gyro", "unsloth"):
47                self.assertEqual(drafting.choice_of("auto", family=family, backend=backend), "dflash2", (backend, family))
48        self.assertEqual(drafting.choice_of("auto", family="qwen", backend=None), "mtp", "an unknown computer is the MTP")
49        self.assertEqual(drafting.choice_of("auto", family="qwen", backend="cpu"), "mtp", "an engine without the code is the MTP")
50        for family in ("coder", "swift", "nvfp4", "deepseek41"):
51            self.assertEqual(drafting.choice_of("auto", family=family, backend="cuda"), "mtp", family)
52
53    def test_intel_runs_dflash2_and_a_build_without_the_code_does_not(self):
54        self.assertTrue(drafting.hardware_support("sycl", ["8086"]).can_run)
55        with mock.patch.object(drafting, "DFLASH2_BACKENDS", ("cuda", "hip", "metal")):
56            self.assertEqual(drafting.choice_of("auto", family="qwen", backend="sycl"), "mtp")
57            self.assertFalse(drafting.hardware_support("sycl").can_run)
58
59    def test_the_choice_is_the_choice(self):
60        for backend in ("cuda", "sycl"):
61            self.assertEqual(drafting.choice_of("mtp", family="qwen", backend=backend), "mtp")
62            self.assertEqual(drafting.choice_of("off", family="qwen", backend=backend), "off")
63        self.assertEqual(drafting.choice_of("dflash2", family="qwen", backend="cuda"), "dflash2")
64        self.assertEqual(drafting.choice_of("dflash2", family="qwen", backend="sycl"), "dflash2")
65        self.assertEqual(drafting.choice_of("dflash2", family="qwen", backend="cpu"), "mtp", "named, but the engine has none")
66        self.assertEqual(drafting.choice_of("dflash2", family="coder", backend="cuda"), "mtp")
67
68    def test_the_two_drafters_have_their_own_memory_figure(self):
69        self.assertEqual((drafting.DRAFTER_GB["dflash2"], drafting.DRAFTER_GB["mtp"], drafting.DRAFTER_GB["off"]), (0.89, 1.08, 0.0))
70        self.assertEqual(drafting.VRAM_GB, 0.89)
71
72    def test_cards_are_classified_by_their_architecture(self):
73        self.assertEqual(drafting.card_class(["sm_120"]), "blackwell")
74        self.assertEqual(drafting.card_class(["gfx1151"]), "strix_halo")
75        self.assertEqual(drafting.card_class(["gfx1201"]), "rdna4")
76        self.assertEqual(drafting.card_class(["sm_86"]), "ampere")
77        self.assertEqual(drafting.card_class([]), "other")
78        self.assertEqual(drafting.card_class("SM_120"), "blackwell")
79
80    def test_both_sides_know_the_same_modes(self):
81        self.assertEqual(drafting.MODES, S.DRAFTING_MODES)
82        self.assertEqual(drafting.normalize(None), "auto")
83        self.assertEqual(drafting.normalize("DFlash2"), "dflash2")
84        self.assertEqual(drafting.normalize("fastest"), "auto", "an unknown value is Auto, never an error")
85
86
87class Decisions(unittest.TestCase):
88    def setUp(self):
89        self.tmp = tempfile.TemporaryDirectory()
90        self.data = Path(self.tmp.name)
91        self.addCleanup(self.tmp.cleanup)
92
93    def ready(self):
94        pack = drafting.pack_path(self.data)
95        pack.parent.mkdir(parents=True)
96        pack.write_bytes(b"x" * (2 << 20))
97
98    def decide(self, mode, **kw):
99        return drafting.decide(mode, model_name=GYRO, data_dir=self.data, backend="cuda", archs=["sm_120"], **kw)
100
101    def test_auto_and_dflash2_run_dflash2_alone_when_the_pack_is_here(self):
102        self.ready()
103        for mode in ("auto", "dflash2", None):
104            d = self.decide(mode)
105            self.assertEqual((d.drafter, d.note), ("dflash2", ""), mode)
106            self.assertEqual(d.flags, ("--draft", "dflash2", "--draft-model", str(drafting.pack_path(self.data)), "--draft-fallback", "none",
107                                       "--spec", "6", "--draft-conf", "0.35"), "no --mtp, and the engine is told there is no fallback")
108        self.assertNotIn("--mtp", self.decide("auto").flags)
109
110    def test_mtp_is_the_mtp_with_no_dflash2_flag(self):
111        d = self.decide("mtp")
112        self.assertEqual((d.drafter, d.flags, d.note), ("mtp", (), ""))
113
114    def test_off_is_off(self):
115        self.assertEqual(self.decide("off").drafter, "off")
116
117    def test_no_pack_and_the_mtp_layer_here_runs_the_mtp_and_says_so(self):
118        d = self.decide("auto", mtp_here=True)
119        self.assertEqual((d.drafter, d.note), ("mtp", drafting.NOT_DOWNLOADED))
120        self.assertTrue(drafting.needs_pack("auto", model_name=GYRO, data_dir=self.data, backend="cuda"))
121
122    def test_no_pack_and_no_mtp_layer_runs_none_and_says_so(self):
123        d = self.decide("dflash2", mtp_here=False)
124        self.assertEqual((d.drafter, d.note, d.flags), ("off", drafting.NONE_HERE, ()))
125        self.assertEqual(drafting.line(d.drafter, d.note), "Drafting: off (no drafter is downloaded yet)")
126
127    def test_mtp_chosen_without_its_layer_runs_dflash2_if_it_is_here_else_none(self):
128        d = self.decide("mtp", mtp_here=False)
129        self.assertEqual((d.drafter, d.note), ("off", drafting.NONE_HERE))
130        self.ready()
131        d = self.decide("mtp", mtp_here=False)
132        self.assertEqual((d.drafter, d.note), ("dflash2", drafting.NO_MTP))
133        self.assertEqual(drafting.line(d.drafter, d.note), "Drafting: DFlash2 (the MTP drafter isn't downloaded yet)")
134        self.assertTrue(drafting.needs_mtp("mtp", model_name=GYRO, backend="cuda", mtp_here=False), "the switch fetches the layer once")
135        self.assertFalse(drafting.needs_mtp("mtp", model_name=GYRO, backend="cuda", mtp_here=True))
136        self.assertFalse(drafting.needs_mtp("auto", model_name=GYRO, backend="cuda", mtp_here=False), "Auto is DFlash2: it needs no layer")
137
138    def test_several_requests_at_once_load_only_the_mtp_and_say_so(self):
139        self.ready()
140        d = self.decide("dflash2", mtp_here=True, blocked=True)
141        self.assertEqual((d.drafter, d.note, d.flags), ("mtp", drafting.NOT_HERE, ()))
142        d = self.decide("auto", mtp_here=True, blocked=True)
143        self.assertEqual((d.drafter, d.note), ("mtp", drafting.NOT_HERE), "Auto says it too: nothing changes silently")
144        self.assertTrue(drafting.blocked_by([], slots=4))
145        self.assertTrue(drafting.blocked_by(["--batch", "4"]) and drafting.blocked_by(["--pipeline-windows", "2"]))
146        # DFlash2 chosen by name (owner 2026-11-03: the person's own choice wins): several requests are their word too, only --pipeline-windows still blocks
147        for args, kw in (([], {"slots": 4}), (["--batch", "4"], {}), (["--slots", "2"], {}), (["--parallel", "3"], {}), (["--batch", "4"], {"slots": 4, "split": True})):
148            self.assertFalse(drafting.blocked_by(args, named=True, **kw), (args, kw))
149            self.assertTrue(drafting.blocked_by(args, **kw), (args, kw, "Auto and the MTP keep their rule"))
150        self.assertTrue(drafting.blocked_by(["--pipeline-windows", "2"], named=True), "the MTP's speculative next window has no DFlash2 counterpart")
151        self.assertFalse(drafting.blocked_by([], split=True), "a layer split over several cards runs DFlash2 (owner 2026-11-02; the 0.1.56 engine does)")
152        self.assertFalse(drafting.blocked_by(["--layer-split", "auto"]))
153        self.assertFalse(drafting.blocked_by(["--spec", "4"], slots=1))
154
155    def test_dflash2_is_for_qwen38_flash_next_only(self):
156        self.ready()
157        for name in ("qwen3.6-35b-a3b-q4", "qwen3.8-flash-next-coder-iq3_xxs", "qwen3.8-flash-next-swift-iq2_xs", None):
158            d = drafting.decide("dflash2", model_name=name, data_dir=self.data, backend="cuda")
159            self.assertEqual((d.drafter, d.note), ("mtp", drafting.NOT_SUPPORTED), name)
160            self.assertFalse(drafting.needs_pack("dflash2", model_name=name, data_dir=self.data, backend="cuda"))
161            self.assertEqual(drafting.decide("auto", model_name=name, data_dir=self.data, backend="cuda").note, "", "Auto never nags about a model DFlash2 is not for")
162        for name in (GYRO, "qwen3.8-flash-next-q2_0", "qwen3.8-flash-next-iq3_xxs"):
163            self.assertEqual(drafting.decide("dflash2", model_name=name, data_dir=self.data, backend="cuda").drafter, "dflash2", name)
164        self.assertTrue(drafting.supported_model(family="qwen") and drafting.supported_model(family="gyro"))
165        self.assertFalse(drafting.supported_model(family="coder") or drafting.supported_model(family="swift") or drafting.supported_model(family="nvfp4"))
166
167    def test_the_engine_of_this_branch_serves_dflash2(self):
168        self.assertTrue(drafting.ENGINE_SERVES_DFLASH2, "src/program/generate.cpp: --draft dflash2 runs with --serve (one card, one request at a time)")
169
170    def test_while_the_engine_cannot_serve_it_the_choice_says_so_and_nothing_is_downloaded(self):
171        with mock.patch.object(drafting, "ENGINE_SERVES_DFLASH2", False):
172            d = self.decide("dflash2")
173            self.assertEqual((d.drafter, d.note), ("mtp", drafting.NOT_SERVED))
174            self.assertFalse(drafting.needs_pack("dflash2", model_name=GYRO, data_dir=self.data, backend="cuda"))
175            self.assertEqual(self.decide("auto").note, "")
176            self.assertEqual(self.decide("auto").drafter, "mtp")
177
178    def test_intel_is_dflash2_and_fetches_its_pack(self):
179        self.assertTrue(drafting.needs_pack("auto", model_name=GYRO, data_dir=self.data, backend="sycl"))
180        d = drafting.decide("auto", model_name=GYRO, data_dir=self.data, backend="sycl")
181        self.assertEqual(d.drafter, "mtp", "the pack is not downloaded yet: the MTP until it is")
182        d = drafting.decide("auto", model_name=GYRO, data_dir=self.data, backend="cpu")
183        self.assertEqual((d.drafter, d.note), ("mtp", ""))
184        self.assertFalse(drafting.needs_pack("auto", model_name=GYRO, data_dir=self.data, backend="cpu"))
185
186
187class EngineArguments(unittest.TestCase):
188    ARGS = ["--pack", "/d/packs/gyro", "--native", "/d/m.gguf", "--mtp", "/d/mtp/rt", "--spec", "4", "--spec-min-p", "0.5"]
189
190    def setUp(self):
191        self.tmp = tempfile.TemporaryDirectory()
192        self.data = Path(self.tmp.name)
193        self.addCleanup(self.tmp.cleanup)
194        self.vocab = self.data / "draft_vocab.bin"
195        self.vocab.write_bytes(b"v")
196        self.mtp = self.data / "mtp" / "rt"
197        self.args = ["--pack", "/d/packs/gyro", "--native", "/d/m.gguf", "--mtp", str(self.mtp), "--spec", "4", "--spec-min-p", "0.5"]
198
199    def layer(self):
200        self.mtp.mkdir(parents=True)
201        (self.mtp / "experts.bin").write_bytes(b"e")
202        (self.mtp / "draft_vocab.bin").write_bytes(b"v")
203
204    def pack(self):
205        pack = drafting.pack_path(self.data)
206        pack.parent.mkdir(parents=True)
207        pack.write_bytes(b"x" * (2 << 20))
208        return pack
209
210    def cfg(self, **extra):
211        return {"model_name": GYRO, "args": list(self.args), **extra}
212
213    def apply(self, cfg, **kw):
214        return drafting.apply(cfg, data_dir=self.data, backend="cuda", archs=["sm_120"], **kw)
215
216    def test_dflash2_alone_has_no_mtp_option_and_says_there_is_no_fallback(self):
217        pack = self.pack()
218        self.layer()
219        for drafting_mode in ("dflash2", "auto", None):
220            c = self.cfg(args=[*self.args, "--batch-mtp", "--mtp-q4", "all"], **({} if drafting_mode is None else {"drafting": drafting_mode}))
221            d = self.apply(c)
222            self.assertEqual(d.drafter, "dflash2", drafting_mode)
223            a = c["args"]
224            for flag in ("--mtp", "--spec-min-p", "--batch-mtp", "--mtp-q4", "--draft-mtp-spec"):
225                self.assertNotIn(flag, a, (drafting_mode, flag))
226            self.assertEqual(a[a.index("--draft") + 1], "dflash2")
227            self.assertEqual(a[a.index("--draft-model") + 1], str(pack))
228            self.assertEqual(a[a.index("--draft-fallback") + 1], "none")
229            self.assertEqual(a[a.index("--mtp-draft-vocab") + 1], str(self.mtp / "draft_vocab.bin"), "the subset the person chose in setup")
230            self.assertEqual((a[a.index("--spec") + 1], a[a.index("--draft-conf") + 1]), ("6", "0.35"))
231            self.assertEqual(a.count("--spec"), 1)
232
233    def test_dflash2_alone_works_when_no_mtp_layer_was_ever_downloaded(self):
234        self.pack()
235        with mock.patch.object(drafting, "vocab_path", return_value=self.vocab):
236            c = self.cfg(drafting="dflash2")
237            d = self.apply(c)
238        self.assertEqual((d.drafter, d.note), ("dflash2", ""))
239        self.assertEqual(c["args"][c["args"].index("--mtp-draft-vocab") + 1], str(self.vocab), "Strata's own default subset")
240        self.assertNotIn("--mtp", c["args"])
241
242    def test_mtp_has_no_dflash2_option(self):
243        self.pack()
244        self.layer()
245        c = self.cfg(drafting="mtp", args=[*self.args, "--draft", "dflash2", "--draft-model", "/p", "--draft-fallback", "mtp", "--draft-conf", "0.3", "--draft-mtp-spec", "4",
246                                          "--draft-cap", "5", "--draft-rule", "df2"])
247        d = self.apply(c)
248        self.assertEqual((d.drafter, c["args"]), ("mtp", self.args), "exactly the MTP's own arguments")
249
250    def test_a_config_that_names_both_starts_with_the_one_chosen(self):
251        pack = self.pack()
252        self.layer()
253        both = [*self.args, "--draft", "dflash2", "--draft-model", str(pack), "--draft-fallback", "mtp", "--spec", "6"]
254        mtp = self.cfg(drafting="mtp", args=list(both))
255        self.apply(mtp)
256        self.assertEqual(mtp["args"].count("--mtp"), 1)
257        self.assertNotIn("--draft", mtp["args"])
258        two = self.cfg(drafting="dflash2", args=list(both))
259        self.apply(two)
260        self.assertNotIn("--mtp", two["args"])
261        self.assertEqual(two["args"][two["args"].index("--draft-fallback") + 1], "none")
262        self.assertEqual(two["args"].count("--draft-fallback"), 1)
263        # Auto picks DFlash2 for it
264        auto = self.cfg(args=list(both))
265        self.apply(auto)
266        self.assertNotIn("--mtp", auto["args"])
267        self.assertEqual(auto["args"][auto["args"].index("--draft") + 1], "dflash2")
268
269    def test_the_persons_own_spec_and_conf_stay(self):
270        self.pack()
271        self.layer()
272        c = self.cfg(drafting="dflash2", args=[*self.args[:self.args.index("--spec")], "--spec", "5"], user_args=["--spec", "5", "--draft-conf", "0.2"])
273        self.apply(c)
274        self.assertEqual((c["args"][c["args"].index("--spec") + 1], c["args"].count("--spec"), c["args"][c["args"].index("--draft-conf") + 1]), ("5", 1, "0.2"))
275
276    def test_parallel_with_auto_loads_only_the_mtp_and_says_so(self):
277        self.pack()
278        self.layer()
279        for kw in ({"slots": 4},):
280            c = self.cfg()                                   # Auto: unchanged, the MTP for several requests
281            d = self.apply(c, **kw)
282            self.assertEqual((d.drafter, d.note), ("mtp", drafting.NONE_IN_SLOTS), kw)
283            self.assertEqual(c["args"], self.args, kw)
284            c = self.cfg(drafting="mtp")                     # the MTP chosen: unchanged
285            d = self.apply(c, **kw)
286            self.assertEqual((d.drafter, d.note), ("mtp", ""), kw)
287            self.assertEqual(c["args"], self.args, kw)
288
289    def test_dflash2_chosen_by_name_keeps_dflash2_for_the_requests_the_person_chose(self):
290        """Owner 2026-11-03: DFlash2 chosen + a number of requests chosen = DFlash2 with that many (the engine runs a drafter per request)."""
291        self.pack()
292        self.layer()
293        for kw in ({"slots": 2}, {"slots": 4}, {"slots": 8}):
294            c = self.cfg(drafting="dflash2")
295            d = self.apply(c, **kw)
296            self.assertEqual((d.drafter, d.note), ("dflash2", ""), kw)
297            a = c["args"]
298            self.assertEqual((a[a.index("--draft") + 1], a[a.index("--draft-fallback") + 1]), ("dflash2", "none"), kw)
299            self.assertNotIn("--mtp", a)
300            self.assertNotIn("--batch-mtp", a, "the MTP's slot switch is the MTP's; the slot drafts are the engine's default for --draft dflash2 --batch")
301        # the number in the arguments themselves (Expert mode / the saved --batch) is the same word
302        c = self.cfg(drafting="dflash2", args=[*self.args, "--batch", "4", "--batch-mtp"])
303        d = self.apply(c)
304        self.assertEqual((d.drafter, d.note), ("dflash2", ""))
305        self.assertEqual(c["args"][c["args"].index("--batch") + 1], "4")
306        self.assertNotIn("--batch-mtp", c["args"])
307        # on a layer split too
308        c = self.cfg(drafting="dflash2")
309        self.assertEqual(self.apply(c, split=True, slots=4).drafter, "dflash2")
310        # one request (1, or none given) was always DFlash2
311        for kw in ({"slots": 0}, {"slots": 1}):
312            self.assertEqual(self.apply(self.cfg(drafting="dflash2"), **kw).drafter, "dflash2", kw)
313        # --pipeline-windows is the one thing that still keeps it out
314        c = self.cfg(drafting="dflash2", args=[*self.args, "--pipeline-windows", "2"])
315        d = self.apply(c, slots=4)
316        self.assertEqual((d.drafter, d.note), ("mtp", drafting.NOT_HERE))
317
318    def test_no_pack_no_internet_runs_the_mtp_when_it_is_here_else_none(self):
319        self.layer()
320        c = self.cfg(drafting="dflash2")
321        d = self.apply(c)
322        self.assertEqual((d.drafter, d.note, c["args"]), ("mtp", drafting.NOT_DOWNLOADED, self.args))
323        self.mtp.joinpath("experts.bin").unlink()
324        c = self.cfg(drafting="dflash2")
325        d = self.apply(c)
326        self.assertEqual((d.drafter, d.note), ("off", drafting.NONE_HERE))
327        for flag in ("--mtp", "--draft", "--spec-min-p"):
328            self.assertNotIn(flag, c["args"])
329
330    def test_the_mtp_switch_off_with_no_drafter_chosen_since_means_no_drafter(self):
331        self.pack()
332        self.layer()
333        c = self.cfg(mtp=False)
334        self.assertEqual(self.apply(c).drafter, "off")
335        c = self.cfg(mtp=False, drafting="dflash2")
336        self.assertEqual(self.apply(c).drafter, "dflash2", "a drafter chosen by name is the person's later word")
337
338    def test_another_model_is_left_alone(self):
339        c = self.cfg(model_name="qwen3.8-flash-next-coder-iq3_xxs")
340        d = self.apply(c)
341        self.assertEqual((d.drafter, d.note, c["args"]), ("mtp", "", self.args))
342        c = self.cfg(model_name="qwen3.8-flash-next-coder-iq3_xxs", drafting="dflash2", args=[*self.args, "--draft", "dflash2", "--draft-model", "/p"])
343        d = self.apply(c)
344        self.assertEqual((d.drafter, d.note, c["args"]), ("mtp", drafting.NOT_SUPPORTED, self.args))
345
346    def test_intel_gets_its_own_confidence_not_the_cuda_slot_steps(self):
347        self.layer()
348        self.pack()
349        for vram in (None, 8000, 24000, 96000):
350            c = self.cfg()
351            d = drafting.apply(c, data_dir=self.data, backend="sycl", archs=[], vram_mib=vram)
352            a = c["args"]
353            self.assertEqual((d.drafter, a[a.index("--draft-conf") + 1], a[a.index("--spec") + 1], "--mtp" in a, a[a.index("--draft-fallback") + 1]), ("dflash2", "0.6", "6", False, "none"), vram)
354        c = self.cfg(user_args=["--draft-conf", "0.5"], args=[*self.args, "--draft-conf", "0.5"])
355        drafting.apply(c, data_dir=self.data, backend="sycl", archs=[], vram_mib=8000)
356        self.assertEqual(c["args"][c["args"].index("--draft-conf") + 1], "0.5", "the person's own value stays")
357        c = self.cfg()
358        drafting.apply(c, data_dir=self.data, backend="cuda", archs=["sm_120"], vram_mib=8000)
359        self.assertEqual(c["args"][c["args"].index("--draft-conf") + 1], "0.8", "CUDA keeps its slot steps")
360
361    def test_a_mac_gets_its_own_confidence_not_the_cuda_slot_steps(self):
362        """Metal maps every expert: the --expert-cache 64 the Mac setup writes is a slot count of 83 to the CUDA steps (0.8), which was not measured on a Mac; M5 Max measured 0.5."""
363        self.layer()
364        self.pack()
365        for vram in (None, 8000, 96000):
366            c = self.cfg()
367            d = drafting.apply(c, data_dir=self.data, backend="metal", archs=[], vram_mib=vram)
368            a = c["args"]
369            self.assertEqual((d.drafter, a[a.index("--draft-conf") + 1], a[a.index("--spec") + 1], "--mtp" in a, a[a.index("--draft-fallback") + 1]), ("dflash2", "0.5", "6", False, "none"), vram)
370        c = self.cfg(user_args=["--draft-conf", "0.4"], args=[*self.args, "--draft-conf", "0.4"])
371        drafting.apply(c, data_dir=self.data, backend="metal", archs=[])
372        self.assertEqual(c["args"][c["args"].index("--draft-conf") + 1], "0.4", "the person's own value stays")
373
374    def test_off_is_the_draft_layers_own_switch(self):
375        c = self.cfg(drafting="off")
376        d = self.apply(c)
377        self.assertEqual(d.drafter, "off")
378        self.assertIs(c["mtp"], False)
379        for flag in ("--mtp", "--spec-min-p", "--batch-mtp", "--draft"):
380            self.assertNotIn(flag, c["args"])
381        self.assertEqual(c["args"][c["args"].index("--spec") + 1], "4", "prompt lookup keeps its windows")
382
383    def test_the_server_applies_it_at_every_start(self):
384        from serve.server import engine_args
385        self.pack()
386        self.layer()
387        with mock.patch("serve.server.drafting_vram_mib", return_value=None), mock.patch.object(drafting, "data_dir_of", return_value=self.data):
388            for kw in ({"drafting": "dflash2"}, {}):          # chosen, and Auto
389                args = engine_args(self.cfg(**kw))
390                self.assertNotIn("--mtp", args)
391                self.assertEqual(args[args.index("--draft") + 1], "dflash2")
392                self.assertEqual(args[args.index("--draft-fallback") + 1], "none")
393            args = engine_args(self.cfg(drafting="mtp"))
394            self.assertEqual(args, self.args)
395            self.assertEqual(engine_args(self.cfg(parallel=4))[:len(self.args)], self.args, "Auto with several requests: the MTP alone")
396            self.assertEqual(drafting.take_note(), drafting.NONE_IN_SLOTS, "the engine that starts next is told why")
397            self.assertEqual(engine_args(self.cfg(drafting="mtp", parallel=4))[:len(self.args)], self.args, "the MTP chosen: unchanged")
398            self.assertEqual(drafting.take_note(), "")
399            # DFlash2 chosen by name with a number of requests the person chose: DFlash2 with that many, no note
400            named = engine_args(self.cfg(drafting="dflash2", parallel=4))
401            self.assertNotIn("--mtp", named)
402            self.assertEqual((named[named.index("--draft") + 1], named[named.index("--draft-fallback") + 1], named[named.index("--batch") + 1]), ("dflash2", "none", "4"))
403            self.assertEqual(drafting.take_note(), "")
404            one = engine_args(self.cfg(drafting="dflash2", parallel=1))
405            self.assertNotIn("--batch", one)
406            self.assertEqual(one[one.index("--draft") + 1], "dflash2")
407        # a 16 GB card holds about 3,700 slots with the drafter on: the server passes its memory and the confidence follows (drafting.CONF_STEPS)
408        with mock.patch("serve.server.drafting_vram_mib", return_value=16384.0), mock.patch.object(drafting, "data_dir_of", return_value=self.data):
409            args = engine_args(self.cfg(drafting="dflash2"))
410            self.assertIn(args[args.index("--draft-conf") + 1], ("0.7", "0.35"))
411            args = engine_args(self.cfg(drafting="dflash2", args=[*self.args, "--expert-cache", "1000"]))
412            self.assertEqual(args[args.index("--draft-conf") + 1], "0.8", "the cache the person asked for decides, not the card")
413        with mock.patch.object(drafting, "ENGINE_SERVES_DFLASH2", False):
414            self.assertEqual(engine_args(self.cfg()), self.args, "the engine cannot serve it: nothing changes")
415            off = engine_args(self.cfg(drafting="off"))
416            self.assertNotIn("--mtp", off)
417            drafting.take_note()
418            engine_args(self.cfg(drafting="dflash2"))
419            self.assertEqual(drafting.take_note(), drafting.NOT_SERVED)
420
421    def test_data_folder_of_an_argument_list(self):
422        self.assertEqual(drafting.data_dir_of(["--pack", "/d/packs/x"]), Path("/d"))
423        self.assertEqual(drafting.data_dir_of(["--mtp", "/d/mtp/rt"]), Path("/d"))
424        self.assertIsNone(drafting.data_dir_of(["--mtp", "4"]))
425        self.assertIsNone(drafting.data_dir_of([]))
426
427    def test_the_engine_takes_the_vocabulary_file_alone(self):
428        """src/program/generate.cpp: --draft dflash2 needs --mtp-draft-vocab FILE or --mtp DIR, and loads no MTP layer either way."""
429        src = (ROOT / "src" / "program" / "generate.cpp").read_text(encoding="utf-8")
430        self.assertIn("(o.mtp.empty() && o.mtp_draft_vocab.empty())", src)
431        self.assertIn('o.draft_fallback != "mtp"', src)
432
433
434class UnslothAndTheOtherFlashNextFiles(unittest.TestCase):
435    """DF2-METAL found that Auto never picked DFlash2 for Unsloth's quantizations: they are the same Qwen3.8-Flash-Next weights and the DFlash2 numbers (Strix, R9700,
436    M5 Max) were measured on UD-Q4_K_XL. Swift (UkisAI's fine-tune) and Coder (ISTA-DASLab's coding version) are fine-tunes with no acceptance numbers: the MTP.
437    The names are the ones setup.py and metal/setup_mac.py write: f"{family name}-{model.lower()}"."""
438
439    UNSLOTH = ("qwen3.8-flash-next-unsloth-ud-q4_k_xl", "qwen3.8-flash-next-unsloth-ud-iq4_xs", "qwen3.8-flash-next-unsloth-ud-q5_k_xl",
440               "qwen3.8-flash-next-unsloth-ud-q6_k_xl", "qwen3.8-flash-next-unsloth-q8_0")
441    FLASH_NEXT = ("qwen3.8-flash-next", "qwen3.8-flash-next-q2_0", "qwen3.8-flash-next-iq2_xs", "qwen3.8-flash-next-iq3_xxs", "qwen3.8-flash-next-iq3_s",
442                  "qwen3.8-flash-next-gyro-gyro-s", "qwen3.8-flash-next-gyro-gyro-m")
443    OTHERS = ("qwen3.8-flash-next-coder-iq1_m", "qwen3.8-flash-next-nvfp4-nvfp4", "qwen3.8-flash-next-nvfp4-nvfp4-nvidia", "qwen3.8-flash-next-nvfp4-nvfp4-qad",
444              "swift-1.5-iq2_xs", "swift-1.5-q4_0", "qwen3.6-35b-a3b-ud-q4_k_xl", "deepseek-v4.1-flash", "qwen3.8-flash-next-unsloth", "qwen3.8-flash-next-unslothx-q8_0")
445    HARDWARE = (("cuda", ["sm_120"]), ("hip", ["gfx1151"]), ("metal", None), ("sycl", ["8086"]))
446
447    def test_the_names_the_setups_write(self):
448        for name in self.UNSLOTH + self.FLASH_NEXT:
449            self.assertTrue(drafting.supported_model(name), name)
450            self.assertTrue(drafting.supported_model(name.upper()), name.upper())
451        for name in self.OTHERS:
452            self.assertFalse(drafting.supported_model(name), name)
453        self.assertTrue(drafting.supported_model(None, "unsloth"))
454        for family in ("swift", "coder", "nvfp4", "qwen36", "deepseek41"):
455            self.assertFalse(drafting.supported_model(None, family), family)
456        self.assertEqual(drafting.SUPPORTED_FAMILIES, ("qwen", "gyro", "unsloth"))
457
458    def test_the_names_are_the_ones_setup_writes(self):
459        """Read from the code, not from memory: the family names and the way setup.py and metal/setup_mac.py make the run config's model_name."""
460        setup = (ROOT / "setup.py").read_text(encoding="utf-8") + (ROOT / "strata_control" / "setup_config.py").read_text(encoding="utf-8")    # (the run config's construction moved to the setup seam)
461        mac = (ROOT / "metal" / "setup_mac.py").read_text(encoding="utf-8")
462        self.assertIn('"name": "qwen3.8-flash-next-unsloth"', setup)
463        self.assertIn('"name": "qwen3.8-flash-next-coder"', setup)
464        self.assertIn('"name": "qwen3.8-flash-next-nvfp4"', setup)
465        self.assertGreaterEqual(setup.count("\"model_name\": f\"{fam['name']}-{model.lower()}\""), 3)
466        self.assertIn("f\"{fam['name']}-{model.lower()}\"", mac)
467        for model in ("UD-IQ4_XS", "UD-Q4_K_XL", "UD-Q5_K_XL", "UD-Q6_K_XL", "Q8_0"):
468            self.assertIn(f'"{model}": {{"about"', setup)
469            self.assertTrue(drafting.supported_model(f"qwen3.8-flash-next-unsloth-{model.lower()}"), model)
470
471    def run_config(self, name, tmp, mode=None):
472        data = Path(tmp)
473        mtp = data / "mtp" / "rt"
474        mtp.mkdir(parents=True)
475        (mtp / "experts.bin").write_bytes(b"e")
476        (mtp / "draft_vocab.bin").write_bytes(b"v")
477        pack = drafting.pack_path(data)
478        pack.parent.mkdir(parents=True)
479        pack.write_bytes(b"x" * (2 << 20))
480        args = ["--pack", str(data / "packs" / "x"), "--native", "/d/m.gguf", "--mtp", str(mtp), "--spec", "4", "--spec-min-p", "0.5"]
481        cfg = {"model_name": name, "args": args, **({} if mode is None else {"drafting": mode})}
482        return cfg, data, mtp
483
484    def test_unsloth_resolves_to_dflash2_alone_with_the_vocabulary_on_every_backend(self):
485        for backend, archs in self.HARDWARE:
486            for name in self.UNSLOTH:
487                with tempfile.TemporaryDirectory() as tmp:
488                    cfg, data, mtp = self.run_config(name, tmp)
489                    decision = drafting.apply(cfg, data_dir=data, backend=backend, archs=archs)
490                    args = cfg["args"]
491                    self.assertEqual((decision.drafter, decision.note), ("dflash2", ""), (backend, name))
492                    self.assertEqual(args[args.index("--draft") + 1], "dflash2")
493                    self.assertEqual(args[args.index("--draft-fallback") + 1], "none")
494                    self.assertEqual(args[args.index("--mtp-draft-vocab") + 1], str(mtp / "draft_vocab.bin"), "the vocabulary the engine needs")
495                    for flag in ("--mtp", "--spec-min-p"):
496                        self.assertNotIn(flag, args, (backend, name, flag))
497                    self.assertEqual(args[args.index("--spec") + 1], "8" if (backend, archs) == ("hip", ["gfx1151"]) else "6", "Strix Halo 8 (RESULTS-CONF.md 11-08), every other card 6")
498
499    def test_swift_coder_and_nvfp4_stay_on_the_mtp(self):
500        for backend, archs in self.HARDWARE:
501            for name in ("qwen3.8-flash-next-coder-iq1_m", "qwen3.8-flash-next-nvfp4-nvfp4", "swift-1.5-iq2_xs"):
502                for mode in (None, "auto", "dflash2"):
503                    with tempfile.TemporaryDirectory() as tmp:
504                        cfg, data, mtp = self.run_config(name, tmp, mode)
505                        original = list(cfg["args"])
506                        decision = drafting.apply(cfg, data_dir=data, backend=backend, archs=archs)
507                        self.assertEqual(decision.drafter, "mtp", (backend, name, mode))
508                        self.assertEqual(cfg["args"], original, "its own MTP arguments, untouched")
509                        self.assertNotIn("--draft", cfg["args"])
510                        if mode == "dflash2":
511                            self.assertEqual(decision.note, drafting.NOT_SUPPORTED)
512
513    def test_by_family_the_terminal_and_the_app_agree(self):
514        for backend, _ in self.HARDWARE:
515            self.assertEqual(drafting.choice_of("auto", family="unsloth", backend=backend), "dflash2", backend)
516            for family in ("swift", "coder", "nvfp4"):
517                self.assertEqual(drafting.choice_of("auto", family=family, backend=backend), "mtp", (backend, family))
518        # the app's own copies of the rule (the host and the page) name the same families and the same names
519        host = (ROOT / "apps" / "host" / "server" / "native-settings.mjs").read_text(encoding="utf-8")
520        page = (ROOT / "apps" / "host" / "src" / "lib" / "drafting.ts").read_text(encoding="utf-8")
521        generated = (ROOT / "apps" / "host" / "server" / "policy-generated.mjs").read_text(encoding="utf-8")        # the host's copy is generated from drafting.py (strata_control/app_policy.py)
522        self.assertIn("DRAFTING_FAMILIES=GENERATED_DRAFTING_FAMILIES", host)
523        self.assertIn('DRAFTING_FAMILIES = ["qwen", "gyro", "unsloth"]', generated)
524        self.assertIn("DRAFTING_FAMILIES = ['qwen', 'gyro', 'unsloth']", page)
525        self.assertIn(r"-unsloth-[a-z0-9._-]+", generated)
526
527
528class TheInstalledEngineDecidesTheFlags(unittest.TestCase):
529    """GUI-FB3 item 2. Gyro-S with Auto sent `--mtp-draft-vocab FILE` and no `--mtp` to the engine 0.1.55.2 (f-0291-r5070-df2), which only takes `--mtp DIR` for the
530    vocabulary and ended with exit code 2. The app reads what the engine program takes (it is never started for this) and sends only that."""
531
532    OLD = b"MZ\x00\x00 strata generate: --draft dflash2 drafts without the MTP layer (--draft-fallback mtp loads it too) and needs --draft-model PACK, --spec 2 or more and --mtp DIR (for DIR/draft_vocab.bin) \x00--draft-fallback\x00"
533    NEW = b"MZ\x00\x00 strata generate: --draft dflash2 drafts without the MTP layer and needs --draft-model PACK, --spec 2 or more and --mtp-draft-vocab FILE (or --mtp DIR, for DIR/draft_vocab.bin) \x00--draft-fallback\x00"
534    UNKNOWN = b"MZ\x00\x00 a program that has the flag and a message nobody knows \x00--draft-fallback\x00"
535    NONE = b"MZ\x00\x00 an engine from before DFlash2 ran alone: --draft dflash2 --draft-model \x00"
536
537    def setUp(self):
538        self.tmp = tempfile.TemporaryDirectory()
539        self.addCleanup(self.tmp.cleanup)
540        self.root = Path(self.tmp.name)
541        self.data = self.root / "data"
542        self.mtp = self.data / "mtp" / "rt"
543        self.mtp.mkdir(parents=True)
544        (self.mtp / "experts.bin").write_bytes(b"e")
545        (self.mtp / "draft_vocab.bin").write_bytes(b"v")
546        self.pack = drafting.pack_path(self.data)
547        self.pack.parent.mkdir(parents=True)
548        self.pack.write_bytes(b"x" * (2 << 20))
549        self.args = ["--pack", str(self.data / "packs" / "gyro"), "--native", "/d/m.gguf", "--mtp", str(self.mtp), "--spec", "4", "--spec-min-p", "0.5"]
550
551    def exe(self, name: str, body: bytes) -> Path:
552        path = self.root / name
553        path.write_bytes(body)
554        return path
555
556    def apply(self, engine, **extra):
557        cfg = {"model_name": GYRO, "args": list(self.args), **extra}
558        decision = drafting.apply(cfg, data_dir=self.data, backend="cuda", archs=["sm_120"], engine=engine)
559        return decision, cfg["args"]
560
561    def test_the_program_is_read_and_the_answer_kept_per_file(self):
562        self.assertEqual(drafting.engine_form(self.exe("old.exe", self.OLD)), drafting.FORM_DIR)
563        self.assertEqual(drafting.engine_form(self.exe("new.exe", self.NEW)), drafting.FORM_FILE)
564        self.assertIsNone(drafting.engine_form(self.exe("odd.exe", self.UNKNOWN)), "the flag is there but the message is not known: the usual form")
565        self.assertEqual(drafting.engine_form(self.exe("none.exe", self.NONE)), drafting.FORM_NONE, "no --draft-fallback: no DFlash2 on its own")
566        self.assertIsNone(drafting.engine_form(None))
567        self.assertIsNone(drafting.engine_form(self.root / "missing.exe"))
568        self.assertIsNone(drafting.engine_form(self.exe("empty.exe", b"")), "an empty file cannot be read: the usual form")
569        # a newer program in the same place is read again (size and time are part of the key)
570        path = self.exe("swap.exe", self.OLD)
571        self.assertEqual(drafting.engine_form(path), drafting.FORM_DIR)
572        path.write_bytes(self.NEW + b"more")
573        self.assertEqual(drafting.engine_form(path), drafting.FORM_FILE)
574
575    def test_the_vocabulary_flag_follows_the_engine(self):
576        vocab = self.mtp / "draft_vocab.bin"
577        usual = drafting.engine_flags("/p", vocab)
578        self.assertEqual(usual, drafting.engine_flags("/p", vocab, drafting.FORM_FILE))
579        self.assertIn("--mtp-draft-vocab", usual)
580        self.assertNotIn("--mtp", usual)
581        old = drafting.engine_flags("/p", vocab, drafting.FORM_DIR)
582        self.assertEqual(old[old.index("--mtp") + 1], str(self.mtp), "the folder that holds draft_vocab.bin")
583        self.assertNotIn("--mtp-draft-vocab", old)
584        self.assertEqual(old[:6], ("--draft", "dflash2", "--draft-model", "/p", "--draft-fallback", "none"), "still no MTP layer: the fallback is none")
585        self.assertEqual(old[-4:], ("--spec", "6", "--draft-conf", "0.35"))
586        self.assertNotIn("--mtp", drafting.engine_flags("/p", None, drafting.FORM_DIR), "no vocabulary, no flag")
587
588    def test_an_engine_that_takes_mtp_dir_gets_dflash2_alone_that_way(self):
589        decision, args = self.apply(self.exe("old.exe", self.OLD))
590        self.assertEqual((decision.drafter, decision.note), ("dflash2", ""))
591        self.assertNotIn("--mtp-draft-vocab", args)
592        self.assertEqual(args[args.index("--mtp") + 1], str(self.mtp))
593        self.assertEqual(args[args.index("--draft-fallback") + 1], "none", "the MTP layer is still not loaded")
594        for flag in ("--spec-min-p", "--batch-mtp", "--draft-mtp-spec"):
595            self.assertNotIn(flag, args)
596        self.assertEqual(args.count("--mtp"), 1)
597        self.assertEqual(args.count("--spec"), 1)
598        # the same start for the newer engine and for one nobody can tell: the vocabulary file alone
599        for body in (self.NEW, self.UNKNOWN):
600            decision, args = self.apply(self.exe("x.exe", body))
601            self.assertEqual(decision.drafter, "dflash2")
602            self.assertEqual(args[args.index("--mtp-draft-vocab") + 1], str(self.mtp / "draft_vocab.bin"))
603            self.assertNotIn("--mtp", args)
604        decision, args = self.apply(None)
605        self.assertIn("--mtp-draft-vocab", args)
606
607    def test_with_no_mtp_folder_the_old_form_names_the_dflash2_folder_that_holds_the_vocabulary(self):
608        own = drafting.vocab_target(self.data)
609        own.parent.mkdir(parents=True, exist_ok=True)
610        own.write_bytes(b"v")
611        args = ["--pack", str(self.data / "packs" / "gyro"), "--native", "/d/m.gguf"]
612        cfg = {"model_name": GYRO, "args": args}
613        decision = drafting.apply(cfg, data_dir=self.data, backend="cuda", archs=["sm_120"], engine=self.exe("old.exe", self.OLD))
614        self.assertEqual(decision.drafter, "dflash2")
615        self.assertEqual(cfg["args"][cfg["args"].index("--mtp") + 1], str(own.parent))
616
617    def test_a_vocabulary_that_is_not_called_draft_vocab_cannot_go_by_mtp_dir(self):
618        custom = self.root / "my-subset.bin"
619        custom.write_bytes(b"v")
620        args = [*self.args, "--mtp-draft-vocab", str(custom)]
621        cfg = {"model_name": GYRO, "args": args}
622        decision = drafting.apply(cfg, data_dir=self.data, backend="cuda", archs=["sm_120"], engine=self.exe("old.exe", self.OLD))
623        self.assertEqual((decision.drafter, decision.note), ("mtp", drafting.NOT_HERE), "said in one line; the MTP runs")
624        self.assertNotIn("--draft", cfg["args"])
625        cfg = {"model_name": GYRO, "args": list(args)}
626        decision = drafting.apply(cfg, data_dir=self.data, backend="cuda", archs=["sm_120"], engine=self.exe("new.exe", self.NEW))
627        self.assertEqual(decision.drafter, "dflash2")
628        self.assertEqual(cfg["args"][cfg["args"].index("--mtp-draft-vocab") + 1], str(custom), "an engine that takes the file keeps the person's own subset")
629
630    def test_an_engine_without_the_fallback_flag_never_gets_a_dflash2_flag(self):
631        for mode in ("auto", "dflash2"):
632            decision, args = self.apply(self.exe("none.exe", self.NONE), drafting=mode)
633            self.assertEqual((decision.drafter, decision.note), ("mtp", drafting.NOT_HERE), mode)
634            for flag in ("--draft", "--draft-model", "--draft-fallback", "--draft-conf", "--mtp-draft-vocab"):
635                self.assertNotIn(flag, args, (mode, flag))
636            self.assertEqual(args[args.index("--mtp") + 1], str(self.mtp), "the MTP, as the config had it")
637
638    def test_the_server_gives_the_engine_program_to_the_drafting_rule(self):
639        from serve.server import engine_args
640        old, new = self.exe("old.exe", self.OLD), self.exe("new.exe", self.NEW)
641        cfg = {"model_name": GYRO, "args": list(self.args), "drafting": "auto"}
642        with mock.patch("serve.server.drafting_vram_mib", return_value=None), mock.patch.object(drafting, "data_dir_of", return_value=self.data):
643            a_old, a_new, a_none = engine_args(cfg, str(old)), engine_args(cfg, str(new)), engine_args(cfg)
644        self.assertEqual(a_old[a_old.index("--mtp") + 1], str(self.mtp))
645        self.assertNotIn("--mtp-draft-vocab", a_old)
646        self.assertIn("--mtp-draft-vocab", a_new)
647        self.assertIn("--mtp-draft-vocab", a_none, "no program given (a test, a tool): the usual form")
648        # "mtp": false does not take the vocabulary folder out of a DFlash2 start
649        off = {"model_name": GYRO, "args": list(self.args), "drafting": "dflash2", "mtp": False}
650        with mock.patch("serve.server.drafting_vram_mib", return_value=None), mock.patch.object(drafting, "data_dir_of", return_value=self.data):
651            a = engine_args(off, str(old))
652        self.assertEqual(a[a.index("--mtp") + 1], str(self.mtp))
653
654    def test_the_retry_arguments_exist_only_for_an_auto_start_that_picked_dflash2(self):
655        from serve.server import mtp_retry_args
656        old = str(self.exe("old.exe", self.OLD))
657        base = {"model_name": GYRO, "args": list(self.args)}
658        with mock.patch("serve.server.drafting_vram_mib", return_value=None), mock.patch.object(drafting, "data_dir_of", return_value=self.data):
659            alt = mtp_retry_args({**base, "drafting": "auto"}, old, ["--effort", "x"])
660            self.assertIsNotNone(alt)
661            self.assertEqual(alt[:len(self.args)], self.args, "the MTP, as the config had it")
662            self.assertNotIn("--draft", alt)
663            self.assertEqual(alt[-2:], ["--effort", "x"], "what the start adds goes along")
664            self.assertIsNotNone(mtp_retry_args(dict(base), old), "no choice saved means Auto")
665            self.assertIsNone(mtp_retry_args({**base, "drafting": "dflash2"}, old), "named by the person: it fails with its reason")
666            self.assertIsNone(mtp_retry_args({**base, "drafting": "mtp"}, old), "nothing to fall back from")
667            self.assertIsNone(mtp_retry_args({**base, "drafting": "off"}, old))
668            self.assertIsNone(mtp_retry_args({"model_name": "qwen3.6-35b-a3b", "args": list(self.args), "drafting": "auto"}, old), "another model has no DFlash2")
669            # no MTP layer on this computer: the other start would be DFlash2 again, so there is nothing to retry with
670            for name in ("experts.bin", "draft_vocab.bin"):
671                (self.mtp / name).unlink()
672            self.assertIsNone(mtp_retry_args({**base, "drafting": "auto"}, old))
673        # the lines and the note of the real start are not touched by working the retry out
674        drafting.take_note()
675        with mock.patch("serve.server.drafting_vram_mib", return_value=None), mock.patch.object(drafting, "data_dir_of", return_value=self.data):
676            mtp_retry_args({**base, "drafting": "auto"}, old)
677        self.assertEqual(drafting.take_note(), "")
678
679    def test_the_no_drafter_retry_exists_for_an_auto_start_with_a_drafter_and_never_swaps_in_the_mtp(self):
680        """A start that ended for lack of graphics memory is repeated with no drafter (multi-card walk): DFlash2 -> MTP would take MORE memory from a card that is short."""
681        from serve.server import nodraft_retry_args
682        old = str(self.exe("old.exe", self.OLD))
683        base = {"model_name": GYRO, "args": list(self.args)}
684        with mock.patch("serve.server.drafting_vram_mib", return_value=None), mock.patch.object(drafting, "data_dir_of", return_value=self.data):
685            alt = nodraft_retry_args({**base, "drafting": "auto"}, old, ["--effort", "x"])
686            self.assertIsNotNone(alt)
687            for flag in ("--draft", "--draft-model", "--draft-fallback", "--mtp", "--mtp-draft-vocab"):
688                self.assertNotIn(flag, alt, flag)
689            self.assertEqual(alt[-2:], ["--effort", "x"], "what the start adds goes along")
690            self.assertIn("--native", alt, "everything else is the same start")
691            self.assertIsNotNone(nodraft_retry_args(dict(base), old), "no choice saved means Auto")
692            self.assertIsNone(nodraft_retry_args({**base, "drafting": "dflash2"}, old), "named by the person: it fails with its reason")
693            self.assertIsNone(nodraft_retry_args({**base, "drafting": "mtp"}, old), "named by the person: it fails with its reason")
694            self.assertIsNone(nodraft_retry_args({**base, "drafting": "off"}, old), "no drafter to drop")
695        drafting.take_note()
696        with mock.patch("serve.server.drafting_vram_mib", return_value=None), mock.patch.object(drafting, "data_dir_of", return_value=self.data):
697            nodraft_retry_args({**base, "drafting": "auto"}, old)
698        self.assertEqual(drafting.take_note(), "", "working the retry out leaves the note of the real start alone")
699
700    def test_the_engine_sources_carry_the_words_the_program_is_read_for(self):
701        src = (ROOT / "src" / "program" / "generate.cpp").read_text(encoding="utf-8")
702        self.assertIn(drafting._MARK_FILE.decode(), src, "rc1's start message is what marks an engine that takes the vocabulary file alone")
703        self.assertIn(drafting._MARK_FALLBACK.decode(), src)
704
705
706class WhatTheEngineSaid(unittest.TestCase):
707    ARGS = ["--mtp", "/m", "--draft", "dflash2", "--draft-model", "/p"]
708
709    def test_no_room_in_graphics_memory(self):
710        log = ("strata generate: --draft dflash2: could not allocate the drafter's buffers. DFlash2 needs about 1.2 GiB of VRAM (the pack 0.76 GiB, "
711               "its buffers and K/V ring 0.25 GiB, a draft head 0.2 GiB); start with --vram-reserve-mib 1900 to keep it. The MTP drafts instead.\n")
712        info = drafting.engine_info(self.ARGS, log)
713        self.assertEqual(info, {"drafting": "mtp", "drafting_note": "Drafting: MTP (DFlash2 didn't fit)"})
714
715    def test_a_mode_this_build_does_not_run(self):
716        log = "strata generate: --draft dflash2 is off: it is for one card and the CLI run (not --serve, --batch or a layer split) in this build; the MTP drafts instead\n"
717        self.assertEqual(drafting.engine_info(self.ARGS, log)["drafting_note"], "Drafting: MTP (DFlash2 isn't available in this mode)")
718
719    def test_it_ran(self):
720        log = "strata generate: DFlash2 drafter on (/p, graphs captured in 3 ms), the MTP layer stays as the fallback\n"
721        self.assertEqual(drafting.engine_info(self.ARGS, log), {"drafting": "dflash2", "drafting_note": ""})
722        self.assertEqual(drafting.fallback_note(log), "")
723
724    def test_choices_that_never_reached_the_engine_keep_their_own_words(self):
725        self.assertEqual(drafting.engine_info(["--mtp", "/m"], "", drafting.NOT_SUPPORTED)["drafting_note"],
726                         "Drafting: MTP (DFlash2 is for Qwen3.8-Flash-Next only)")
727        self.assertEqual(drafting.engine_info(["--mtp", "/m"]), {"drafting": "mtp", "drafting_note": ""})
728        self.assertEqual(drafting.engine_info(["--spec", "4"]), {"drafting": "off", "drafting_note": ""})
729
730    def test_summary_line(self):
731        self.assertEqual(drafting.summary_line(drafting.Decision("auto", "mtp")), "Drafting: MTP")
732        self.assertEqual(drafting.summary_line(drafting.Decision("dflash2", "dflash2")), "Drafting: DFlash2")
733        self.assertEqual(drafting.summary_line(drafting.Decision("off", "off")), "Drafting: Off")
734        self.assertEqual(drafting.summary_line(drafting.Decision("dflash2", "mtp", drafting.NOT_DOWNLOADED)),
735                         "Drafting: MTP (the DFlash2 drafter isn't downloaded yet)")
736
737
738class WordsMatchTheApp(unittest.TestCase):
739    def test_every_line_the_engine_start_can_say_is_in_the_apps_catalog_in_all_nine_languages(self):
740        folder = ROOT / "apps" / "host" / "src" / "locales"
741        catalogs = {l: {**json.loads((folder / f"{l}.json").read_text(encoding="utf-8")), **json.loads((folder / f"df2-{l}.json").read_text(encoding="utf-8"))}
742                    for l in ("en", "de", "es", "fr", "ja", "ko", "pt", "ru", "zh")}
743        ids = {v: k for k, v in catalogs["en"].items()}
744        self.assertEqual(len(drafting.REASONS), 10)
745        lines = [drafting.mtp_line(r) for r in (drafting.DIDNT_FIT, drafting.NOT_HERE, drafting.NOT_SUPPORTED, drafting.NOT_DOWNLOADED, drafting.NOT_THIS_CARD, drafting.DIDNT_START)]
746        lines += [drafting.line("dflash2", drafting.NO_MTP), drafting.line("off", drafting.NONE_HERE), drafting.line("off", drafting.SHORT_OF_VRAM), drafting.line("mtp", drafting.NONE_IN_SLOTS)]
747        for line in lines:
748            self.assertIn(line, ids, line)
749            for lang, catalog in catalogs.items():
750                self.assertTrue(catalog[ids[line]].strip(), f"{line} in {lang}")
751        # and what the engine's log makes of them
752        self.assertEqual(drafting.fallback_note("--draft dflash2: out of memory"), drafting.mtp_line(drafting.DIDNT_FIT))
753        self.assertEqual(drafting.fallback_note("--draft dflash2 is off: it is for one card and the CLI run"), drafting.mtp_line(drafting.NOT_HERE))
754
755
756class TerminalFlag(unittest.TestCase):
757    BASE = {"exe": "component:strata-engine", "args": ["--pack", "/d/packs/x", "--mtp", "/d/mtp/rt"], "port": 8080, "model_name": GYRO}
758
759    def test_the_flag_is_listed_planned_copyable_and_saved_in_the_launch_config(self):
760        code, out, _ = run_cli(["launch", "--help"])
761        self.assertIn("--drafting", out)
762        self.assertIn("auto|mtp|dflash2|off", out)
763        cfg = derive_config(self.BASE, S.LaunchSettings(drafting="dflash2"), bool_flags=frozenset())
764        self.assertEqual(cfg["drafting"], "dflash2")
765        self.assertNotIn("drafting", derive_config(self.BASE, S.LaunchSettings(), bool_flags=frozenset()), "Auto writes nothing: nobody chose")
766        self.assertIn("--drafting dflash2", S.flags_text(S.LaunchSettings(drafting="dflash2")))
767        self.assertNotIn("--drafting", S.flags_text(S.LaunchSettings()))
768        code, out, err = run_cli(["launch", "--plan", "--drafting", "fastest"])
769        self.assertNotEqual(code, 0)
770
771    def test_a_saved_preset_keeps_the_choice(self):
772        s = S.LaunchSettings.from_dict(S.LaunchSettings(drafting="mtp").to_dict())
773        self.assertEqual(s.drafting, "mtp")
774        self.assertIsNone(S.LaunchSettings.from_dict({}).drafting)
775
776
777class _Handler(http.server.BaseHTTPRequestHandler):
778    files: dict = {}
779    hits: list = []
780
781    def do_GET(self):
782        body = self.files.get(self.path.rsplit("/", 1)[-1])
783        self.hits.append(self.path)
784        if body is None:
785            self.send_error(404)
786            return
787        start = 0
788        rng = self.headers.get("Range")
789        if rng and rng.startswith("bytes="):
790            start = int(rng[6:].split("-")[0])
791        self.send_response(206 if start else 200)
792        if start:
793            self.send_header("Content-Range", f"bytes {start}-{len(body) - 1}/{len(body)}")
794        self.send_header("Content-Length", str(len(body) - start))
795        self.end_headers()
796        self.wfile.write(body[start:])
797
798    def log_message(self, *_):
799        pass
800
801
802class FetchAndPack(unittest.TestCase):
803    @classmethod
804    def setUpClass(cls):
805        sys.path.insert(0, str(ROOT / "tools"))
806        spec = importlib.util.spec_from_file_location("t_pack", ROOT / "tools" / "test_dflash2_pack.py")
807        cls.synth = importlib.util.module_from_spec(spec)
808        spec.loader.exec_module(cls.synth)
809
810    def setUp(self):
811        self.tmp = tempfile.TemporaryDirectory()
812        self.addCleanup(self.tmp.cleanup)
813        self.dir = Path(self.tmp.name)
814        self.synth.write_safetensors(self.dir / "m.safetensors", self.synth.tensors())
815        (self.dir / "c.json").write_text(json.dumps(self.synth.CFG))
816        import hashlib
817        self.blobs = {"config.json": (self.dir / "c.json").read_bytes(), "model.safetensors": (self.dir / "m.safetensors").read_bytes()}
818        self.files = tuple((n, len(b), hashlib.sha256(b).hexdigest()) for n, b in self.blobs.items())
819        _Handler.files, _Handler.hits = dict(self.blobs), []
820        self.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
821        threading.Thread(target=self.server.serve_forever, daemon=True).start()
822        self.addCleanup(self.server.shutdown)
823        self.base = f"http://127.0.0.1:{self.server.server_address[1]}/"
824        self.data = self.dir / "data"
825        self.steps: list = []
826        # the packed test file is a few hundred kB, not the real 0.76 GB: "ready" asks for more than 1 MiB by default
827        patcher = mock.patch.object(drafting, "pack_ready", lambda d: bool(d) and drafting.pack_path(d).is_file())
828        patcher.start()
829        self.addCleanup(patcher.stop)
830
831    def fetch(self, **kw):
832        with mock.patch.dict("os.environ", {"STRATA_UPDATE_ALLOW_HTTP": "1"}):
833            return drafting_fetch.ensure(self.data, progress=lambda *a: self.steps.append(a), base_url=self.base, files=self.files, **kw)
834
835    def test_the_pinned_files_are_the_repositorys_own(self):
836        self.assertEqual(drafting.REVISION, "a22a1744e85c17364dcc54a6a420af7135d4c7f6")
837        self.assertTrue(drafting.BASE_URL.endswith(f"/{drafting.REVISION}/"), "a revision, never a branch name")
838        names = {n: (size, sha) for n, size, sha in drafting.FILES}
839        self.assertEqual(names["model.safetensors"], (1206140008, "d6723f2a359eaf33ec0c95f22ae8edda896774020c552296a85e1913b4d3186f"))
840        self.assertEqual(len(names["config.json"][1]), 64)
841        self.assertEqual(drafting.LICENSE, "Apache-2.0")
842
843    def test_it_downloads_checks_packs_and_removes_the_source(self):
844        out = self.fetch()
845        self.assertEqual(out, drafting.pack_path(self.data))
846        self.assertEqual(out.read_bytes()[:4], b"DF2P")
847        self.assertFalse((out.parent / "src").exists(), "the 1.2 GB source file does not stay on disk")
848        words = [s[0] for s in self.steps]
849        self.assertIn("Downloading the DFlash2 drafter…", words)
850        self.assertIn("Packing the DFlash2 drafter for the engine…", words)
851        self.assertEqual(words[-1], "The DFlash2 drafter is ready.")
852        self.assertEqual(max(s[1] for s in self.steps if s[0].startswith("Downloading")), sum(f[1] for f in self.files))
853
854    def test_a_drafter_that_is_here_is_not_fetched_again(self):
855        self.fetch()
856        _Handler.hits.clear()
857        self.steps.clear()
858        self.fetch()
859        self.assertEqual(_Handler.hits, [])
860        self.assertEqual(self.steps[0][0], "The DFlash2 drafter is ready.")
861
862    def test_a_fresh_install_that_selected_only_dflash2_has_everything_the_engine_needs(self):
863        """No MTP layer was ever downloaded (no mtp folder at all): the pack comes with the draft vocabulary, and the engine arguments carry
864        --mtp-draft-vocab for it and no --mtp."""
865        self.assertFalse((self.data / "mtp").exists())
866        self.assertFalse(drafting.vocab_target(self.data).exists())
867        self.fetch()
868        vocab = drafting.vocab_target(self.data)
869        self.assertEqual(vocab, self.data / drafting.FOLDER / "draft_vocab.bin")
870        self.assertTrue(vocab.is_file() and vocab.stat().st_size > 0)
871        self.assertEqual(vocab.read_bytes(), drafting.shipped_vocab().read_bytes(), "the subset Strata ships")
872        args = ["--pack", str(self.data / "packs" / "gyro"), "--native", "/m.gguf", "--mtp", str(self.data / "mtp" / "rt"), "--spec", "4", "--spec-min-p", "0.5"]
873        # the Strata folder's own copy is not needed any more: the install keeps its own
874        with mock.patch.object(drafting, "shipped_vocab", return_value=self.dir / "gone.bin"):
875            cfg = {"model_name": GYRO, "args": list(args)}
876            d = drafting.apply(cfg, data_dir=self.data, backend="cuda", archs=["sm_120"])
877        self.assertEqual((d.drafter, d.note), ("dflash2", ""))
878        a = cfg["args"]
879        self.assertNotIn("--mtp", a)
880        self.assertEqual(a[a.index("--mtp-draft-vocab") + 1], str(vocab))
881        self.assertEqual(a[a.index("--draft-model") + 1], str(drafting.pack_path(self.data)))
882        self.assertEqual(a[a.index("--draft-fallback") + 1], "none")
883        # and through the server, as a start builds it
884        from serve.server import engine_args
885        with mock.patch("serve.server.drafting_vram_mib", return_value=None), mock.patch.object(drafting, "data_dir_of", return_value=self.data):
886            served = engine_args({"model_name": GYRO, "args": list(args)})
887        self.assertNotIn("--mtp", served)
888        self.assertTrue(Path(served[served.index("--mtp-draft-vocab") + 1]).is_file())
889
890    def test_the_vocabulary_is_provided_once_and_never_overwritten(self):
891        out = drafting.provide_vocab(self.data)
892        self.assertEqual(out, drafting.vocab_target(self.data))
893        out.write_bytes(b"mine")
894        self.assertEqual(drafting.provide_vocab(self.data).read_bytes(), b"mine")
895        self.assertIsNone(drafting.provide_vocab(None))
896        with mock.patch.object(drafting, "shipped_vocab", return_value=self.dir / "gone.bin"):
897            self.assertIsNone(drafting.provide_vocab(self.dir / "other"))
898
899    def test_without_any_vocabulary_dflash2_does_not_start_and_says_so(self):
900        """The engine refuses a missing vocabulary file; the app never gets there: no file anywhere means the MTP (or none), in one line."""
901        self.fetch()
902        args = ["--pack", str(self.data / "packs" / "gyro"), "--mtp", str(self.data / "mtp" / "rt")]
903        drafting.vocab_target(self.data).unlink()
904        with mock.patch.object(drafting, "shipped_vocab", return_value=self.dir / "gone.bin"):
905            cfg = {"model_name": GYRO, "args": list(args)}
906            d = drafting.apply(cfg, data_dir=self.data, backend="cuda", archs=["sm_120"])
907        self.assertEqual((d.drafter, d.note), ("off", drafting.NONE_HERE))
908        self.assertNotIn("--draft", cfg["args"])
909
910    def test_a_file_that_does_not_match_its_hash_is_deleted_and_the_words_are_plain(self):
911        bad = tuple((n, size, "0" * 64) for n, size, _h in self.files)
912        with mock.patch.dict("os.environ", {"STRATA_UPDATE_ALLOW_HTTP": "1"}):
913            with self.assertRaises(drafting_fetch.DraftingError) as ctx:
914                drafting_fetch.ensure(self.data, base_url=self.base, files=bad)
915        self.assertIn("did not pass the safety check", str(ctx.exception))
916        self.assertFalse(drafting.pack_path(self.data).exists())
917        self.assertEqual(list((drafting.pack_path(self.data).parent / "src").glob("*.part")), [])
918
919    def test_an_interrupted_download_is_continued(self):
920        name, size, _sha = self.files[1]
921        src = drafting.pack_path(self.data).parent / "src"
922        src.mkdir(parents=True)
923        (src / (name + ".part")).write_bytes(self.blobs[name][: size // 2])
924        self.fetch()
925        ranges = [h for h in _Handler.hits if h.endswith(name)]
926        self.assertEqual(len(ranges), 1)
927        self.assertTrue(drafting.pack_path(self.data).is_file())
928
929    def test_a_start_never_downloads(self):
930        with acquisition.forbidden():
931            with self.assertRaises(acquisition.AcquisitionRefused):
932                drafting_fetch.ensure(self.data, base_url=self.base, files=self.files)
933        self.assertFalse(drafting.pack_path(self.data).exists())
934
935    def test_the_plan_names_the_size_and_where_it_comes_from(self):
936        with mock.patch.object(drafting, "pack_ready", return_value=False):
937            plan = drafting_fetch.plan(self.data)
938        self.assertEqual(plan["gb"], 1.2)
939        self.assertIn("1.2 GB to download", plan["text"])
940        self.assertIn("0.52 GB", plan["text"])
941        self.assertIn("incoai/Qwen3.8-Flash-Next-DFlash2", plan["text"])
942        self.assertIn("Apache-2.0", plan["text"])
943        self.assertIn("It needs about 0.9 GB of graphics memory", plan["text"], "the figure of DFlash2 alone")
944        with mock.patch.object(drafting, "pack_ready", return_value=True):
945            self.assertEqual(drafting_fetch.plan(self.data)["gb"], 0.0)
946
947    def test_the_command_line_says_the_same(self):
948        code, out, err = run_cli(["drafting", "plan", "--data-dir", str(self.data), "--output", "json"])
949        self.assertEqual(code, 0, err)
950        payload = json.loads(out)
951        self.assertEqual((payload["ok"], payload["revision"]), (True, drafting.REVISION))
952        self.assertEqual(payload["gb"], 1.2)
953
954
955class TheAppAsksControl(unittest.TestCase):
956    """The app calls `strata drafting plan|fetch --config <run config> --mode <choice>` before a load; Control decides, the app never reads the table."""
957
958    def setUp(self):
959        self.tmp = tempfile.TemporaryDirectory()
960        self.addCleanup(self.tmp.cleanup)
961        self.data = Path(self.tmp.name) / "data"
962        self.cfg = Path(self.tmp.name) / "strata-gyro.json"
963        self.cfg.write_text(json.dumps({"model_name": GYRO, "args": ["--pack", str(self.data / "packs" / "gyro"), "--mtp", str(self.data / "mtp" / "rt")]}))
964
965    def plan(self, *extra):
966        code, out, err = run_cli(["drafting", "plan", "--config", str(self.cfg), "--output", "json", *extra])
967        self.assertEqual(code, 0, err)
968        return json.loads(out)
969
970    def test_nothing_is_needed_for_mtp_or_off_and_the_pack_for_auto_and_dflash2(self):
971        for mode in ("mtp", "off"):
972            plan = self.plan("--mode", mode)
973            self.assertFalse(plan["needed"], mode)
974            self.assertEqual(plan["gb"], 0.0)
975        for mode in ("auto", "dflash2"):
976            plan = self.plan("--mode", mode)
977            self.assertTrue(plan["needed"], mode)
978            self.assertEqual((plan["gb"], plan["choice"]), (1.2, "dflash2"))
979        self.assertEqual(self.plan("--mode", "off")["drafter"], "off")
980
981    def test_choosing_the_mtp_without_its_layer_says_the_layer_is_needed(self):
982        plan = self.plan("--mode", "mtp")
983        self.assertTrue(plan["mtp_needed"])
984        self.assertEqual((plan["mtp_gb"], plan["choice"]), (5.2, "mtp"))
985        self.assertFalse(self.plan("--mode", "auto")["mtp_needed"])
986
987    def test_dflash2_is_needed_once_the_engine_can_serve_it_and_not_before(self):
988        (self.data / "mtp" / "rt").mkdir(parents=True)
989        (self.data / "mtp" / "rt" / "experts.bin").write_bytes(b"e")           # the MTP layer is on this computer
990        with mock.patch.object(drafting, "ENGINE_SERVES_DFLASH2", False):
991            before = self.plan("--mode", "dflash2")
992        self.assertFalse(before["needed"], "while the engine cannot serve it nothing is downloaded")
993        self.assertEqual(before["line"], "Drafting: MTP (DFlash2 isn't available in this mode)")
994        with serving_dflash2():
995            plan = self.plan("--mode", "dflash2")
996            self.assertTrue(plan["needed"])
997            self.assertEqual(plan["gb"], 1.2)
998            self.assertEqual(Path(plan["pack"]), drafting.pack_path(self.data), "the data folder comes from the run config's own arguments")
999            self.cfg.write_text(json.dumps({"model_name": "qwen3.8-flash-next-coder-iq3_xxs", "drafting": "dflash2", "args": ["--pack", str(self.data / "packs" / "c")]}))
1000            other = self.plan()
1001            self.assertFalse(other["needed"])
1002            self.assertEqual(other["note"], drafting.NOT_SUPPORTED)
1003
1004    def test_a_model_that_is_not_installed_yet_is_asked_about_by_its_family(self):
1005        with serving_dflash2():
1006            for family, needed in (("gyro", True), ("qwen", True), ("coder", False), ("swift", False)):
1007                code, out, err = run_cli(["drafting", "plan", "--family", family, "--mode", "dflash2", "--data-dir", str(self.data), "--output", "json"])
1008                self.assertEqual(code, 0, err)
1009                self.assertEqual(json.loads(out)["needed"], needed, family)
1010
1011    def test_fetch_if_needed_does_nothing_when_nothing_is_needed(self):   # (the MTP is chosen: no drafter file is needed)
1012        code, out, err = run_cli(["drafting", "fetch", "--config", str(self.cfg), "--mode", "mtp", "--if-needed", "--output", "jsonl"])
1013        self.assertEqual(code, 0, err)
1014        last = json.loads(out.strip().splitlines()[-1])
1015        self.assertEqual((last["ok"], last["skipped"], last["pack"]), (True, True, None))
1016        self.assertFalse(drafting.pack_path(self.data).exists())
1017
1018
1019class TheDownloadPlanListsIt(unittest.TestCase):
1020    """`strata launch --plan --drafting dflash2` adds the drafter to the download when it would be used."""
1021
1022    def setUp(self):
1023        from tests.terminal.launch_support import not_intel
1024        not_intel(self)
1025
1026    def test_the_plan_line_and_the_part(self):
1027        from tests.terminal.launch_support import HW_12, Home, catalog
1028        from strata_cli.launch.runner import Runner
1029        with Home() as home:
1030            runner = Runner(S.LaunchSettings(family="qwen", model="Q2_0", context=32768, vision="off", drafting="dflash2"), catalog=catalog(HW_12))
1031            with mock.patch.object(drafting, "ENGINE_SERVES_DFLASH2", False):
1032                line = runner.drafting_plan_line()
1033                self.assertEqual(line, "Drafting: MTP (DFlash2 isn't available in this mode)")
1034                self.assertNotIn("dflash2", [p["kind"] for p in runner.download_plan()["parts"]], "nothing to fetch while the engine cannot serve it")
1035            with serving_dflash2():
1036                kinds = {p["kind"]: p for p in runner.download_plan()["parts"]}
1037                self.assertEqual(kinds["dflash2"]["gb"], 1.2)
1038                self.assertIn("the DFlash2 drafter (1.2 GB)", runner.download_plan()["text"])
1039                self.assertIn("--drafting mtp", runner.download_plan()["text"])
1040                auto = Runner(S.LaunchSettings(family="qwen", model="Q2_0", context=32768, vision="off"), catalog=catalog(HW_12))
1041                self.assertIn("dflash2", [p["kind"] for p in auto.download_plan()["parts"]], "Auto is DFlash2: its drafter is the download")
1042                mtp = Runner(S.LaunchSettings(family="qwen", model="Q2_0", context=32768, vision="off", drafting="mtp"), catalog=catalog(HW_12))
1043                kinds = [p["kind"] for p in mtp.download_plan()["parts"]]
1044                self.assertNotIn("dflash2", kinds)
1045                self.assertIn("mtp", kinds, "the MTP is chosen: its layer is the download, DFlash2's is not")
1046                self.assertNotIn("mtp", [p["kind"] for p in auto.download_plan()["parts"]], "one drafter per run: a new install fetches only the one it will use")
1047                other = Runner(S.LaunchSettings(family="coder", model="IQ3_XXS", context=32768, vision="off", drafting="dflash2"), catalog=catalog(HW_12))
1048                self.assertNotIn("dflash2", [p["kind"] for p in other.download_plan()["parts"]], "not for this model: hidden, not offered")
1049
1050
1051if __name__ == "__main__":
1052    unittest.main()
1053
1054
1055class ControlReportsWhetherTheEngineServesIt(unittest.TestCase):
1056    def test_the_plan_says_it_so_the_app_can_hide_the_choice(self):
1057        for served in (False, True):
1058            with mock.patch.object(drafting, "ENGINE_SERVES_DFLASH2", served):
1059                code, out, err = run_cli(["drafting", "plan", "--mode", "auto", "--family", "gyro", "--data-dir", tempfile.gettempdir(), "--output", "json"])
1060                self.assertEqual(code, 0, err)
1061                self.assertIs(json.loads(out)["serves"], served)