okami.mom/strata

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

Niko1221Merge f-ctl-drafting-auto (d7cc382ed): Drafting Auto after Off starts with the drafter again7f5b34d1d

main
8.3 KiB162 linesraw
1"""Drafting Off (or MTP), then Auto again, in one scratch world: Auto starts the engine exactly as Auto did before (the same drafter, --spec, --draft-conf and
2batch), on every machine class and model set.  Found in the shipped 0.2.13.1 by the real-use rehearsal on an RTX PRO 5000 (REAL-USE-1, block (b)): after one
3`strata launch --drafting off`, `strata launch --drafting auto` started with no drafter (the Off line, --spec 4 --batch 4) and stayed so.  There the launch named
4--model-path, so setup ran at every launch: the Off launch's "--mtp off" left "mtp": false in the installed config, and Auto read that as "the draft layer is off".
5
6The Auto line compared with is the second Auto launch of the world: on the UD sets the first launch fetches the plain DFlash2 pack and the next one converts it
7for the selector (the same with Auto, Auto and nothing else), which is not what this test is about.  An explicit Off or MTP stays what it is, and a start
8without a --drafting word after Off stays Off.  Nothing real is used (tests/snapshot/README.md: scratch HOME, data folder, install folder).
9
10  python -m pytest tests/snapshot/test_drafting_round_trip.py -q -p no:cacheprovider
11"""
12
13from __future__ import annotations
14
15import json
16import sys
17import unittest
18from pathlib import Path
19
20ROOT = Path(__file__).resolve().parents[2]
21if str(ROOT) not in sys.path:
22    sys.path.insert(0, str(ROOT))
23
24from tests.snapshot.driver import drive_launch  # noqa: E402
25from tests.snapshot.matrix import MACHINES, MODEL_SETS  # noqa: E402
26from tests.snapshot.normalize import normalize  # noqa: E402
27from tests.snapshot.world import World  # noqa: E402
28
29
30TUI = "tui"
31
32
33def tui_drafting(world, pick):
34    """The TUI's Drafting step on this world's installed config, in a fresh launch (no choice in the settings yet): (the row it preselects, what its
35    commit leaves in the settings).  `pick` None: the person leaves the preselected row as it is."""
36    from types import SimpleNamespace
37    from strata_cli.launch import settings as S
38    from strata_cli.launch.screens import DraftingScreen
39    base = json.loads(world.config_path.read_text(encoding="utf-8"))
40    s = S.LaunchSettings(family=world.mset.family, model=world.mset.model)
41    menu = SimpleNamespace(columns=None, sel=None, current=None)
42    menu.set_items = lambda items, sel: setattr(menu, "sel", sel)
43    fake = SimpleNamespace(ctx=SimpleNamespace(settings=s, base_config=lambda: base), CHOICES=DraftingScreen.CHOICES,
44                           query_one=lambda _cls: menu, paint=lambda: None, menu=lambda: menu)
45    with world.patched():
46        DraftingScreen.on_mount(fake)
47        shown = DraftingScreen.CHOICES[menu.sel][0]
48        menu.current = SimpleNamespace(key=pick or shown)
49        DraftingScreen.commit(fake)
50    return shown, s.drafting
51
52
53def launches(machine, mset, steps, prepare=None):
54    """One world, one `strata launch` per (choice, setup_runs) step (choice None: no --drafting word; (TUI, pick): the TUI's Drafting step first, then the launch
55    with what it saved), in order; the normalized records (a TUI step's record also has "tui": (shown, saved)).  `prepare(world)` runs before the first step."""
56    world = World(machine, mset).build()
57    try:
58        if prepare is not None:
59            prepare(world)
60        out = []
61        for choice, runs in steps:
62            tui = None
63            if isinstance(choice, tuple) and choice[0] == TUI:
64                tui = tui_drafting(world, choice[1])
65                choice = tui[1]
66            with world.patched():
67                rec = drive_launch(world, () if choice is None else ("--drafting", choice), setup_runs=runs)
68            assert "failed" not in rec, rec.get("failed")
69            rec = normalize(rec, world)
70            if tui is not None:
71                rec["tui"] = tui
72            out.append(rec)
73        return out
74    finally:
75        world.close()
76
77
78def argv(rec: dict) -> list[str]:
79    return rec["engine"]["argv"]
80
81
82def drafter(rec: dict) -> str:
83    a = argv(rec)
84    return "dflash2" if "--draft" in a else "mtp" if "--mtp" in a else "off"
85
86
87class AutoAgainIsAuto(unittest.TestCase):
88    maxDiff = None
89
90    def cells(self, setup_runs=(False, True)):
91        for runs in setup_runs:
92            for m in MACHINES:
93                for s in MODEL_SETS:
94                    yield m, s, runs
95
96    def round_trip(self, middle: str, back: str = "auto"):
97        for m, s, runs in self.cells():
98            with self.subTest(machine=m.key, set=s.key, setup_runs=runs):
99                recs = launches(m, s, [("auto", runs), (back, runs), (middle, runs), (back, runs)])
100                self.assertEqual(drafter(recs[2]), middle, f"the explicit {middle} stays {middle}")
101                self.assertEqual(argv(recs[3]), argv(recs[1]), f"{back} after {middle} starts as {back} did before")
102                self.assertEqual(recs[3]["config_file"].get("drafting"), back)
103
104    def test_off_then_auto_is_auto(self):
105        self.round_trip("off")
106
107    def test_mtp_then_auto_is_auto(self):
108        self.round_trip("mtp")
109
110    def test_off_then_mtp_is_mtp(self):
111        self.round_trip("off", back="mtp")
112
113    def test_auto_after_off_runs_setup_again_when_the_install_would_be_reused(self):
114        # setup ran at the Off launch only (a change of context, a --model-path), the Auto launch after it would reuse the installed copy as it is
115        for m, s, _runs in self.cells(setup_runs=(True,)):
116            with self.subTest(machine=m.key, set=s.key):
117                recs = launches(m, s, [("auto", False), ("auto", False), ("off", True), ("auto", "when_needed")])
118                self.assertEqual(argv(recs[3]), argv(recs[1]), "Auto after Off starts as Auto did before")
119
120    def test_off_stays_off_at_a_start_without_a_drafting_word(self):
121        for m, s, runs in self.cells(setup_runs=(True,)):
122            if m.os == "macos":
123                continue                                     # a Mac's setup takes no --mtp word (runner.setup_args): Off is not written there, as before
124            with self.subTest(machine=m.key, set=s.key):
125                recs = launches(m, s, [("auto", runs), ("off", runs), (None, runs)])
126                self.assertEqual(argv(recs[2]), argv(recs[1]), "the Off of the launch before is kept (setup's \"mtp\": false)")
127
128    # the TUI (`strata launch` without --no-tui): its Drafting step shows Off where the installed config's draft layer is off and no Drafting choice is saved
129    def test_tui_off_then_auto_is_auto(self):
130        for m, s, runs in self.cells(setup_runs=(True,)):
131            if m.os == "macos":
132                continue
133            with self.subTest(machine=m.key, set=s.key):
134                recs = launches(m, s, [("auto", runs), ("auto", runs), ("off", runs), ((TUI, "auto"), runs)])
135                self.assertEqual(recs[3]["tui"], ("off", "auto"), "the step shows Off, and Auto picked is saved")
136                self.assertEqual(argv(recs[3]), argv(recs[1]), "Auto picked in the TUI after Off starts as Auto did before")
137
138    def test_tui_off_left_as_it_is_stays_off(self):
139        for m, s, runs in self.cells(setup_runs=(True,)):
140            if m.os == "macos":
141                continue
142            with self.subTest(machine=m.key, set=s.key):
143                recs = launches(m, s, [("auto", runs), ("off", runs), ((TUI, None), runs)])
144                self.assertEqual(recs[2]["tui"], ("off", None), "Off is shown, and leaving it writes nothing new")
145                self.assertEqual(argv(recs[2]), argv(recs[1]), "the Off line")
146
147    def test_tui_app_draft_layer_off_left_as_it_is_stays_off(self):
148        def app_turned_the_layer_off(world):                # the app's "Draft layer (MTP)" switch: "mtp": false in the run config, no "drafting" key
149            from strata_control import draft_layer
150            cfg = json.loads(world.config_path.read_text(encoding="utf-8"))
151            cfg["mtp"] = False
152            draft_layer.apply(cfg)
153            world.config_path.write_text(json.dumps(cfg, indent=1), encoding="utf-8")
154        for m, s, _runs in self.cells(setup_runs=(True,)):
155            with self.subTest(machine=m.key, set=s.key):
156                recs = launches(m, s, [((TUI, None), "when_needed")], prepare=app_turned_the_layer_off)
157                self.assertEqual(recs[0]["tui"], ("off", None), "Off is shown, and leaving it writes nothing new")
158                self.assertEqual(drafter(recs[0]), "off", "the draft layer stays off")
159
160
161if __name__ == "__main__":
162    unittest.main()