okami.mom/strata

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

Niko1221launch: a drafter the person chose stays chosen, the way Off does1b4018870

main
9.4 KiB166 linesraw
1"""A drafter the person chose stays chosen (owner 11-15, item 7 of lane FIX-0215A): MTP or DFlash2 picked by hand (`--drafting`, the TUI's Drafting step, the app's
2Drafting setting) is kept by a later restart or launch with no Drafting word, the way Off is; only a new explicit choice changes it, Auto included.  The drafter
3rule holds: a chosen drafter whose file is not here and cannot be fetched (offline) starts the other drafter when that one is on disk and safe on the card, with
4the existing note; the saved choice stays what the person set, never the fallback; on gfx1201 DFlash2 never stands in.  Nothing real is used
5(tests/snapshot/README.md).
6
7  python -m pytest tests/snapshot/test_drafting_chosen_holds.py -q -p no:cacheprovider
8"""
9
10from __future__ import annotations
11
12import json
13import sys
14import unittest
15from pathlib import Path
16from types import SimpleNamespace
17from unittest import mock
18
19ROOT = Path(__file__).resolve().parents[2]
20if str(ROOT) not in sys.path:
21    sys.path.insert(0, str(ROOT))
22
23from tests.snapshot.driver import drive_launch  # noqa: E402
24from tests.snapshot.matrix import MACHINES, MODEL_SETS, machine as get_machine, model_set as get_set  # noqa: E402
25from tests.snapshot.normalize import normalize  # noqa: E402
26from tests.snapshot.test_drafting_round_trip import argv, drafter, launches  # noqa: E402
27from tests.snapshot.world import World, context_for  # noqa: E402
28
29FLASH = [s for s in MODEL_SETS if s.family in ("qwen", "unsloth", "gyro")]
30
31
32def setup_drafter(rec: dict) -> str | None:
33    a = rec.get("setup_args") or []
34    return a[a.index("--drafter") + 1] if "--drafter" in a else None
35
36
37class ChosenHolds(unittest.TestCase):
38    maxDiff = None
39
40    def test_a_chosen_mtp_or_dflash2_holds_over_restarts_with_no_word(self):
41        for m in MACHINES:
42            for s in FLASH:
43                for word in ("mtp", "dflash2"):
44                    with self.subTest(machine=m.key, set=s.key, word=word):
45                        recs = launches(m, s, [(word, False), (word, False), (None, False), (None, False)])
46                        for later in recs[2:]:
47                            self.assertEqual(later["config_file"].get("drafting"), word, "the saved choice stays as the person set it")
48                            self.assertEqual(argv(later), argv(recs[1]), "a restart with no word starts as one with the word")
49
50    def test_only_a_new_explicit_choice_changes_it_auto_included(self):
51        for mkey, skey in (("nv_resident", "iq3_s"), ("nv_12gb_streaming", "ud_q4_k_xl"), ("strix_halo_win", "ud_q4_k_xl"), ("mac_large", "ud_q4_k_xl")):
52            with self.subTest(machine=mkey, set=skey):
53                m, s = get_machine(mkey), get_set(skey)
54                recs = launches(m, s, [("auto", False), ("auto", False), ("mtp", False), ("auto", False), (None, False)])
55                self.assertEqual(drafter(recs[2]), "mtp")
56                self.assertEqual(recs[4]["config_file"].get("drafting"), "auto", "Auto chosen again replaces the MTP")
57                self.assertEqual(argv(recs[4]), argv(recs[1]), "and starts as Auto did")
58                recs = launches(m, s, [("dflash2", False), ("off", False), (None, False)])
59                self.assertEqual(drafter(recs[2]), "off", "Off chosen after a drafter holds")
60
61    def test_setup_is_told_the_chosen_drafter_at_a_start_with_no_word(self):
62        # setup runs again (a --model-path, a change): it is told the drafter the person chose, not Auto's
63        for mkey, skey in (("nv_resident", "iq3_s"), ("nv_resident", "ud_q4_k_xl"), ("strix_halo_win", "ud_q4_k_xl")):
64            with self.subTest(machine=mkey, set=skey):
65                recs = launches(get_machine(mkey), get_set(skey), [("mtp", True), (None, True)])
66                self.assertEqual(setup_drafter(recs[1]), setup_drafter(recs[0]))
67                self.assertEqual(drafter(recs[1]), "mtp")
68
69    def test_the_models_screen_choice_still_decides_and_is_not_overwritten(self):
70        def app_says_dflash2(world):
71            cfg = json.loads(world.config_path.read_text(encoding="utf-8"))
72            cfg["drafting"] = "dflash2"
73            world.config_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8")
74        recs = launches(get_machine("nv_resident"), get_set("ud_q4_k_xl"), [("mtp", False), (None, False)], prepare=app_says_dflash2)
75        self.assertEqual(recs[0]["config_file"].get("drafting"), "mtp", "the word given wins at its own launch")
76        self.assertEqual(recs[1]["config_file"].get("drafting"), "dflash2", "no word: the installed config's own choice (a later one) decides")
77
78
79def chosen_then_offline(m, s, word, *, other_on_disk: bool):
80    """`--drafting <word>` online, then the chosen drafter's file is gone and this computer is offline; a restart with no word.  `other_on_disk`: the other
81    drafter is on this computer."""
82    from strata_control import drafting_fetch
83    from tests.snapshot import driver
84    world = World(m, s).build()
85    try:
86        with world.patched():
87            first = drive_launch(world, ("--drafting", word), setup_runs=False)
88            assert "failed" not in first, first.get("failed")
89            if word == "mtp":
90                for f in (world.mtp / "experts.bin", world.data / "mtp" / "mtp-q2_0.gguf"):
91                    f.unlink(missing_ok=True)
92                if other_on_disk:
93                    drafting_fetch.ensure(world.data)
94            else:
95                for f in sorted((world.data / "dflash2").glob("*.pack*")):
96                    f.unlink()
97                if not other_on_disk:
98                    (world.mtp / "experts.bin").unlink(missing_ok=True)
99            world.fetches.clear()
100            # offline: nothing can be fetched (the world's own fakes of the drafter download write the file whatever `online` says)
101            with mock.patch.object(driver, "setup_fetches_layer", lambda *a, **k: None), mock.patch.object(drafting_fetch, "online", lambda *a, **k: False), \
102                    mock.patch.object(drafting_fetch, "ensure", lambda *a, **k: None), mock.patch.object(drafting_fetch, "ensure_tuned", lambda *a, **k: None), \
103                    mock.patch.object(drafting_fetch, "convert_selector", lambda *a, **k: None):
104                rec = drive_launch(world, (), setup_runs=False)
105        assert "failed" not in rec, rec.get("failed")
106        return normalize(rec, world)
107    finally:
108        world.close()
109
110
111class ChosenOffline(unittest.TestCase):
112    maxDiff = None
113
114    def test_a_chosen_mtp_without_its_layer_starts_dflash2_from_disk_and_stays_mtp(self):
115        for mkey in ("nv_resident", "nv_12gb_streaming", "strix_halo_win"):
116            with self.subTest(machine=mkey):
117                rec = chosen_then_offline(get_machine(mkey), get_set("iq3_s"), "mtp", other_on_disk=True)
118                self.assertEqual(drafter(rec), "dflash2", rec["engine"]["argv"])
119                self.assertEqual(rec["config_file"].get("drafting"), "mtp", "the saved choice is the person's, not the fallback")
120
121    def test_on_gfx1201_dflash2_never_stands_in(self):
122        rec = chosen_then_offline(get_machine("r9700_linux"), get_set("iq3_s"), "mtp", other_on_disk=True)
123        self.assertEqual(drafter(rec), "off", "no safe drafter on disk there: no DFlash2 stand-in")
124        self.assertEqual(rec["config_file"].get("drafting"), "mtp")
125
126    def test_a_chosen_dflash2_without_its_drafter_starts_the_mtp_and_stays_dflash2(self):
127        for mkey in ("nv_resident", "strix_halo_win"):
128            with self.subTest(machine=mkey):
129                rec = chosen_then_offline(get_machine(mkey), get_set("ud_q4_k_xl"), "dflash2", other_on_disk=True)
130                self.assertEqual(drafter(rec), "mtp", rec["engine"]["argv"])
131                self.assertEqual(rec["config_file"].get("drafting"), "dflash2")
132
133
134class TuiStep(unittest.TestCase):
135    """The TUI's Drafting step after a launch with a chosen drafter: it shows the choice that holds, and an Auto picked there is written, so it replaces it."""
136
137    def step(self, world, pick):
138        from strata_cli.launch import settings as S
139        from strata_cli.launch.screens import DraftingScreen
140        base = json.loads(world.config_path.read_text(encoding="utf-8"))
141        s = S.LaunchSettings(family=world.mset.family, model=world.mset.model, context=context_for(world.machine, world.mset))
142        menu = SimpleNamespace(columns=None, sel=None, current=None)
143        menu.set_items = lambda items, sel: setattr(menu, "sel", sel)
144        fake = SimpleNamespace(ctx=SimpleNamespace(settings=s, base_config=lambda: base), CHOICES=DraftingScreen.CHOICES,
145                               query_one=lambda _cls: menu, paint=lambda: None, menu=lambda: menu)
146        DraftingScreen.on_mount(fake)
147        shown = DraftingScreen.CHOICES[menu.sel][0]
148        menu.current = SimpleNamespace(key=pick or shown)
149        DraftingScreen.commit(fake)
150        return shown, s.drafting
151
152    def test_the_step_shows_the_chosen_drafter_and_auto_replaces_it(self):
153        m, s = get_machine("nv_resident"), get_set("ud_q4_k_xl")
154        world = World(m, s).build()
155        try:
156            with world.patched():
157                rec = drive_launch(world, ("--drafting", "mtp"), setup_runs=False)
158                self.assertNotIn("failed", rec)
159                self.assertEqual(self.step(world, None), ("mtp", "mtp"), "the step shows the MTP that holds; left as it is it stays")
160                self.assertEqual(self.step(world, "auto"), ("mtp", "auto"), "Auto picked is written, so it replaces the MTP")
161        finally:
162            world.close()
163
164
165if __name__ == "__main__":
166    unittest.main()