okami.mom/strata

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

Niko1221Merge main 6c642df75 into f-own-int (round 16: network waits, robustness, Windows kill-on-close job start, GitHub and transfer fixes)cd9745050

main
29.0 KiB579 linesraw
1"""An engine update beside a loaded model (owner, 11-01: "it updated the engine by itself mid-session and he had a model loaded").
2
3The rule under test: an update never starts by itself while a model is loaded; nothing replaces or removes the engine a running model uses; the
4update is the person's choice: warn naming the model, download while it keeps serving, stop it cleanly, update, ask whether to start it again with the
5same settings; a failed update leaves the old engine in use and the model can be started again; a script is never asked anything.
6
7Real pieces: the owner runtime starts and stops a real (stub) engine from the installed package, so "serving", "stopped" and "serving again on the new
8engine" are read from the runtime and from the file the stub engine writes when it starts.  Only the questions are scripted.
9"""
10from __future__ import annotations
11
12import argparse
13import contextlib
14import io
15import json
16import os
17import shutil
18import socket
19import sys
20import threading
21import time
22import unittest
23from pathlib import Path
24from unittest import mock
25
26sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
27from strata_cli import update_cmd  # noqa: E402
28from strata_control import engine_component as ec, engine_update, profiles, runtime, updater  # noqa: E402
29from tests.terminal import update_fixture as fx  # noqa: E402
30from tests.terminal.test_updater import PLATFORM, UpdaterCase  # noqa: E402
31
32PROFILE = "launch-demo"
33NAME = "Demo model"
34
35
36class Script:
37    """The person at the keyboard: answers in order, remembers every question."""
38
39    def __init__(self, *answers):
40        self.answers, self.asked = list(answers), []
41
42    def __call__(self, question, default):
43        self.asked.append((question, default))
44        return self.answers.pop(0) if self.answers else default
45
46
47def free_port() -> int:
48    with socket.socket() as s:
49        s.bind(("127.0.0.1", 0))
50        return s.getsockname()[1]
51
52
53class ModelCase(UpdaterCase):
54    def setUp(self):
55        super().setUp()
56        self.install_current("0.1.45")
57        self.lines: list[str] = []
58        self.events: list[dict] = []
59
60    # ------------------------------------------------------------------ a real loaded model
61    def start_model(self, profile=PROFILE, name=NAME, port=None):
62        cfg = json.loads(self.config.read_text())
63        cfg.update(exe=ec.REFERENCE_PREFIX + ec.COMPONENT_ID, backend="cuda", host="127.0.0.1", port=port or free_port(), model_name=name,
64                   log=str(self.root / f"{profile}.engine.log"))
65        cfg.pop("lib_dirs", None)
66        path = self.root / f"run-{profile}.json"
67        path.write_text(json.dumps(cfg))
68        profiles.create(profile, str(path))
69        got = runtime.start(profile, wait=60)
70        self.assertTrue(got.get("ok"), got)
71        self.addCleanup(self._stop, profile)
72        return profile
73
74    def _stop(self, profile):
75        try:
76            runtime.stop(profile, timeout=20)
77        except Exception:                                  # noqa: BLE001
78            pass
79
80    def state(self, profile=PROFILE):
81        return runtime.status(profile).get("state")
82
83    def engine_of_last_start(self):
84        """Which engine folder the stub engine ran from the last time it started."""
85        return Path((self.root / "ran.txt").read_text().splitlines()[0]).parent.name
86
87    # ------------------------------------------------------------------ the update
88    def gate(self, *answers, **flags):
89        self.script = Script(*answers)
90        ask = None if flags.pop("nobody", False) else self.script
91        return engine_update.ModelGate(ask=ask, say=self.lines.append, emit=self.events.append, **flags)
92
93    def update(self, gate, **over):
94        over.setdefault("serving", updater.serving_now)
95        ctx = self.ctx(events=self.events, **over)
96        return engine_update.update_with_models(ctx, gate, control=False)
97
98    def publish_new(self, version="0.1.46", source=None):
99        self.publish((version, source or fx.GOOD_ENGINE))
100
101    def said(self):
102        return " ".join(self.lines)
103
104
105class WithAModel(ModelCase):
106    def setUp(self):
107        super().setUp()
108        self.start_model()
109        self.publish_new()
110
111    # ---- yes, then start it again
112    def test_yes_and_start_again_stops_after_the_download_updates_and_starts_the_same_model_on_the_new_engine(self):
113        archives_when_stopped = []
114        real_stop = engine_update.stop_model
115
116        def stop(model):
117            archives_when_stopped.append(len(self.archive_requests()))
118            real_stop(model)
119        gate = self.gate(True, True)
120        gate._stop = stop
121        out = self.update(gate)
122        self.assertEqual((out["exit_code"], out["results"][0]["status"]), (0, "updated"), out)
123        self.assertEqual(archives_when_stopped, [1], "the new engine was downloaded while the model kept serving; it was stopped after")
124        self.assertEqual(self.state(), "ready", "the model is serving again")
125        self.assertEqual(self.resolved(), "0.1.46")
126        self.assertEqual(self.engine_of_last_start(), f"0.1.46-{PLATFORM}-cuda-cuda13", "the restarted model runs on the NEW engine")
127        # the warning came first, named the model, and said what would happen
128        first, second = self.script.asked
129        self.assertIn(NAME, first[0])
130        self.assertFalse(first[1], "stopping a model is never the default answer")
131        self.assertIn(NAME, second[0])
132        self.assertIn("same settings", second[0])
133        self.assertTrue(second[1])
134        self.assertIn(NAME, self.said())
135        self.assertIn("keeps serving", self.said())
136        phases = [e.get("phase") for e in self.events if e.get("event") == "models"]
137        self.assertEqual(phases, ["consent", "stopping", "stopped", "restarting", "restarted"])
138        self.assertEqual(out["models"]["restarts"][0]["restarted"], True)
139        self.assert_user_data_untouched()
140
141    def test_the_old_engine_stays_installed_and_the_restart_uses_the_saved_settings_untouched(self):
142        before = (profiles.load(PROFILE)[0], Path(profiles.load(PROFILE)[0]["source_config"]).read_bytes())
143        self.update(self.gate(True, True))
144        after = (profiles.load(PROFILE)[0], Path(profiles.load(PROFILE)[0]["source_config"]).read_bytes())
145        self.assertEqual(before, after, "the model's profile and run config are exactly what they were")
146        self.assertEqual(self.engine_folders(), [f"0.1.45-{PLATFORM}-cuda-cuda13", f"0.1.46-{PLATFORM}-cuda-cuda13"])
147
148    # ---- yes, but do not start it again
149    def test_yes_and_no_to_start_again_leaves_it_stopped_and_says_how_to_start_it(self):
150        out = self.update(self.gate(True, False))
151        self.assertEqual(out["exit_code"], 0)
152        self.assertEqual(self.state(), "stopped")
153        self.assertEqual(self.resolved(), "0.1.46")
154        self.assertIn("is stopped. Start it when you want with", self.said())
155        self.assertEqual(out["models"]["restarts"][0]["restarted"], False)
156        self.assertEqual([e["phase"] for e in self.events if e.get("event") == "models"][-1], "left-stopped")
157
158    # ---- no
159    def test_no_changes_nothing_downloads_nothing_and_the_model_keeps_serving(self):
160        with self.assertRaises(engine_update.Declined) as caught:
161            self.update(self.gate(False))
162        self.assertEqual(caught.exception.exit_code, 0)
163        self.assertEqual(self.state(), "ready")
164        self.assertEqual(self.resolved(), "0.1.45")
165        self.assertEqual(self.archive_requests(), [], "nothing was downloaded")
166        self.assertEqual(len(self.script.asked), 1)
167
168    # ---- the update fails
169    def test_a_new_engine_that_will_not_start_leaves_the_old_one_in_use_and_the_model_can_be_started_again(self):
170        self.publish_new(source=fx.BAD_ENGINE)
171        out = self.update(self.gate(True, True))
172        self.assertEqual(out["exit_code"], 6, out)
173        self.assertEqual(out["results"][0]["status"], "failed")
174        self.assertEqual(self.resolved(), "0.1.45", "the old engine is still the one in use")
175        self.assertEqual(self.engine_folders(), [f"0.1.45-{PLATFORM}-cuda-cuda13"], "the engine that failed is not installed")
176        self.assertEqual(self.state(), "ready", "the model was started again on the old engine")
177        self.assertEqual(self.engine_of_last_start(), f"0.1.45-{PLATFORM}-cuda-cuda13")
178        question = self.script.asked[1][0]
179        self.assertIn("old engine is unchanged", question)
180        self.assertIn(NAME, question)
181
182    def test_a_failed_update_and_no_to_start_again_leaves_the_model_stopped_with_the_old_engine(self):
183        self.publish_new(source=fx.BAD_ENGINE)
184        out = self.update(self.gate(True, False))
185        self.assertEqual(out["exit_code"], 6)
186        self.assertEqual(self.state(), "stopped")
187        self.assertEqual(self.resolved(), "0.1.45")
188
189    def test_a_download_that_fails_never_stops_the_model(self):
190        (next((self.release / "engine").glob("*.tar.gz"))).unlink()     # the server answers 404 for the archive (a cut connection is resumed in the same run now)
191        out = self.update(self.gate(True, True))
192        self.assertEqual(out["exit_code"], 6, out)
193        self.assertEqual(self.state(), "ready", "the model was not stopped for a download that failed")
194        self.assertEqual(self.resolved(), "0.1.45")
195        self.assertEqual(out["models"]["stopped"], [])
196        self.assertEqual(len(self.script.asked), 1, "no 'start it again' question: it was never stopped")
197
198    # ---- the model does not start again
199    def test_a_model_that_does_not_start_again_is_said_plainly_and_the_exit_code_is_8(self):
200        gate = self.gate(True, True)
201        real_stop = engine_update.stop_model
202
203        def stop_and_break(model):
204            real_stop(model)
205            Path(profiles.load(PROFILE)[0]["source_config"]).write_text("{ not a run config")        # whatever would stop it starting
206        gate._stop = stop_and_break
207        out = self.update(gate)
208        self.assertEqual(out["exit_code"], engine_update.EXIT_NOT_RESTARTED, out)
209        self.assertEqual(out["results"][0]["status"], "updated", "the update itself is done and stays")
210        self.assertEqual(self.resolved(), "0.1.46")
211        self.assertIn("did not start again", self.said())
212        self.assertEqual(self.state(), "stopped", "nothing is left half alive")
213        self.assertEqual([r["restarted"] for r in out["models"]["restarts"]], [False])
214
215    # ---- nobody can be asked
216    def test_a_script_is_never_asked_and_nothing_is_downloaded_or_changed(self):
217        with self.assertRaises(updater.UpdateError) as caught:
218            self.update(self.gate(nobody=True))
219        self.assertEqual(caught.exception.exit_code, 7)
220        text = str(caught.exception)
221        self.assertIn(NAME, text)
222        self.assertIn("--stop-model", text)
223        self.assertIn("strata launch --stop", text)
224        self.assertIn("nothing was changed", text)
225        self.assertEqual(self.archive_requests(), [])
226        self.assertEqual((self.state(), self.resolved()), ("ready", "0.1.45"))
227
228    def test_stop_model_stops_updates_and_leaves_it_stopped_when_start_again_is_not_given(self):
229        out = self.update(self.gate(nobody=True, allow_stop=True))
230        self.assertEqual(out["exit_code"], 0)
231        self.assertEqual((self.state(), self.resolved()), ("stopped", "0.1.46"))
232        self.assertIn("Start it when you want with", self.said())
233
234    def test_stop_model_and_start_again_in_a_script_do_it_all_without_a_question(self):
235        gate = self.gate(nobody=True, allow_stop=True, start_again=True)
236        out = self.update(gate)
237        self.assertEqual(out["exit_code"], 0)
238        self.assertEqual(self.state(), "ready")
239        self.assertEqual(self.engine_of_last_start(), f"0.1.46-{PLATFORM}-cuda-cuda13")
240        self.assertEqual(self.script.asked, [])
241
242    def test_start_again_after_a_failed_update_puts_the_model_back_on_the_old_engine(self):
243        self.publish_new(source=fx.BAD_ENGINE)
244        out = self.update(self.gate(nobody=True, allow_stop=True, start_again=True))
245        self.assertEqual(out["exit_code"], 6)
246        self.assertEqual((self.state(), self.resolved()), ("ready", "0.1.45"))
247
248    # ---- a server nobody here started (a service)
249    def test_a_server_that_strata_did_not_start_is_never_stopped_even_with_stop_model(self):
250        with self.assertRaises(updater.UpdateError) as caught:
251            self.update(self.gate(nobody=True, allow_stop=True), serving=lambda: [{"profile": "a running Strata server", "state": "serving"}])
252        self.assertEqual(caught.exception.exit_code, 7)
253        self.assertIn("did not start it from here", str(caught.exception))
254        self.assertIn("Stop it yourself", str(caught.exception))
255        self.assertEqual(self.archive_requests(), [])
256        self.assertEqual(self.state(), "ready")
257
258    # ---- offline and a feed that does not answer
259    def test_an_unreachable_feed_is_said_before_anything_is_stopped(self):
260        for dead in ("http://127.0.0.1:9/strata-feed.json", str(self.root / "no-such-feed")):
261            with self.assertRaises(Exception) as caught:
262                self.update(self.gate(True, True), source=dead)
263            self.assertTrue("could not be read" in str(caught.exception) or "so the update check could not run" in str(caught.exception),
264                            str(caught.exception))            # a folder that is gone: the old sentence; a host nobody answers for: the network rule's (W7)
265            self.assertEqual(self.state(), "ready", dead)
266        self.assertEqual(self.resolved(), "0.1.45")
267
268    def test_a_feed_that_never_answers_gives_up_and_leaves_the_model_alone(self):
269        hang = socket.socket()
270        hang.bind(("127.0.0.1", 0))
271        hang.listen(5)
272        self.addCleanup(hang.close)
273        started = time.monotonic()
274        with self.assertRaises(Exception) as caught:
275            self.update(self.gate(True, True), source=f"http://127.0.0.1:{hang.getsockname()[1]}/strata-feed.json", feed_timeout=1.0)
276        self.assertLess(time.monotonic() - started, 20)
277        self.assertIn("did not answer within", str(caught.exception))       # the network rule (W7): the host, and that nothing was changed
278        self.assertIn("so the update check could not run", str(caught.exception))
279        self.assertEqual((self.state(), self.resolved()), ("ready", "0.1.45"))
280
281    def test_nothing_to_update_asks_nothing_and_leaves_the_model_alone(self):
282        self.publish((("0.1.45", fx.GOOD_ENGINE)))
283        out = self.update(self.gate(True, True))
284        self.assertEqual((out["exit_code"], out["results"][0]["status"]), (0, "current"))
285        self.assertEqual(self.script.asked, [])
286        self.assertEqual(self.state(), "ready")
287
288
289class StartedDuringTheUpdate(ModelCase):
290    """A model started after the person said yes is a different model: nobody agreed to stop it."""
291
292    def setUp(self):
293        super().setUp()
294        self.start_model()
295        self.publish_new()
296
297    def run_update(self, gate):
298        """Runs the update; a second model is started as soon as the download is done (before the engine is put in place)."""
299        real = updater._download
300
301        def download(*args, **kwargs):
302            got = real(*args, **kwargs)
303            self.start_model("launch-second", "Second model")
304            return got
305        ctx = self.ctx(serving=updater.serving_now, events=self.events)
306        with mock.patch.object(updater, "_download", download):
307            return engine_update.update_with_models(ctx, gate, control=False)
308
309    def test_in_a_script_the_new_model_is_refused_and_nothing_more_is_changed(self):
310        out = self.run_update(self.gate(nobody=True, allow_stop=True, start_again=True))
311        self.assertEqual(out["exit_code"], 7)
312        self.assertEqual(out["results"][0]["status"], "failed")
313        self.assertIn("Second model", out["results"][0]["error"])
314        self.assertIn("started while the update was running", out["results"][0]["error"])
315        self.assertIn("the download is kept", out["results"][0]["error"])
316        self.assertEqual(self.resolved(), "0.1.45")
317        self.assertEqual(self.state("launch-second"), "ready", "the model nobody agreed to stop was not stopped")
318        self.assertEqual(self.state(PROFILE), "ready", "nothing was stopped at all")
319
320    def test_at_the_keyboard_the_person_is_asked_again_and_both_come_back(self):
321        out = self.run_update(self.gate(True, True, True, True))
322        self.assertEqual(out["exit_code"], 0, out)
323        self.assertEqual(self.resolved(), "0.1.46")
324        self.assertEqual((self.state(PROFILE), self.state("launch-second")), ("ready", "ready"))
325        self.assertTrue(any("Second model" in q for q, _ in self.script.asked))
326
327    def test_at_the_keyboard_no_to_the_new_model_changes_nothing_more(self):
328        out = self.run_update(self.gate(True, False))
329        self.assertEqual(out["exit_code"], 7)
330        self.assertEqual(self.resolved(), "0.1.45")
331        self.assertEqual((self.state("launch-second"), self.state(PROFILE)), ("ready", "ready"), "nothing was stopped")
332
333
334class TwoTerminals(ModelCase):
335    def setUp(self):
336        super().setUp()
337        self.start_model()
338        self.publish_new()
339
340    def test_a_second_update_while_the_first_runs_is_refused_and_stops_nothing(self):
341        with updater.update_lock(self.components):
342            with self.assertRaises(updater.UpdateError) as caught:
343                self.update(self.gate(True, True))
344        self.assertEqual(caught.exception.exit_code, 7)
345        self.assertIn("another update is already running", str(caught.exception))
346        self.assertEqual((self.state(), self.resolved()), ("ready", "0.1.45"))
347        self.assertEqual(self.script.asked, [], "the model was not even asked about: the lock comes first")
348
349    def test_two_updates_at_once_stop_the_model_once_and_start_it_once(self):
350        results = []
351
352        def go():
353            try:
354                results.append(("ok", self.update(self.gate(True, True))["exit_code"]))
355            except updater.UpdateError as exc:
356                results.append(("refused", exc.exit_code))
357        threads = [threading.Thread(target=go) for _ in range(2)]
358        for t in threads:
359            t.start()
360        for t in threads:
361            t.join(180)
362        self.assertEqual(sorted(results), [("ok", 0), ("refused", 7)], results)
363        self.assertEqual((self.state(), self.resolved()), ("ready", "0.1.46"))
364
365
366class WithoutAGate(ModelCase):
367    """Anything that runs the update without the questions (the app's button today, a library caller) is refused BEFORE a download, whole."""
368
369    def setUp(self):
370        super().setUp()
371        self.start_model()
372
373    def bundle(self):
374        folder = self.root / "control-bundle"
375        (folder / "strata_control").mkdir(parents=True)
376        (folder / "strata.py").write_text("print('strata 0.1.46 (python stub)')\n")
377        (folder / "strata_control" / "__init__.py").write_text("")
378        from feed_tool import build_feed, pack_control
379        (self.release / "control").mkdir()
380        pack_control(folder, self.release / "control", version="0.1.46", platform=PLATFORM)
381        build_feed(self.release, key=self.key, sequence=self.sequence + 1, engine_dir=self.release / "engine", control_dir=self.release / "control")
382
383    def test_engine_and_control_are_both_left_alone_and_nothing_is_downloaded(self):
384        self.publish_new()
385        self.bundle()
386        with self.assertRaises(updater.Busy) as caught:
387            updater.run_update(self.ctx(serving=updater.serving_now))
388        self.assertEqual(caught.exception.exit_code, 7)
389        self.assertEqual(self.archive_requests(), [], "no download beside a loaded model")
390        self.assertIsNone(updater.active_control(self.components), "Control did not move on while the engine was refused")
391        self.assertEqual((self.state(), self.resolved()), ("ready", "0.1.45"))
392
393    def test_nothing_to_install_is_not_a_busy_error(self):
394        self.publish((("0.1.45", fx.GOOD_ENGINE)))
395        out = updater.run_update(self.ctx(serving=updater.serving_now), control=False)
396        self.assertEqual(out["exit_code"], 0)
397
398    def test_wait_lets_the_model_finish_first(self):
399        self.publish_new()
400        answers = [[{"profile": PROFILE}], [{"profile": PROFILE}], [], [], []]
401        out = updater.run_update(self.ctx(serving=lambda: answers.pop(0) if answers else [], wait=30), control=False)
402        self.assertEqual(out["results"][0]["status"], "updated")
403
404
405class TheCommand(ModelCase):
406    """`strata update` as a person or a script runs it."""
407
408    def setUp(self):
409        super().setUp()
410        self.start_model()
411        self.publish_new()
412        sp = argparse.ArgumentParser().add_subparsers(dest="command")
413        comp = sp.add_parser("components").add_subparsers(dest="components_command")
414        update_cmd.add_parsers(sp, comp)
415        self.parser = sp
416
417    def run_cmd(self, *flags, asks=None):
418        argv = ["update", "--feed", self.server.url + "/strata-feed.json", "--components-dir", str(self.components), "--no-control",
419                "--model-config", str(self.config), *flags]
420        a = self.parser.choices["update"].parse_args(argv[1:])
421        a.command, a.components_command = "update", None
422        out, err = io.StringIO(), io.StringIO()
423        with mock.patch.object(update_cmd, "_ask_factory", return_value=asks), contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
424            code = update_cmd.run(a)
425        return code, out.getvalue(), err.getvalue()
426
427    def test_yes_alone_never_stops_a_model(self):
428        code, out, err = self.run_cmd("--yes")
429        self.assertEqual(code, 7)
430        self.assertIn(NAME, err)
431        self.assertIn("--stop-model", err)
432        self.assertEqual((self.state(), self.resolved()), ("ready", "0.1.45"))
433        self.assertEqual(self.archive_requests(), [])
434
435    def test_stop_model_and_start_again(self):
436        code, out, err = self.run_cmd("--yes", "--stop-model", "--start-again")
437        self.assertEqual(code, 0, (out, err))
438        self.assertIn("Engine", out)
439        self.assertIn("serving again with the same settings", out)
440        self.assertEqual((self.state(), self.resolved()), ("ready", "0.1.46"))
441
442    def test_stop_model_alone_leaves_it_stopped_and_prints_the_start_line(self):
443        code, out, err = self.run_cmd("--yes", "--stop-model")
444        self.assertEqual(code, 0, (out, err))
445        self.assertIn("is stopped. Start it when you want with", out)
446        self.assertEqual(self.state(), "stopped")
447
448    def test_the_questions_in_a_terminal(self):
449        asks = Script(True, True)
450        code, out, err = self.run_cmd(asks=asks)
451        self.assertEqual(code, 0, (out, err))
452        self.assertEqual(len(asks.asked), 2)
453        self.assertEqual((self.state(), self.resolved()), ("ready", "0.1.46"))
454
455    def test_no_in_a_terminal_exits_0_and_says_nothing_was_changed(self):
456        code, out, err = self.run_cmd(asks=Script(False))
457        self.assertEqual(code, 0)
458        self.assertIn("Nothing was changed", out)
459        self.assertEqual((self.state(), self.resolved()), ("ready", "0.1.45"))
460
461    def test_the_exit_code_when_a_model_does_not_start_again_is_8(self):
462        real = engine_update.start_model
463        with mock.patch.object(engine_update, "start_model", return_value=(False, "Demo model did not start again: out of memory.")):
464            code, out, err = self.run_cmd("--yes", "--stop-model", "--start-again")
465        self.assertEqual(code, 8, (out, err))
466        self.assertIn("did not start again", out)
467        self.assertIn("the new engine is in use", out)
468        self.assertEqual(self.resolved(), "0.1.46")
469        del real
470
471    def test_machine_output_has_the_models_and_never_a_question(self):
472        code, out, err = self.run_cmd("--output", "json", "--stop-model", "--start-again")
473        self.assertEqual(code, 0, (out, err))
474        data = json.loads(out)
475        self.assertTrue(data["ok"])
476        self.assertEqual(data["models"]["stopped"][0]["name"], NAME)
477        self.assertTrue(data["models"]["restarts"][0]["restarted"])
478
479    def test_machine_output_with_a_model_and_no_flag_is_error_7_as_json(self):
480        code, out, err = self.run_cmd("--output", "json")
481        self.assertEqual(code, 7)
482        data = json.loads(out)
483        self.assertFalse(data["ok"])
484        self.assertEqual(data["error"]["code"], 7)
485        self.assertIn(NAME, data["error"]["message"])
486
487    def test_jsonl_carries_the_model_events_for_the_app(self):
488        code, out, err = self.run_cmd("--output", "jsonl", "--stop-model", "--start-again")
489        self.assertEqual(code, 0, (out, err))
490        events = [json.loads(line) for line in out.splitlines() if line.startswith("{")]
491        phases = [e["phase"] for e in events if e.get("event") == "models"]
492        self.assertEqual(phases, ["consent", "stopping", "stopped", "restarting", "restarted"])
493        self.assertEqual(events[[e.get("phase") for e in events].index("consent")]["models"][0]["profile"], PROFILE)
494
495    def test_check_names_the_model_and_the_one_next_step(self):
496        code, out, err = self.run_cmd("--check")
497        self.assertEqual(code, 0)
498        self.assertIn(NAME, out)
499        self.assertIn("asks before it stops it", out)
500        self.assertEqual((self.state(), self.resolved()), ("ready", "0.1.45"), "a check changes nothing")
501
502
503class AfterTheStop(unittest.TestCase):
504    """Found by the real DeepSeek flow: right after a big model was stopped, the next look still saw 'a running Strata server' (its engine had not let
505    go of the shared lease yet) and the update was refused half way."""
506
507    def gate(self, **kw):
508        stopped = []
509        asked = []
510        gate = engine_update.ModelGate(ask=lambda q, d: asked.append(q) or True, stop=stopped.append, start=lambda m: (True, "ok"), **kw)
511        model = engine_update.RunningModel("launch-x", "X", port=8080)
512        gate.consented["launch-x"] = model
513        gate.asked, gate.stops = asked, stopped
514        return gate, model
515
516    def test_the_update_waits_until_the_stopped_engine_has_let_go(self):
517        gate, _ = self.gate(settle_s=30)
518        answers = [[{"profile": "launch-x"}], [{"profile": "a running Strata server"}], [{"profile": "a running Strata server"}], []]
519        with mock.patch("time.sleep"):
520            gate.release(lambda: answers.pop(0) if answers else [])
521        self.assertEqual(len(gate.stops), 1)
522        self.assertEqual(answers, [], "it looked until nothing was serving")
523
524    def test_an_engine_that_never_lets_go_is_said_plainly_and_nothing_more_is_changed(self):
525        gate, _ = self.gate(settle_s=0.3)
526        calls = {"n": 0}
527
528        def serving():
529            calls["n"] += 1
530            return [{"profile": "launch-x"}] if calls["n"] == 1 else [{"profile": "a running Strata server"}]
531        with self.assertRaises(updater.UpdateError) as caught:
532            gate.release(serving)
533        self.assertEqual(caught.exception.exit_code, 7)
534        self.assertIn("has not let go of the graphics card", str(caught.exception))
535
536    def test_the_start_again_question_says_same_settings_when_part_of_the_update_was_made(self):
537        for changed, text in ((True, "with the same settings"), (False, "The old engine is unchanged")):
538            gate, model = self.gate()
539            gate.stopped.append(model)
540            gate.finish(False, changed)
541            self.assertIn(text, gate.asked[0], changed)
542
543
544class StartWait(unittest.TestCase):
545    """Found by the real DeepSeek flow: a DeepSeek run config asks for a long engine wait; runtime.start takes 0..1800 only, so the model did not start again."""
546
547    def test_the_wait_never_exceeds_what_the_runtime_accepts(self):
548        import tempfile
549        with tempfile.TemporaryDirectory() as d:
550            cfg = Path(d) / "run.json"
551            for ready, want in ((None, 960.0), (300, 360.0), (1800, 1800.0), (5000, 1800.0)):
552                cfg.write_text(json.dumps({"engine_ready_s": ready} if ready else {}))
553                model = engine_update.RunningModel("launch-x", "X")
554                with mock.patch.object(profiles, "load", return_value=({"source_config": str(cfg)}, "r")):
555                    self.assertEqual(engine_update._start_wait(model), want, ready)
556
557
558class TheQuestion(unittest.TestCase):
559    def test_a_person_at_a_keyboard_gets_the_question_and_default_on_enter(self):
560        a = argparse.Namespace(yes=False)
561        with mock.patch.object(sys.stdin, "isatty", return_value=True), mock.patch.object(sys.stdout, "isatty", return_value=True):
562            ask = update_cmd._ask_factory(a, False)
563            self.assertIsNotNone(ask)
564            for typed, default, want in (("", False, False), ("", True, True), ("y", False, True), ("Yes", False, True), ("n", True, False), ("what", True, False)):
565                with mock.patch("builtins.input", return_value=typed):
566                    self.assertEqual(ask("q?", default), want, (typed, default))
567            with mock.patch("builtins.input", side_effect=EOFError):
568                self.assertFalse(ask("q?", False))
569
570    def test_nobody_is_asked_for_a_program_a_pipe_or_yes(self):
571        with mock.patch.object(sys.stdin, "isatty", return_value=True), mock.patch.object(sys.stdout, "isatty", return_value=True):
572            self.assertIsNone(update_cmd._ask_factory(argparse.Namespace(yes=True), False))
573            self.assertIsNone(update_cmd._ask_factory(argparse.Namespace(yes=False), True))
574        with mock.patch.object(sys.stdin, "isatty", return_value=False):
575            self.assertIsNone(update_cmd._ask_factory(argparse.Namespace(yes=False), False))
576
577
578if __name__ == "__main__":
579    unittest.main()