okami.mom/strata

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

Niko1221Merge main 7726f80cb (local, 11-10 14:08) into f-own-int714ff8242

main
94.9 KiB1576 linesraw
1"""Managed local instance lifecycle with an owned fake engine process."""
2
3import io
4import hashlib
5import json
6import os
7import queue
8import signal
9import socket
10import subprocess
11import sys
12import tempfile
13import threading
14import time
15import unittest
16import urllib.request
17from contextlib import redirect_stdout
18from pathlib import Path
19from unittest import mock
20
21from strata_cli.cli import main
22from strata_cli import bench
23from strata_cli.client import Endpoint
24from strata_control import calibration, journal, management, owner_transport, procs, profiles, recipes, runtime
25
26
27WINDOWS = os.name == "nt"
28
29
30@unittest.skipUnless(os.name in ("posix", "nt"), "no qualified owner transport on this platform")
31class RuntimeTests(unittest.TestCase):
32    def setUp(self):
33        self.temp = tempfile.TemporaryDirectory(prefix="strata-runtime-test-")
34        self.addCleanup(self._remove_temp)
35        self.root = Path(self.temp.name)
36        env = mock.patch.dict(os.environ, {"STRATA_PROFILE_DIR": str(self.root / "profiles"),
37                                       "STRATA_RUNTIME_DIR": str(self.root / "runtime")})
38        env.start()
39        self.addCleanup(env.stop)
40        previous_key = os.environ.pop("STRATA_API_KEY", None)
41        self.addCleanup(lambda: os.environ.__setitem__("STRATA_API_KEY", previous_key)
42                        if previous_key is not None else os.environ.pop("STRATA_API_KEY", None))
43        engine = self.root / "engine.py"
44        engine.write_text("#!" + sys.executable + "\nimport sys\nfrom pathlib import Path\n"
45                          "if '--batch' in sys.argv: print('INFO batch_slots=2', flush=True)\n"
46                          "print('READY 4096 stop', flush=True)\n"
47                          "for line in sys.stdin:\n"
48                          "    if line.strip() == 'QUIT': break\n"
49                          "    if line.startswith(('GEN ', 'BGEN ')):\n"
50                          "        slot = int(line.split()[1]) if line.startswith('BGEN ') else None\n"
51                          "        if Path('fail-generation').exists():\n"
52                          "            print('ERR generation-failed', flush=True)\n"
53                          "            continue\n"
54                          "        if Path('empty-generation').exists():\n"
55                          "            print('DONE 0 1 1.0 0.0 stop 0 0 0', flush=True)\n"
56                          "            if slot is not None: print(f'BADM {slot} 0', flush=True)\n"
57                          "            continue\n"
58                          "        print('T 97', flush=True)\n"
59                          "        print('DONE 1 1 1.0 1.0 length 0 0 0', flush=True)\n"
60                          "        if slot is not None: print(f'BADM {slot} 0', flush=True)\n", encoding="utf-8")
61        engine.chmod(0o700)
62        if WINDOWS:
63            # a script cannot be an engine exe on Windows: a .cmd that runs it stands in for the binary
64            wrapper = self.root / "engine.cmd"
65            wrapper.write_bytes(f'@echo off\r\n"{sys.executable}" "{engine}" %*\r\n'.encode())
66            engine = wrapper
67        from tools.strata_tokenizer import BYTE_TO_UNICODE
68        tokenizer = self.root / "tokenizer"
69        tokenizer.mkdir()
70        tokens = [BYTE_TO_UNICODE[i] for i in range(256)] + [
71            "ab", "<|im_start|>", "<|im_end|>", "<|endoftext|>"]
72        (tokenizer / "vocab.json").write_text(json.dumps({token: i for i, token in enumerate(tokens)}))
73        (tokenizer / "merges.txt").write_text("a b")
74        (tokenizer / "token_type.json").write_text(json.dumps([0] * 257 + [3, 3, 3]))
75        self.config = self.root / "run.json"
76        self.config.write_text(json.dumps({"exe": str(engine), "tokenizer": str(tokenizer),
77                                            "args": [], "cwd": str(self.root), "model_name": "fake",
78                                            "host": "127.0.0.1", "port": 0}), encoding="utf-8")
79        profiles.create("local", str(self.config))
80        self.addCleanup(self._stop)
81
82    def _remove_temp(self):
83        # On Windows the stopped host can still hold runtime\local.host.log for a moment while it exits (seen on a GitHub runner): retry for
84        # up to 10 s, then fail with the path that stayed open
85        deadline = time.monotonic() + 10
86        while True:
87            try:
88                self.temp.cleanup()
89                return
90            except PermissionError:
91                if time.monotonic() > deadline:
92                    raise
93                time.sleep(0.25)
94
95    def _stop(self):
96        try:
97            if runtime._read_state("local") is not None:
98                runtime.stop("local", timeout=12)
99        except (OSError, profiles.ProfileError):
100            pass
101
102    def _cli(self, *args):
103        output = io.StringIO()
104        with redirect_stdout(output):
105            code = main(["runtime", *args, "--output", "json"])
106        return code, json.loads(output.getvalue())
107
108    def test_component_inspection_bridge_is_read_only_and_reports_missing_files(self):
109        command = [sys.executable, "-m", "strata_control.management"]
110        root = Path(__file__).resolve().parents[2]
111
112        def send(live):
113            request = {"schema_version": 1, "action": "components.inspect",
114                       "profile": "local", "params": {"live": live}}
115            completed = subprocess.run(command, input=json.dumps(request), text=True,
116                                       capture_output=True, cwd=root, env=os.environ.copy(), timeout=15)
117            return completed.returncode, json.loads(completed.stdout)
118
119        code, result = send(False)
120        self.assertEqual(code, 0)
121        self.assertTrue(result["ok"])
122        self.assertTrue(result["report"]["ok"])
123        self.assertEqual(result["report"]["profile"], "local")
124        self.assertEqual(Path(result["report"]["source_config"]), self.config.resolve())
125        self.assertIsNone(result["report"]["live_gpu_probe"])
126        self.assertEqual(journal.list_runs("local"), [])
127        self.assertEqual(runtime.status("local")["state"], "stopped")
128
129        code, invalid = send("true")
130        self.assertEqual((code, invalid["ok"]), (2, False))
131        self.assertIn("live must be true or false", invalid["error"])
132        engine = self.root / ("engine.cmd" if WINDOWS else "engine.py")
133        engine.unlink()
134        code, missing = send(False)
135        self.assertEqual((code, missing["ok"], missing["report"]["ok"]), (0, True, False))
136        self.assertIn("engine", [row["name"] for row in missing["report"]["components"]
137                      if row["status"] == "missing"])
138        self.assertEqual(journal.list_runs("local"), [])
139
140    def test_profile_change_bridge_reviews_revision_source_and_typed_overrides(self):
141        command = [sys.executable, "-m", "strata_control.management"]
142        root = Path(__file__).resolve().parents[2]
143
144        def send(action, params):
145            request = {"schema_version": 1, "action": action, "profile": "local", "params": params}
146            completed = subprocess.run(command, input=json.dumps(request), text=True,
147                                       capture_output=True, cwd=root, env=os.environ.copy(), timeout=15)
148            return completed.returncode, json.loads(completed.stdout)
149
150        other = self.root / "strata-other.json"
151        other.write_text(self.config.read_text().replace('"fake"', '"other"'), encoding="utf-8")
152        with mock.patch.dict(os.environ, {"STRATA_INSTALL_DIR": str(self.root)}):
153            code, listed = send("models.installed", {})
154            inspect_code, inspected = send("models.inspect", {"model_id": "other"})
155        self.assertEqual(code, 0)
156        self.assertIn("other", [item["id"] for item in listed["inventory"]["models"]])
157        self.assertEqual((inspect_code, inspected["ok"]), (0, True))
158        self.assertEqual(inspected["inspection"]["model"]["id"], "other")
159        self.assertEqual(journal.list_runs("local"), [])
160        candidate = self.root / "candidate.gguf"
161        candidate.write_bytes(b"GGUF" + (3).to_bytes(4, "little"))
162        code, import_plan = send("models.import.plan", {"path": str(candidate)})
163        self.assertEqual((code, import_plan["ok"]), (0, True))
164        self.assertFalse(import_plan["plan"]["would_write"])
165        self.assertEqual(import_plan["plan"]["execution_compatibility"], "unverified")
166        code, invalid_import = send("models.import.plan", {"path": "relative.gguf"})
167        self.assertEqual((code, invalid_import["ok"]), (2, False))
168        code, current = send("profile.inspect", {})
169        self.assertEqual((code, current["ok"], current["profile"]["id"]), (0, True, "local"))
170        self.assertEqual(current["profile"]["overrides"], {})
171        edits = {"overrides": {"parallel": 4, "batch_groups": "auto", "max_queue": 8,
172                               "queue_timeout": 2.5}, "source_config": str(other)}
173        code, plan = send("profile.change.plan", {**edits, "if_revision": current["revision"]})
174        self.assertEqual((code, plan["ok"], plan["plan"]["would_save"]), (0, True, True))
175        self.assertEqual(plan["plan"]["revision"], current["revision"])
176        self.assertEqual(plan["plan"]["effective"]["parallel"], 4)
177        self.assertEqual(plan["plan"]["source_config_after"], str(other.resolve()))
178        self.assertEqual(profiles.load("local")[0]["source_config"], str(self.config.resolve()))
179        self.assertEqual(journal.list_runs("local"), [])
180
181        execute = {**edits, "if_revision": plan["plan"]["revision"],
182                   "if_source_sha256": plan["plan"]["source_sha256"]}
183        profiles.set_values("local", ["max_queue=1"])
184        code, stale = send("profile.change", execute)
185        self.assertEqual((code, stale["ok"]), (6, False))
186        self.assertIn("changed after review", stale["error"])
187        code, stale_plan = send("profile.change.plan", {**edits, "if_revision": current["revision"]})
188        self.assertEqual((code, stale_plan["ok"]), (6, False))
189        code, plan = send("profile.change.plan", {**edits,
190            "if_revision": profiles.load("local")[1]})
191        execute.update(if_revision=plan["plan"]["revision"],
192                       if_source_sha256=plan["plan"]["source_sha256"])
193        other.write_text(other.read_text() + "\n", encoding="utf-8")
194        code, changed_source = send("profile.change", execute)
195        self.assertEqual((code, changed_source["ok"]), (6, False))
196        code, plan = send("profile.change.plan", {**edits,
197            "if_revision": profiles.load("local")[1]})
198        execute.update(if_revision=plan["plan"]["revision"],
199                       if_source_sha256=plan["plan"]["source_sha256"])
200        code, saved = send("profile.change", execute)
201        self.assertEqual((code, saved["ok"], saved["saved"]), (0, True, True))
202        self.assertEqual(profiles.load("local")[0]["source_config"], str(other.resolve()))
203        self.assertEqual(profiles.load("local")[0]["overrides"], edits["overrides"])
204        self.assertEqual(runtime.status("local")["state"], "stopped")
205        self.assertEqual(journal.list_runs("local"), [])
206
207        code, invalid = send("profile.change.plan", {"overrides": {"parallel": True},
208            "source_config": str(other), "if_revision": profiles.load("local")[1]})
209        self.assertEqual((code, invalid["ok"]), (2, False))
210
211        started = runtime.start("local", wait=12)
212        self.assertTrue(started["ok"], started)
213        running = runtime.status("local")
214        self.assertEqual(running["state"], "ready")
215        running_revision = running["profile_revision"]
216        next_edit = {"overrides": {**edits["overrides"], "parallel": 6},
217                     "source_config": str(other.resolve())}
218        code, next_plan = send("profile.change.plan", {**next_edit,
219            "if_revision": profiles.load("local")[1]})
220        self.assertEqual((code, next_plan["ok"]), (0, True))
221        code, next_saved = send("profile.change", {**next_edit,
222            "if_revision": next_plan["plan"]["revision"],
223            "if_source_sha256": next_plan["plan"]["source_sha256"]})
224        self.assertEqual((code, next_saved["ok"]), (0, True))
225        still_running = runtime.status("local")
226        self.assertEqual(still_running["instance_id"], running["instance_id"])
227        self.assertEqual(still_running["profile_revision"], running_revision)
228        restart_plan = runtime.plan_restart("local")
229        self.assertTrue(restart_plan["ok"], restart_plan)
230        self.assertEqual(restart_plan["candidate_profile_revision"], next_saved["revision"])
231        self.assertNotEqual(restart_plan["candidate_profile_revision"], running_revision)
232
233    def test_local_management_bridge_and_cli_share_owner_and_journal(self):
234        command = [sys.executable, "-m", "strata_control.management"]
235        root = Path(__file__).resolve().parents[2]
236
237        def send(action, params):
238            request = {"schema_version": 1, "action": action, "profile": "local", "params": params}
239            completed = subprocess.run(command, input=json.dumps(request), text=True,
240                                       capture_output=True, cwd=root, env=os.environ.copy(), timeout=120)
241            return completed.returncode, json.loads(completed.stdout)
242
243        code, invalid = send("runtime.start", {"wait_s": True, "shutdown_timeout_s": 2,
244                                               "if_profile_revision": None,
245                                               "if_source_sha256": None})
246        self.assertEqual((code, invalid["ok"]), (2, False))
247        self.assertEqual(runtime.status("local")["state"], "stopped")
248        self.assertEqual(journal.list_runs("local"), [])
249        code, preview = send("runtime.start.plan", {"shutdown_timeout_s": 2})
250        self.assertEqual(code, 0)
251        self.assertFalse(preview["plan"]["would_start"])
252        self.assertEqual(runtime.status("local")["state"], "stopped")
253        start_params = {"wait_s": 10, "shutdown_timeout_s": 2,
254                        "if_profile_revision": preview["plan"]["launch"]["profile_revision"],
255                        "if_source_sha256": preview["plan"]["source_sha256"]}
256        self.assertEqual(preview["plan"]["source_sha256"], hashlib.sha256(self.config.read_bytes()).hexdigest())
257        code, missing = send("runtime.start", {**start_params, "if_source_sha256": None})
258        self.assertEqual((code, missing["ok"]), (2, False))
259        self.config.write_bytes(self.config.read_bytes() + b" ")
260        code, stale_source = send("runtime.start", start_params)
261        self.assertEqual((code, stale_source["error"]), (6, "source_changed_after_start_plan"))
262        self.assertEqual(journal.list_runs("local"), [])
263        self.config.write_bytes(self.config.read_bytes()[:-1])
264        profiles.set_values("local", ["max_queue=32"])
265        code, stale_profile = send("runtime.start", start_params)
266        self.assertEqual((code, stale_profile["error"]), (6, "profile_changed_after_start_plan"))
267        self.assertEqual(journal.list_runs("local"), [])
268        code, preview = send("runtime.start.plan", {"shutdown_timeout_s": 2})
269        self.assertEqual(code, 0)
270        start_params.update(if_profile_revision=preview["plan"]["launch"]["profile_revision"],
271                            if_source_sha256=preview["plan"]["source_sha256"])
272
273        code, started = send("runtime.start", start_params)
274        self.assertEqual(code, 0, started)
275        self.assertTrue(started["ok"])
276        start_record = journal.load("local", started["operation_id"])
277        self.assertEqual(start_record["kind"], "runtime.start")
278        self.assertEqual(start_record["intent"]["expected_source_sha256"], start_params["if_source_sha256"])
279        cli_code, current = self._cli("status", "--profile", "local")
280        self.assertEqual((cli_code, current["instance_id"]), (0, started["instance_id"]))
281        code, verify_plan = send("runtime.verify.plan", {"load": False})
282        self.assertEqual((code, verify_plan["ok"]), (0, True))
283        self.assertEqual(verify_plan["plan"]["owner_id"], started["owner_id"])
284        self.assertEqual(verify_plan["plan"]["instance_id"], started["instance_id"])
285        self.assertFalse(verify_plan["plan"]["would_verify"])
286        verify_params = {"wait_s": 10, "load": False,
287                         "if_owner_id": verify_plan["plan"]["owner_id"],
288                         "if_instance_id": verify_plan["plan"]["instance_id"]}
289        count = len(journal.list_runs("local"))
290        code, missing_verify = send("runtime.verify", {**verify_params, "if_owner_id": None})
291        self.assertEqual((code, missing_verify["ok"]), (2, False))
292        code, stale_verify_owner = send("runtime.verify", {**verify_params,
293                                                           "if_owner_id": "0" * 32})
294        self.assertEqual((code, stale_verify_owner["error"]),
295                         (6, "owner_changed_after_verify_plan"))
296        code, stale_verify_instance = send("runtime.verify", {**verify_params,
297                                                              "if_instance_id": "0" * 32})
298        self.assertEqual((code, stale_verify_instance["error"]),
299                         (6, "instance_changed_after_verify_plan"))
300        self.assertEqual(len(journal.list_runs("local")), count)
301        host_denied = runtime._rpc("local", "verify", params={
302            "wait": 10, "load": False, "expected_owner_id": "0" * 32,
303            "expected_instance_id": started["instance_id"]})
304        self.assertEqual(host_denied["error"], "owner_changed_after_verify_plan")
305        host_denied = runtime._rpc("local", "verify", params={
306            "wait": 10, "load": False, "expected_owner_id": started["owner_id"],
307            "expected_instance_id": "0" * 32})
308        self.assertEqual(host_denied["error"], "instance_changed_after_verify_plan")
309        code, verified = send("runtime.verify", verify_params)
310        self.assertEqual((code, verified["ok"], verified["verified_now"]), (0, True, True))
311        self.assertEqual(verified["instance_id"], started["instance_id"])
312        verify_record = journal.load("local", verified["operation_id"])
313        self.assertEqual(verify_record["intent"]["expected_instance_id"], started["instance_id"])
314        cli_code, cli_verify_plan = self._cli("verify", "--profile", "local", "--plan")
315        self.assertEqual((cli_code, cli_verify_plan["plan"]["instance_id"]),
316                         (0, started["instance_id"]))
317        code, old_stop_plan = send("runtime.stop.plan", {})
318        self.assertEqual((code, old_stop_plan["ok"]), (0, True))
319        self.assertEqual(old_stop_plan["plan"]["instance_id"], started["instance_id"])
320        code, restart_plan = send("runtime.restart.plan", {"allow_source_switch": False,
321                                                             "allow_source_migration": False})
322        self.assertEqual((code, restart_plan["ok"]), (0, True))
323        self.assertEqual(restart_plan["current_owner_id"], started["owner_id"])
324        self.assertEqual(restart_plan["current_instance_id"], started["instance_id"])
325        restart_params = {"wait_s": 80, "startup_wait_s": 60,
326                          "if_profile_revision": restart_plan["candidate_profile_revision"],
327                          "if_owner_id": restart_plan["current_owner_id"],
328                          "if_instance_id": restart_plan["current_instance_id"],
329                          "if_source_sha256": restart_plan["candidate_source_sha256"],
330                          "allow_source_switch": False, "allow_source_migration": False}
331        code, missing_condition = send("runtime.restart", {**restart_params,
332                                                             "if_source_sha256": None})
333        self.assertEqual((code, missing_condition["ok"]), (2, False))
334        code, missing_owner = send("runtime.restart", {**restart_params,
335                                                         "if_owner_id": None})
336        self.assertEqual((code, missing_owner["ok"]), (2, False))
337        count = len(journal.list_runs("local"))
338        code, stale_owner = send("runtime.restart", {**restart_params,
339                                                       "if_owner_id": "0" * 32})
340        self.assertEqual((code, stale_owner["error"]), (6, "owner_changed_after_restart_plan"))
341        code, stale_instance = send("runtime.restart", {**restart_params,
342                                                          "if_instance_id": "0" * 32})
343        self.assertEqual((code, stale_instance["error"]), (6, "instance_changed_after_restart_plan"))
344        self.assertEqual(len(journal.list_runs("local")), count)
345        host_denied = runtime._rpc("local", "restart", params={
346            "expected_owner_id": "0" * 32, "expected_instance_id": started["instance_id"]})
347        self.assertEqual(host_denied["error"], "owner_changed_after_restart_plan")
348        host_denied = runtime._rpc("local", "restart", params={
349            "expected_owner_id": started["owner_id"], "expected_instance_id": "0" * 32})
350        self.assertEqual(host_denied["error"], "instance_changed_after_restart_plan")
351        self.assertEqual(runtime.status("local")["instance_id"], started["instance_id"])
352        code, restarted = send("runtime.restart", restart_params)
353        self.assertEqual((code, restarted["ok"]), (0, True), restarted)
354        self.assertNotEqual(restarted["instance_id"], started["instance_id"])
355        self.assertEqual(journal.load("local", restarted["operation_id"])["kind"], "runtime.restart")
356        count = len(journal.list_runs("local"))
357        code, stale_verify = send("runtime.verify", verify_params)
358        self.assertEqual((code, stale_verify["error"]), (6, "instance_changed_after_verify_plan"))
359        self.assertEqual(len(journal.list_runs("local")), count)
360        code, stale_review = send("runtime.restart", restart_params)
361        self.assertEqual((code, stale_review["error"]), (6, "instance_changed_after_restart_plan"))
362        self.assertEqual(len(journal.list_runs("local")), count)
363        self.assertEqual(runtime.status("local")["instance_id"], restarted["instance_id"])
364        old_stop_params = {"wait_s": 12, "if_owner_id": old_stop_plan["plan"]["owner_id"],
365                           "if_instance_id": old_stop_plan["plan"]["instance_id"]}
366        count = len(journal.list_runs("local"))
367        code, stale_stop = send("runtime.stop", old_stop_params)
368        self.assertEqual((code, stale_stop["error"]), (6, "instance_changed_after_stop_plan"))
369        self.assertEqual(len(journal.list_runs("local")), count)
370        self.assertEqual(runtime.status("local")["instance_id"], restarted["instance_id"])
371        code, stop_plan = send("runtime.stop.plan", {})
372        self.assertEqual((code, stop_plan["ok"]), (0, True))
373        stop_params = {"wait_s": 12, "if_owner_id": stop_plan["plan"]["owner_id"],
374                       "if_instance_id": stop_plan["plan"]["instance_id"]}
375        code, stale_owner = send("runtime.stop", {**stop_params, "if_owner_id": "0" * 32})
376        self.assertEqual((code, stale_owner["error"]), (6, "owner_changed_after_stop_plan"))
377        self.assertEqual(len(journal.list_runs("local")), count)
378        host_denied = runtime._rpc("local", "stop", params={"expected_owner_id": "0" * 32,
379                                                        "expected_instance_id": restarted["instance_id"]})
380        self.assertEqual(host_denied["error"], "owner_changed_after_stop_plan")
381        host_denied = runtime._rpc("local", "stop", params={"expected_owner_id": stop_params["if_owner_id"],
382                                                        "expected_instance_id": started["instance_id"]})
383        self.assertEqual(host_denied["error"], "instance_changed_after_stop_plan")
384        self.assertEqual(runtime.status("local")["instance_id"], restarted["instance_id"])
385        code, stopped = send("runtime.stop", stop_params)
386        self.assertEqual((code, stopped["state"]), (0, "stopped"))
387        self.assertEqual(journal.load("local", stopped["operation_id"])["kind"], "runtime.stop")
388        self.assertEqual(runtime.status("local")["state"], "stopped")
389
390    def test_local_management_bridge_rejects_ambiguous_requests(self):
391        command = [sys.executable, "-m", "strata_control.management"]
392        root = Path(__file__).resolve().parents[2]
393        invalid = (
394            '{"schema_version":1,"action":"runtime.status","action":"runtime.start",'
395            '"profile":"local","params":{}}',
396            '{"schema_version":1,"action":"runtime.start","profile":"local",'
397            '"params":{"wait_s":NaN,"shutdown_timeout_s":2}}',
398            '{"schema_version":1,"action":"runtime.start","profile":"local",'
399            '"params":{"wait_s":10,"shutdown_timeout_s":2,"command":"rm -rf /"}}',
400            '{"schema_version":2,"action":"runtime.status","profile":"local","params":{}}',
401        )
402        for payload in invalid:
403            with self.subTest(payload=payload[:50]):
404                completed = subprocess.run(command, input=payload, text=True, capture_output=True,
405                                           cwd=root, env=os.environ.copy(), timeout=10)
406                response = json.loads(completed.stdout)
407                self.assertEqual((completed.returncode, response["ok"]), (2, False))
408                self.assertEqual(runtime.status("local")["state"], "stopped")
409        self.assertEqual(journal.list_runs("local"), [])
410
411    def test_owner_host_refuses_source_changed_after_start_review(self):
412        preview = management.runtime_action("start", "local", plan=True)["plan"]
413        self.config.write_bytes(self.config.read_bytes() + b" ")
414        host = subprocess.Popen([sys.executable, "-m", "strata_control.runtime", "--host", "local",
415                                 "--shutdown-timeout", "2", "--startup-wait", "10",
416                                 "--expected-profile-revision", preview["launch"]["profile_revision"],
417                                 "--expected-source-sha256", preview["source_sha256"]],
418                                cwd=Path(__file__).resolve().parents[2], env=os.environ.copy(),
419                                stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
420                                stderr=subprocess.DEVNULL)
421        try:
422            deadline = time.monotonic() + 8
423            result = {"state": "stopped"}
424            while time.monotonic() < deadline:
425                result = runtime.status("local")
426                if result.get("state") == "failed":
427                    break
428                self.assertIsNone(host.poll(), "owner host exited before reporting status")
429                time.sleep(0.05)
430            self.assertEqual(result.get("error"), "source_changed_after_start_plan")
431            self.assertIsNone(result.get("child_pid"))
432            self.assertEqual(list((self.root / "runtime").glob("*.ready.json")), [])
433        finally:
434            if host.poll() is None:
435                try:
436                    runtime.stop("local", timeout=8)
437                finally:
438                    host.wait(timeout=10)
439
440    @unittest.skipIf(WINDOWS, "Windows console stop needs a platform-specific integration runner (no SIGTERM/SIGINT)")
441    def test_foreground_jsonl_emits_ready_and_stop_without_human_stdout(self):
442        for stop_signal, expected_code, expected_reason, quiet in (
443                (signal.SIGTERM, 0, "sigterm", False),
444                (signal.SIGINT, 130, "sigint", False),
445                (signal.SIGTERM, 0, "sigterm", True)):
446            with self.subTest(signal=expected_reason, quiet=quiet):
447                rows = queue.Queue()
448                stderr_path = self.root / f"serve-{expected_reason}-{'quiet' if quiet else 'normal'}.stderr"
449                with stderr_path.open("w+", encoding="utf-8") as diagnostics:
450                    process = subprocess.Popen(
451                        [sys.executable, "strata.py", "serve", "--profile", "local", "--port", "0",
452                         "--shutdown-timeout", "2", "--output", "jsonl", *(["--quiet"] if quiet else [])],
453                        cwd=Path(__file__).resolve().parents[2], env=os.environ.copy(),
454                        stdout=subprocess.PIPE, stderr=diagnostics, text=True, bufsize=1)
455                    reader = threading.Thread(target=lambda: [rows.put(line) for line in process.stdout],
456                                              daemon=True)
457                    reader.start()
458                    try:
459                        collected = []
460                        for _ in range(4):
461                            collected.append(json.loads(rows.get(timeout=15)))
462                            if collected[-1].get("event") == "ready":
463                                break
464                        self.assertEqual([row["event"] for row in collected], ["starting", "ready"])
465                        ready = collected[-1]
466                        self.assertGreater(ready["bound_port"], 0)
467                        self.assertEqual(ready["model_state"], "ready")
468                        self.assertEqual(ready["pid"], process.pid)
469                        request = urllib.request.Request(
470                            ready["api_url"] + "/v1/chat/completions", method="POST",
471                            data=json.dumps({"messages": [{"role": "user", "content": "Hi"}],
472                                             "max_tokens": 1}).encode(),
473                            headers={"Content-Type": "application/json"})
474                        with urllib.request.urlopen(request, timeout=5) as response:
475                            self.assertEqual(response.status, 200)
476                            self.assertIn("choices", json.load(response))
477                        process.send_signal(stop_signal)
478                        self.assertEqual(process.wait(timeout=15), expected_code)
479                        reader.join(timeout=3)
480                        self.assertFalse(reader.is_alive())
481                        while not rows.empty():
482                            collected.append(json.loads(rows.get_nowait()))
483                        self.assertEqual([row["event"] for row in collected],
484                                         ["starting", "ready", "stopping", "draining", "stopped"])
485                        self.assertEqual(collected[-1]["reason"], expected_reason)
486                        self.assertEqual(collected[-1]["exit_code"], expected_code)
487                        self.assertTrue(all(row["schema_version"] == 1 for row in collected))
488                        self.assertNotIn("api_key", json.dumps(collected).lower())
489                        diagnostics.flush()
490                        if quiet:
491                            self.assertNotIn("ready:", stderr_path.read_text(encoding="utf-8"))
492                        else:
493                            self.assertIn("ready:", stderr_path.read_text(encoding="utf-8"))
494                    finally:
495                        if process.poll() is None:
496                            process.kill()
497                            process.wait(timeout=5)
498                        reader.join(timeout=2)
499                        process.stdout.close()
500
501    def test_start_profile_revision_restart_and_stop(self):
502        code, started = self._cli("start", "--profile", "local", "--wait", "60",
503                                  "--shutdown-timeout", "2")
504        self.assertEqual(code, 0)
505        self.assertEqual(started["state"], "ready")
506        self.assertTrue(started["api_identity_verified"])
507        self.assertTrue(started["launch_attested"])
508        self.assertTrue(started["generation_ready"])
509        self.assertEqual(started["readiness_state"], "generation_ready")
510        started_record = journal.load("local", started["operation_id"])
511        self.assertEqual((started_record["schema_version"], started_record["kind"], started_record["state"]),
512                         (2, "runtime.start", "succeeded"))
513        self.assertTrue(started_record["result"]["launch_attested"])
514        first_id = started["instance_id"]
515        self.assertNotEqual(started["host_pid"], started["child_pid"])
516        status = self._cli("status", "--profile", "local")[1]
517        self.assertEqual(status["instance_id"], first_id)
518        self.assertNotIn("operation_id", status)
519        code, checked = self._cli("verify", "--profile", "local", "--wait", "60")
520        self.assertEqual(code, 0)
521        self.assertTrue(checked["verified_now"])
522        self.assertTrue(checked["launch_attested"])
523        self.assertTrue(checked["generation_ready"])
524        checked_record = journal.load("local", checked["operation_id"])
525        self.assertEqual(checked_record["kind"], "runtime.verify")
526        self.assertTrue(checked_record["result"]["launch_attested"])
527        profiles.set_values("local", ["parallel=2"])
528        code, restarted = self._cli("restart", "--profile", "local", "--wait", "80")
529        self.assertEqual(code, 0)
530        self.assertTrue(restarted["restarted"])
531        self.assertTrue(restarted["launch_attested"])
532        self.assertTrue(restarted["generation_ready"])
533        self.assertEqual(journal.load("local", restarted["operation_id"])["kind"], "runtime.restart")
534        self.assertEqual(restarted["previous_instance_id"], first_id)
535        self.assertNotEqual(restarted["instance_id"], first_id)
536        code, stopped = self._cli("stop", "--profile", "local", "--wait", "12")
537        self.assertEqual(code, 0)
538        self.assertEqual(stopped["state"], "stopped")
539        self.assertEqual(journal.load("local", stopped["operation_id"])["kind"], "runtime.stop")
540        self.assertEqual([row["origin"] for row in journal.list_runs("local")], ["direct"] * 4)
541        deadline = time.monotonic() + 3
542        while runtime._read_state("local") is not None and time.monotonic() < deadline:
543            time.sleep(0.05)
544        self.assertIsNone(runtime._read_state("local"))
545
546    def test_cli_stop_plan_pins_the_reviewed_owner_and_instance(self):
547        started = runtime.start("local", wait=60, shutdown_timeout=2)
548        self.assertTrue(started["ok"])
549        code, preview = self._cli("stop", "--profile", "local", "--plan")
550        self.assertEqual(code, 0, preview)
551        self.assertEqual(preview["plan"]["instance_id"], started["instance_id"])
552        self.assertFalse(preview["plan"]["would_stop"])
553        code, denied = self._cli("stop", "--profile", "local", "--wait", "12",
554                                  "--if-owner-id", "0" * 32,
555                                  "--if-instance-id", preview["plan"]["instance_id"])
556        self.assertEqual((code, denied["error"]["message"]), (6, "owner_changed_after_stop_plan"))
557        self.assertEqual(runtime.status("local")["instance_id"], started["instance_id"])
558        code, stopped = self._cli("stop", "--profile", "local", "--wait", "12",
559                                   "--if-owner-id", preview["plan"]["owner_id"],
560                                   "--if-instance-id", preview["plan"]["instance_id"])
561        self.assertEqual((code, stopped["state"]), (0, "stopped"))
562        record = journal.load("local", stopped["operation_id"])
563        self.assertEqual(record["intent"]["expected_owner_id"], preview["plan"]["owner_id"])
564
565    def test_managed_benchmark_binds_to_owned_launch(self):
566        with socket.socket() as reserved:
567            reserved.bind(("127.0.0.1", 0))
568            port = reserved.getsockname()[1]
569        cfg = json.loads(self.config.read_text(encoding="utf-8"))
570        cfg["port"] = port
571        self.config.write_text(json.dumps(cfg), encoding="utf-8")
572        started = runtime.start("local", wait=60, shutdown_timeout=2)
573        self.assertTrue(started["ok"])
574        identity = {"profile": "local", "revision": profiles.load("local")[1],
575                    "source_sha256": hashlib.sha256(self.config.read_bytes()).hexdigest()}
576        endpoint = Endpoint(started["api_url"])
577        output = self.root / "managed-bench"
578        with redirect_stdout(io.StringIO()):
579            result = bench.run(endpoint, endpoint, output, concurrency=1,
580                               profile_identity=identity, require_managed_match=True)
581        self.assertTrue(result["successful"])
582        self.assertEqual(result["profile_running_match"], "managed_launch_checked")
583        self.assertEqual(result["instance_id"], started["instance_id"])
584        self.assertTrue(result["profile_running_check"]["after"]["matched"])
585        output_json = io.StringIO()
586        with redirect_stdout(output_json):
587            code = main(["bench", "run", "--suite", "serving-smoke", "--profile", "local", "--require-managed-match",
588                         "--concurrency", "1", "--out", str(self.root / "cli-managed"),
589                         "--output", "json"])
590        self.assertEqual(code, 0)
591        self.assertEqual(json.loads(output_json.getvalue())["summary"]["successful"], True)
592        self.assertEqual(json.loads(output_json.getvalue())["summary"]["profile_running_match"],
593                         "managed_launch_checked")
594        self.assertEqual(bench.load(self.root / "cli-managed")["profile_running_match"],
595                         "managed_launch_checked")
596        comparison = bench.compare(result, bench.load(self.root / "cli-managed"))
597        self.assertEqual(comparison["baseline"]["profile_running_match"], "managed_launch_checked")
598        self.assertFalse(any("running server config" in warning for warning in comparison["warnings"]))
599
600    def test_owned_runtime_and_calibration_exclude_each_other_even_on_port_zero(self):
601        first = runtime.start("local", wait=60, shutdown_timeout=2)
602        self.assertTrue(first["ok"])
603        output = self.root / "blocked-calibration.json"
604        with self.assertRaisesRegex(profiles.ProfileError, "engine lease"):
605            calibration.measure("local", output, exclusive_ack=True,
606                                runner=lambda cfg, say: self.fail("calibration runner was started"))
607        self.assertFalse(output.exists())
608        self.assertTrue(runtime.stop("local", timeout=12)["ok"])
609        with calibration._managed_exclusive():
610            with self.assertRaisesRegex(profiles.ProfileError, "runtime host failed to start"):
611                runtime.start("local", wait=1, shutdown_timeout=2)
612        self.assertTrue(runtime.start("local", wait=60, shutdown_timeout=2)["ok"])
613
614    def test_failed_new_port_rolls_back_previous_owned_launch(self):
615        first = runtime.start("local", wait=60, shutdown_timeout=2)
616        self.assertTrue(first["ok"])
617        with socket.socket() as occupied:
618            occupied.bind(("127.0.0.1", 0))
619            occupied.listen(1)
620            profiles.set_values("local", [f"port={occupied.getsockname()[1]}"])
621            result = runtime.restart("local", timeout=20)
622        self.assertFalse(result["ok"])
623        self.assertTrue(result["rolled_back"])
624        self.assertNotEqual(result["instance_id"], first["instance_id"])
625        self.assertEqual(runtime.status("local")["instance_id"], result["instance_id"])
626
627    def test_changed_source_is_rejected_before_stopping_old_instance(self):
628        first = runtime.start("local", wait=60, shutdown_timeout=2)
629        self.assertTrue(first["ok"])
630        self.config.write_bytes(self.config.read_bytes() + b" ")
631        for allow in (False, True):
632            result = runtime.restart("local", timeout=10, allow_source_switch=allow,
633                                     expected_source_sha256=hashlib.sha256(self.config.read_bytes()).hexdigest()
634                                     if allow else None)
635            self.assertFalse(result["ok"])
636            self.assertEqual(result["error"], "source_config_changed_restart_requires_migration")
637        self.assertEqual(runtime.status("local")["instance_id"], first["instance_id"])
638
639    def test_edited_source_migration_is_previewed_digest_pinned_and_verified(self):
640        first = runtime.start("local", wait=60, shutdown_timeout=2)
641        self.assertTrue(first["ok"])
642        edited = json.loads(self.config.read_text())
643        edited["model_name"] = "edited-fake"
644        self.config.write_text(json.dumps(edited), encoding="utf-8")
645        denied = runtime.plan_restart("local")
646        self.assertEqual(denied["error"], "source_config_changed_restart_requires_migration")
647        self.assertTrue(denied["requires_allow_source_migration"])
648        code, plan = self._cli("restart", "--profile", "local", "--allow-source-migration", "--plan")
649        self.assertEqual(code, 0)
650        self.assertTrue(plan["source_migration"])
651        self.assertTrue(plan["rollback_snapshot_required"])
652        self.assertFalse(plan["source_switch"])
653        self.assertTrue(plan["changed"])
654        self.assertEqual(runtime.status("local")["instance_id"], first["instance_id"])
655        code, missing = self._cli("restart", "--profile", "local", "--allow-source-migration")
656        self.assertEqual((code, missing["error"]["code"]), (2, 2))
657        self.config.write_bytes(self.config.read_bytes() + b" ")
658        code, stale = self._cli("restart", "--profile", "local", "--allow-source-migration",
659                                "--if-source-sha256", plan["candidate_source_sha256"])
660        self.assertEqual((code, stale["error"]), (6, "source_changed_after_preview"))
661        self.assertEqual(runtime.status("local")["instance_id"], first["instance_id"])
662        self.config.write_text(json.dumps(edited), encoding="utf-8")
663        code, restarted = self._cli("restart", "--profile", "local", "--allow-source-migration",
664                                    "--if-profile-revision", plan["candidate_profile_revision"],
665                                    "--if-source-sha256", plan["candidate_source_sha256"],
666                                    "--startup-wait", "60", "--wait", "80")
667        self.assertEqual(code, 0, restarted)
668        self.assertTrue(restarted["source_migrated"])
669        self.assertFalse(restarted["source_switched"])
670        self.assertTrue(restarted["launch_attested"])
671        self.assertTrue(restarted["generation_ready"])
672        self.assertNotEqual(restarted["instance_id"], first["instance_id"])
673        self.assertTrue(journal.load("local", restarted["operation_id"])["result"]["source_migrated"])
674        self.assertEqual(list((self.root / "runtime").glob("*.rollback.json")), [])
675
676    def test_failed_edited_source_migration_uses_private_snapshot_for_rollback(self):
677        secret = "migration-test-key"
678        original = json.loads(self.config.read_text())
679        original["api_key"] = secret
680        self.config.write_text(json.dumps(original), encoding="utf-8")
681        first = runtime.start("local", wait=60, shutdown_timeout=2)
682        self.assertTrue(first["ok"])
683        with socket.socket() as occupied:
684            occupied.bind(("127.0.0.1", 0))
685            occupied.listen(1)
686            edited = json.loads(self.config.read_text())
687            edited["port"] = occupied.getsockname()[1]
688            self.config.write_text(json.dumps(edited), encoding="utf-8")
689            plan = runtime.plan_restart("local", allow_source_migration=True)
690            code, result = self._cli("restart", "--profile", "local", "--allow-source-migration",
691                                     "--startup-wait", "30", "--wait", "80",
692                                     "--if-source-sha256", plan["candidate_source_sha256"])
693        self.assertEqual(code, 6)
694        self.assertFalse(result["ok"])
695        self.assertTrue(result["rolled_back"])
696        self.assertEqual(result["state"], "ready")
697        self.assertNotEqual(result["instance_id"], first["instance_id"])
698        self.assertEqual(json.loads(self.config.read_text())["port"], edited["port"])
699        snapshot = Path(result["rollback_source_config"])
700        self.assertEqual(snapshot.parent, self.root / "runtime")
701        if WINDOWS:
702            from strata_control import private_files
703            self.assertTrue(private_files.is_unshared(snapshot))      # NTFS has no mode bits: the ACL is the promise
704        else:
705            self.assertEqual(snapshot.stat().st_mode & 0o077, 0)
706        self.assertEqual(json.loads(snapshot.read_text())["port"], 0)
707        self.assertEqual(json.loads(snapshot.read_text())["api_key"], secret)
708        self.assertNotIn(secret, json.dumps(result))
709        record_result = journal.load("local", result["operation_id"])["result"]
710        self.assertEqual(record_result["rollback_source_config"], str(snapshot))
711        self.assertNotIn(secret, json.dumps(record_result))
712        self.assertTrue(runtime.status("local")["generation_ready"])
713        # The edited file can be retried as a distinct source after freeing its port.
714        plan = runtime.plan_restart("local", allow_source_switch=True)
715        self.assertTrue(plan["source_switch"])
716        retried = runtime.restart("local", timeout=20, startup_wait=60,
717                                  allow_source_switch=True,
718                                  expected_source_sha256=plan["candidate_source_sha256"])
719        self.assertTrue(retried["ok"], retried)
720        self.assertFalse(snapshot.exists())
721
722    def test_explicit_source_switch_previews_and_restarts_new_config(self):
723        first = runtime.start("local", wait=60, shutdown_timeout=2)
724        self.assertTrue(first["ok"])
725        next_config = self.root / "next-run.json"
726        changed = json.loads(self.config.read_text())
727        changed["model_name"] = "fake-next"
728        next_config.write_text(json.dumps(changed), encoding="utf-8")
729        previous_revision = profiles.load("local")[1]
730        source_output = io.StringIO()
731        with redirect_stdout(source_output):
732            source_code = main(["profile", "use-config", "local", "--from-config", str(next_config),
733                                "--if-revision", previous_revision, "--output", "json"])
734        self.assertEqual(source_code, 0)
735        next_revision = json.loads(source_output.getvalue())["revision"]
736
737        denied = runtime.plan_restart("local")
738        self.assertFalse(denied["ok"])
739        self.assertEqual(denied["error"], "source_switch_requires_opt_in")
740        self.assertTrue(denied["requires_allow_source_switch"])
741        code, preview = self._cli("restart", "--profile", "local", "--allow-source-switch", "--plan")
742        self.assertEqual(code, 0)
743        self.assertTrue(preview["source_switch"])
744        self.assertTrue(preview["changed"])
745        self.assertEqual(preview["current_source_config"], str(self.config.resolve()))
746        self.assertEqual(preview["candidate_source_config"], str(next_config.resolve()))
747        self.assertEqual(preview["candidate_profile_revision"], next_revision)
748        self.assertEqual(runtime.status("local")["instance_id"], first["instance_id"])
749
750        code, missing_digest = self._cli("restart", "--profile", "local", "--allow-source-switch")
751        self.assertEqual(code, 2)
752        self.assertFalse(missing_digest["ok"])
753        self.assertEqual(runtime.status("local")["instance_id"], first["instance_id"])
754        next_config.write_bytes(next_config.read_bytes() + b" ")
755        code, stale = self._cli("restart", "--profile", "local", "--allow-source-switch",
756                                "--if-source-sha256", preview["candidate_source_sha256"])
757        self.assertEqual(code, 6)
758        self.assertEqual(stale["error"], "source_changed_after_preview")
759        self.assertEqual(runtime.status("local")["instance_id"], first["instance_id"])
760        next_config.write_text(json.dumps(changed), encoding="utf-8")
761        code, switched = self._cli("restart", "--profile", "local", "--allow-source-switch",
762                                   "--if-profile-revision", next_revision, "--wait", "80",
763                                   "--if-source-sha256", preview["candidate_source_sha256"],
764                                   "--startup-wait", "60")
765        self.assertEqual(code, 0, switched)
766        self.assertTrue(switched["source_switched"])
767        self.assertNotEqual(switched["instance_id"], first["instance_id"])
768        self.assertEqual(switched["profile_revision"], next_revision)
769        self.assertTrue(switched["launch_attested"])
770        record = journal.load("local", switched["operation_id"])
771        self.assertTrue(record["intent"]["allow_source_switch"])
772        self.assertEqual(runtime.plan_restart("local")["source_switch"], False)
773
774    def test_failed_source_switch_restores_prior_owned_launch(self):
775        first = runtime.start("local", wait=60, shutdown_timeout=2)
776        self.assertTrue(first["ok"])
777        with socket.socket() as occupied:
778            occupied.bind(("127.0.0.1", 0))
779            occupied.listen(1)
780            next_config = self.root / "bad-next-run.json"
781            changed = json.loads(self.config.read_text())
782            changed["port"] = occupied.getsockname()[1]
783            next_config.write_text(json.dumps(changed), encoding="utf-8")
784            proposed, revision = profiles.load("local")
785            proposed["source_config"] = str(next_config)
786            profiles.save("local", proposed, expected_revision=revision)
787            digest = hashlib.sha256(next_config.read_bytes()).hexdigest()
788            result = runtime.restart("local", timeout=20, startup_wait=30, allow_source_switch=True,
789                                     expected_source_sha256=digest)
790        self.assertFalse(result["ok"])
791        self.assertTrue(result["rolled_back"])
792        self.assertNotEqual(result["instance_id"], first["instance_id"])
793        self.assertEqual(runtime.status("local")["instance_id"], result["instance_id"])
794        self.assertEqual(runtime.status("local")["profile_revision"], revision)
795
796    def test_source_switch_needs_unchanged_distinct_regular_rollback_file(self):
797        first = runtime.start("local", wait=60, shutdown_timeout=2)
798        self.assertTrue(first["ok"])
799        hardlink = self.root / "same-inode.json"
800        os.link(self.config, hardlink)
801        proposed, revision = profiles.load("local")
802        proposed["source_config"] = str(hardlink)
803        profiles.save("local", proposed, expected_revision=revision)
804        denied = runtime.plan_restart("local", allow_source_switch=True)
805        self.assertEqual(denied["error"], "source_switch_requires_distinct_regular_files")
806
807        next_config = self.root / "next-run.json"
808        next_config.write_bytes(self.config.read_bytes())
809        proposed, revision = profiles.load("local")
810        proposed["source_config"] = str(next_config)
811        profiles.save("local", proposed, expected_revision=revision)
812        self.config.write_bytes(self.config.read_bytes() + b" ")
813        denied = runtime.plan_restart("local", allow_source_switch=True)
814        self.assertEqual(denied["error"], "rollback_source_changed")
815        self.assertEqual(runtime.status("local")["instance_id"], first["instance_id"])
816        allowed = runtime.plan_restart("local", allow_source_switch=True,
817                                       allow_source_migration=True)
818        self.assertTrue(allowed["source_switch"])
819        self.assertTrue(allowed["source_migration"])
820        result = runtime.restart("local", timeout=20, startup_wait=60,
821                                 allow_source_switch=True, allow_source_migration=True,
822                                 expected_source_sha256=allowed["candidate_source_sha256"])
823        self.assertTrue(result["ok"], result)
824        self.assertTrue(result["source_switched"])
825        self.assertTrue(result["source_migrated"])
826        self.assertEqual(list((self.root / "runtime").glob("*.rollback.json")), [])
827
828    def test_server_reading_changed_config_fails_launch_attestation(self):
829        host = runtime.Host("local", shutdown_timeout=2, startup_wait=10)
830        plan, args, source, original = host._plan()
831        # Change valid JSON between the owner's snapshot and the server's read.
832        self.config.write_bytes(original + b" ")
833        try:
834            host._launch(args, source, original, plan["profile_revision"])
835            result = host._wait_ready(10)
836            self.assertFalse(result["ok"])
837            self.assertEqual(result["error"], "probe_launch_attestation_mismatch")
838        finally:
839            host._stop_child()
840
841    def test_authenticated_generation_probe_keeps_credential_out_of_status(self):
842        secret = "runtime-probe-test-key"
843        cfg = json.loads(self.config.read_text())
844        cfg["api_key"] = secret
845        self.config.write_text(json.dumps(cfg))
846        result = runtime.start("local", wait=60, shutdown_timeout=2)
847        self.assertTrue(result["generation_ready"])
848        self.assertTrue(result["launch_attested"])
849        self.assertNotIn(secret, json.dumps(result))
850        self.assertNotIn(secret, json.dumps(runtime.status("local")))
851
852    def test_remote_bind_preview_accepts_server_supported_key_list(self):
853        cfg = json.loads(self.config.read_text())
854        cfg.update(host="0.0.0.0", api_key=["first", "second"])
855        self.config.write_text(json.dumps(cfg))
856        from strata_cli.cli import _launch_plan
857        plan, _ = _launch_plan("local")
858        self.assertEqual(plan["effective"]["host"], "0.0.0.0")
859        self.assertNotIn("first", json.dumps(plan))
860
861    def test_remote_bind_without_a_key_is_planned_not_refused(self):
862        # owner decision 2026-10-20: a key is recommended on a network, never required
863        from strata_cli.cli import _launch_plan
864        for key in (None, "none"):
865            cfg = json.loads(self.config.read_text())
866            cfg["host"] = "0.0.0.0"
867            cfg.pop("api_key", None)
868            if key:
869                cfg["api_key"] = key
870            self.config.write_text(json.dumps(cfg))
871            with mock.patch.dict(os.environ, {"STRATA_API_KEY": ""}):
872                plan, args = _launch_plan("local")
873            self.assertEqual(plan["effective"]["host"], "0.0.0.0")
874
875    def test_lazy_model_is_verified_as_unloaded_without_generation(self):
876        cfg = json.loads(self.config.read_text())
877        cfg["lazy_load"] = True
878        self.config.write_text(json.dumps(cfg))
879        result = runtime.start("local", wait=60, shutdown_timeout=2)
880        self.assertTrue(result["ok"])
881        self.assertTrue(result["api_identity_verified"])
882        self.assertFalse(result["generation_ready"])
883        self.assertEqual((result["model_state"], result["readiness_state"]), ("unloaded", "unloaded"))
884        code, checked = self._cli("verify", "--profile", "local", "--wait", "60", "--load")
885        self.assertEqual(code, 0)
886        self.assertTrue(checked["generation_ready"])
887        self.assertEqual(runtime.status("local")["model_state"], "ready")
888        self.assertTrue(runtime.verify("local", timeout=10)["generation_ready"])
889
890    def test_failed_generation_probe_does_not_report_ready(self):
891        engine = self.root / "engine.py"
892        engine.write_text(engine.read_text().replace("        print('T 97', flush=True)",
893                                                      "        print('ERR probe-failed', flush=True)\n        continue"))
894        result = runtime.start("local", wait=60, shutdown_timeout=2)
895        self.assertFalse(result["ok"])
896        self.assertEqual(result["state"], "failed")
897        self.assertEqual(result["error"], "probe_http_400")
898
899    def test_zero_token_completion_does_not_count_as_generation_ready(self):
900        (self.root / "empty-generation").write_text("empty")
901        result = runtime.start("local", wait=60, shutdown_timeout=2)
902        self.assertFalse(result["ok"])
903        self.assertEqual(result["error"], "probe_generation_no_tokens")
904
905    def test_explicit_verify_reports_later_engine_failure_without_stopping_instance(self):
906        first = runtime.start("local", wait=60, shutdown_timeout=2)
907        self.assertTrue(first["generation_ready"])
908        flag = self.root / "fail-generation"
909        flag.write_text("fail")
910        code, checked = self._cli("verify", "--profile", "local", "--wait", "60")
911        self.assertEqual(code, 6)
912        self.assertEqual(checked["error"], "probe_http_400")
913        self.assertEqual(journal.load("local", checked["operation_id"])["state"], "failed")
914        self.assertEqual(runtime.status("local")["instance_id"], first["instance_id"])
915        flag.unlink()
916        self.assertTrue(runtime.verify("local", timeout=10)["generation_ready"])
917
918    def test_failed_generation_after_profile_edit_rolls_back_prior_launch(self):
919        first = runtime.start("local", wait=60, shutdown_timeout=2)
920        self.assertTrue(first["generation_ready"])
921        engine = self.root / "engine.py"
922        engine.write_text(engine.read_text().replace(
923            "        print('T 97', flush=True)",
924            "        if slot is not None:\n"
925            "            print('ERR batch-probe-failed', flush=True)\n"
926            "            continue\n"
927            "        print('T 97', flush=True)"))
928        profiles.set_values("local", ["parallel=2"])
929        result = runtime.restart("local", timeout=30, startup_wait=60)
930        self.assertFalse(result["ok"])
931        self.assertTrue(result["rolled_back"])
932        restored = runtime.status("local")
933        self.assertTrue(restored["generation_ready"])
934        self.assertEqual(restored["instance_id"], result["instance_id"])
935
936    def test_start_plan_is_read_only(self):
937        code, result = self._cli("start", "--profile", "local", "--plan")
938        self.assertEqual(code, 0)
939        self.assertFalse(result["plan"]["would_start"])
940        self.assertIsNone(runtime._read_state("local"))
941        self.assertEqual(journal.list_runs("local"), [])
942
943    def test_restart_plan_compares_revision_without_stopping_instance(self):
944        started = runtime.start("local", wait=60, shutdown_timeout=2)
945        self.assertTrue(started["ok"])
946        unchanged = runtime.plan_restart("local")
947        self.assertTrue(unchanged["ok"])
948        self.assertFalse(unchanged["changed"])
949        profiles.set_values("local", ["parallel=2"])
950        code, planned = self._cli("restart", "--profile", "local", "--plan")
951        self.assertEqual(code, 0)
952        self.assertTrue(planned["changed"])
953        self.assertFalse(planned["would_drain"])
954        self.assertFalse(planned["would_start"])
955        count = len(journal.list_runs("local"))
956        code, denied = self._cli("restart", "--profile", "local",
957                                 "--if-profile-revision", planned["candidate_profile_revision"],
958                                 "--if-source-sha256", planned["candidate_source_sha256"],
959                                 "--if-owner-id", planned["current_owner_id"],
960                                 "--if-instance-id", "0" * 32)
961        self.assertEqual((code, denied["error"]["message"]),
962                         (6, "instance_changed_after_restart_plan"))
963        self.assertEqual(len(journal.list_runs("local")), count)
964        self.assertEqual(runtime.status("local")["instance_id"], started["instance_id"])
965
966    def test_editable_recipe_previews_and_reruns_owned_instance(self):
967        recipes.initialize("local")
968        started = runtime.start("local", wait=60, shutdown_timeout=2)
969        self.assertTrue(started["ok"])
970        profiles.set_values("local", ["parallel=2"])
971        code, planned = self._ops("plan", "restart")
972        self.assertEqual(code, 0)
973        self.assertTrue(planned["plan"]["operation"]["preflight"]["changed"])
974        self.assertEqual(runtime.status("local")["instance_id"], started["instance_id"])
975        revision = planned["plan"]["recipe_revision"]
976        preflight = planned["plan"]["operation"]["preflight"]
977        code, ran = self._ops("run", "restart", "--if-revision", revision,
978                              "--if-profile-revision", planned["plan"]["profile_revision"],
979                              "--if-owner-id", preflight["current_owner_id"],
980                              "--if-instance-id", preflight["current_instance_id"],
981                              "--if-source-sha256", preflight["candidate_source_sha256"])
982        self.assertEqual(code, 0)
983        self.assertTrue(ran["operation"]["result"]["restarted"])
984        self.assertNotEqual(ran["operation"]["result"]["instance_id"], started["instance_id"])
985        record = journal.load("local", ran["operation"]["operation_id"])
986        self.assertEqual(record["state"], "succeeded")
987        self.assertEqual(record["result"]["instance_id"], ran["operation"]["result"]["instance_id"])
988        count = len(journal.list_runs("local"))
989        with self.assertRaisesRegex(profiles.ProfileError, "instance_changed_after_restart_plan"):
990            recipes.run("local", "restart", expected_revision=revision,
991                        expected_profile_revision=planned["plan"]["profile_revision"],
992                        expected_owner_id=preflight["current_owner_id"],
993                        expected_instance_id=preflight["current_instance_id"],
994                        expected_source_sha256=preflight["candidate_source_sha256"])
995        self.assertEqual(len(journal.list_runs("local")), count)
996
997    def test_stale_profile_revision_does_not_drain_owned_instance(self):
998        started = runtime.start("local", wait=60, shutdown_timeout=2)
999        self.assertTrue(started["ok"])
1000        previous = profiles.load("local")[1]
1001        profiles.set_values("local", ["parallel=2"])
1002        result = runtime.restart("local", timeout=10, expected_profile_revision=previous)
1003        self.assertFalse(result["ok"])
1004        self.assertEqual(result["error"], "profile_changed_after_preview")
1005        self.assertEqual(runtime.status("local")["instance_id"], started["instance_id"])
1006
1007    def _ops(self, *args):
1008        output = io.StringIO()
1009        with redirect_stdout(output):
1010            code = main(["ops", *args, "--profile", "local", "--output", "json"])
1011        return code, json.loads(output.getvalue())
1012
1013    @unittest.skipIf(WINDOWS, "SIGTERM to a Windows process is TerminateProcess: the hard-kill test below covers it")
1014    def test_terminating_owner_host_stops_its_child_and_removes_state(self):
1015        started = runtime.start("local", wait=60, shutdown_timeout=2)
1016        self.assertTrue(started["ok"])
1017        os.kill(started["host_pid"], signal.SIGTERM)
1018        deadline = time.monotonic() + 8
1019        while runtime._read_state("local") is not None and time.monotonic() < deadline:
1020            time.sleep(0.05)
1021        self.assertIsNone(runtime._read_state("local"))
1022        owned = runtime._STARTED_HOSTS.pop("local", None)
1023        if owned is not None:
1024            self.assertEqual(owned.wait(timeout=3), 0)
1025
1026    def test_hard_killed_host_child_exits_and_next_start_recovers_private_state(self):
1027        started = runtime.start("local", wait=60, shutdown_timeout=2)
1028        self.assertTrue(started["ok"])
1029        old_child = started["child_pid"]
1030        state = runtime._read_state("local")
1031        orphan = self.root / "runtime" / f"local-{state['token']}-{'a' * 32}.rollback.json"
1032        orphan.write_bytes(self.config.read_bytes())
1033        orphan.chmod(0o600)
1034        owned = runtime._STARTED_HOSTS.pop("local")
1035        if WINDOWS:
1036            owned.kill()                          # TerminateProcess: the host cannot clean up after itself
1037            owned.wait(timeout=3)
1038            # the job object ends the server tree with the host, no matter how the host ended
1039            deadline = time.monotonic() + 15
1040            while runtime._pid_exists(old_child) and time.monotonic() < deadline:
1041                time.sleep(0.1)
1042            self.assertFalse(runtime._pid_exists(old_child))
1043        else:
1044            os.kill(started["host_pid"], signal.SIGKILL)
1045            self.assertEqual(owned.wait(timeout=3), -signal.SIGKILL)
1046        stale = runtime.status("local")
1047        self.assertEqual((stale["state"], stale["error"]), ("stale", "owner_host_lost"))
1048        # The next start waits for the inherited-pipe guard to stop the old
1049        # process group; it never sends a signal to the saved child PID.
1050        replacement = runtime.start("local", wait=60, shutdown_timeout=2)
1051        self.assertTrue(replacement["ok"])
1052        self.assertNotEqual(replacement["child_pid"], old_child)
1053        self.assertFalse(runtime._pid_exists(old_child))
1054        self.assertFalse(orphan.exists())
1055
1056    def test_recovery_refuses_a_still_present_child(self):
1057        state_path, socket_path, _ = runtime._paths("local")
1058        token = "a" * 64
1059        state = {"schema_version": 1, "profile": "local",
1060                 "socket": "tcp:127.0.0.1:50000" if WINDOWS else str(socket_path),
1061                 "token": token, "host_pid": 999999}
1062        lease = runtime._write_new(state_path, (json.dumps(state) + "\n").encode())
1063        os.close(lease)
1064        marker = runtime._child_marker("local", token)
1065        marker.write_text(json.dumps({"host_token": token, "phase": "owned",
1066                                      "pid": os.getpid(),
1067                                      "ready": str(state_path.parent / "local-fake.ready.json")}), encoding="utf-8")
1068        marker.chmod(0o600)
1069        with self.assertRaisesRegex(profiles.ProfileError, "still present"):
1070            runtime.start("local", wait=0, shutdown_timeout=2)
1071        self.assertTrue(state_path.exists())
1072
1073    # ---- round 0213 LIFECYCLE: the owner answers while it starts, leaves when its server is gone, and is recoverable at every point
1074
1075    def _slow_plan_owner(self, delay):
1076        """An owner host in another process whose plan takes `delay` seconds (the slow imports, hardware questions and virus scans of #5177)."""
1077        code = ("import time\n"
1078                "from strata_control import runtime\n"
1079                "original = runtime.Host._plan\n"
1080                "def slow(self):\n"
1081                f"    time.sleep({delay})\n"
1082                "    return original(self)\n"
1083                "runtime.Host._plan = slow\n"
1084                "raise SystemExit(runtime.Host('local', shutdown_timeout=2).serve())\n")
1085        owner = subprocess.Popen([sys.executable, "-c", code], cwd=Path(__file__).resolve().parents[2],
1086                                 env=os.environ.copy(), stdin=subprocess.DEVNULL,
1087                                 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
1088        self.addCleanup(lambda: owner.poll() is None and (owner.kill(), owner.wait(timeout=5)))
1089        deadline = time.monotonic() + 15
1090        while runtime._read_state("local") is None and owner.poll() is None and time.monotonic() < deadline:
1091            time.sleep(0.05)
1092        self.assertIsNotNone(runtime._read_state("local"), "the owner did not publish its state")
1093        return owner
1094
1095    def test_the_owner_answers_status_while_it_is_still_planning(self):                       # #5177
1096        owner = self._slow_plan_owner(6)
1097        began = time.monotonic()
1098        for _ in range(3):
1099            answer = runtime._rpc("local", "status", timeout=2)           # the old owner did not accept before its plan was done: this timed out
1100            self.assertEqual((answer["state"], answer["phase"]), ("starting", "preparing"))
1101            time.sleep(0.3)
1102        self.assertLess(time.monotonic() - began, 5, "the status answers waited for the plan")
1103        deadline = time.monotonic() + 40
1104        answer = runtime._rpc("local", "status", timeout=2)
1105        while answer["state"] == "starting" and time.monotonic() < deadline:
1106            time.sleep(0.2)
1107            answer = runtime._rpc("local", "status", timeout=2)
1108        self.assertEqual(answer["state"], "ready", answer)
1109        self.assertIsInstance(answer["child_pid"], int)
1110
1111    def test_a_stop_while_the_owner_plans_starts_no_server(self):                                # #5177
1112        owner = self._slow_plan_owner(4)
1113        state = runtime._read_state("local")
1114        answer = self._send(state, state["token"], "stop")
1115        self.assertTrue(answer["ok"], answer)
1116        self.assertEqual(owner.wait(timeout=20), 0)
1117        time.sleep(0.5)
1118        self.assertFalse(list((self.root / "runtime").glob("*.server.log")) and
1119                         any(p.stat().st_size for p in (self.root / "runtime").glob("*.server.log")), "a server was started after the stop")
1120        self.assertIsNone(runtime._read_state("local"))
1121
1122    def test_a_start_keeps_asking_a_busy_owner_until_its_wait_is_over(self):                    # #5177: one missed answer is not a failed start
1123        calls = []
1124        real = runtime._rpc
1125
1126        def flaky(name, command, **kw):
1127            if command == "status" and len(calls) < 2:
1128                calls.append(kw.get("timeout"))
1129                raise profiles.ProfileError("runtime operation wait expired; inspect runtime status", 8)
1130            return real(name, command, **kw)
1131        with mock.patch.object(runtime, "_rpc", flaky):
1132            started = runtime.start("local", wait=30, shutdown_timeout=2)
1133        self.assertTrue(started["ok"], started)
1134        self.assertEqual(len(calls), 2)
1135        self.assertTrue(all(x >= 1 for x in calls))
1136
1137    def test_a_lost_owner_is_still_a_failed_start_at_once(self):
1138        def gone(name, command, **kw):
1139            raise profiles.ProfileError("runtime control is unavailable; inspect the private host log", 3)
1140        with mock.patch.object(runtime, "_rpc", gone), mock.patch.object(runtime, "_owner_alive", return_value=False):
1141            with self.assertRaisesRegex(profiles.ProfileError, "unavailable"):
1142                runtime.start("local", wait=30, shutdown_timeout=2)
1143
1144    def test_an_engine_that_is_up_gets_its_own_first_token_budget(self):                        # #5177 #5059 #4293
1145        host = runtime.Host("local", shutdown_timeout=2, startup_wait=5)
1146        ready = self.root / "ready.json"
1147        child = mock.Mock(pid=4321)
1148        child.poll.return_value = None
1149        ready.write_text(json.dumps({"pid": 4321, "instance_id": "i" * 32}), encoding="utf-8")
1150        host.child, host.ready_path = child, ready
1151        host.args, host.source_bytes, host.expected_attestation = ["--host", "127.0.0.1"], b"{}", "0" * 64
1152        host.probe_deadline = time.monotonic() - 100          # the load used up the whole wait
1153        seen = []
1154        started = threading.Event()
1155
1156        def probe(self_, ready_, key, host_, source, attestation, timeout):
1157            seen.append(timeout)
1158            started.set()
1159        with mock.patch.object(runtime.Host, "_verify_ready", probe):
1160            self.assertEqual(host._status()["phase"], "verifying_generation")
1161            self.assertTrue(started.wait(5))
1162        self.assertGreaterEqual(seen[0], runtime.VERIFY_BUDGET)
1163
1164    def test_the_start_wait_does_not_end_while_the_first_token_is_being_checked(self):          # #5177 #4293
1165        answers = [{"ok": True, "state": "starting", "phase": "verifying_generation"}] * 3 +                   [{"ok": True, "state": "ready", "phase": None, "instance_id": "i" * 32}]
1166        clock = [0.0]
1167
1168        def rpc(name, command, **kw):
1169            clock[0] += 100.0                                 # every look is 100 s later: the 150 s wait is over after the second
1170            return answers.pop(0)
1171        with mock.patch.object(runtime, "_rpc", rpc), mock.patch.object(runtime.time, "sleep", lambda s: None),                 mock.patch.object(runtime.time, "monotonic", lambda: clock[0]):
1172            result = runtime._await_start("local", 150)
1173        self.assertTrue(result["ok"], result)                 # the verifying phase carried it past the wait, up to VERIFY_BUDGET
1174        answers[:] = [{"ok": True, "state": "starting", "phase": "loading"}] * 9
1175        clock[0] = 0.0
1176        with mock.patch.object(runtime, "_rpc", rpc), mock.patch.object(runtime.time, "sleep", lambda s: None),                 mock.patch.object(runtime.time, "monotonic", lambda: clock[0]):
1177            result = runtime._await_start("local", 150)
1178        self.assertEqual((result["error"], result["phase"]), ("startup_wait_expired", "loading"))     # a load that does not finish still ends
1179
1180    def test_the_host_leaves_when_its_server_ends_on_its_own(self):                              # #4574 #4893 (#4893 is the PR: same idea, own code)
1181        started = runtime.start("local", wait=60, shutdown_timeout=2)
1182        self.assertTrue(started["ok"])
1183        owned = runtime._STARTED_HOSTS.pop("local")
1184        os.kill(started["child_pid"], signal.SIGTERM)         # the server dies; the host did not ask it to
1185        failed = None
1186        deadline = time.monotonic() + 8
1187        while time.monotonic() < deadline:
1188            failed = runtime.status("local")
1189            if failed.get("state") == "failed":
1190                break
1191            time.sleep(0.1)
1192        self.assertEqual(failed["state"], "failed", "the server's end is published before the host leaves")
1193        self.assertEqual(failed["error"], "server_exited")
1194        try:
1195            code = owned.wait(timeout=runtime.CHILD_EXIT_GRACE + 15)
1196        except subprocess.TimeoutExpired:
1197            self.fail("the owner host stays alive as a husk after its server exited")
1198        self.assertEqual(code, 6)
1199        self.assertIsNone(runtime._read_state("local"), "the host left its private state behind")
1200        log = (self.root / "runtime" / "local.host.log").read_text(encoding="utf-8", errors="replace")
1201        self.assertIn("the server ended on its own", log)
1202        replacement = runtime.start("local", wait=60, shutdown_timeout=2)                    # no manual kill
1203        self.assertTrue(replacement["ok"])
1204
1205    def test_die_with_does_not_stop_an_engine_for_a_look_that_failed(self):                     # #4973
1206        host = runtime.Host("local", shutdown_timeout=2, die_with=(os.getpid(), "tok"))
1207        with mock.patch.object(runtime.procs, "start_token", return_value=None), mock.patch.object(runtime, "_pid_exists", return_value=True):
1208            for _ in range(10):
1209                self.assertFalse(host._die_with_gone(), "a process that is there but cannot be read ended the engine")
1210        with mock.patch.object(runtime.procs, "start_token", return_value="tok"):
1211            self.assertFalse(host._die_with_gone())
1212        with mock.patch.object(runtime.procs, "start_token", return_value="other"):
1213            self.assertTrue(host._die_with_gone(), "a later process with that number is the end of the one followed")
1214        host.die_misses = 0
1215        with mock.patch.object(runtime.procs, "start_token", return_value=None), mock.patch.object(runtime, "_pid_exists", return_value=False):
1216            self.assertEqual([host._die_with_gone() for _ in range(runtime.DIE_WITH_MISSES)], [False] * (runtime.DIE_WITH_MISSES - 1) + [True])
1217
1218    def test_a_host_lost_before_it_launched_anything_is_recovered(self):                        # #4250: the PR's idea
1219        owner = self._slow_plan_owner(120)
1220        state = runtime._read_state("local")
1221        marker = runtime._child_marker("local", state["token"])
1222        self.assertEqual(json.loads(marker.read_text(encoding="utf-8")), {"host_token": state["token"], "phase": "no_child"})
1223        owner.kill()
1224        owner.wait(timeout=5)
1225        deadline = time.monotonic() + 5
1226        while runtime._host_lease_active("local") and time.monotonic() < deadline:
1227            time.sleep(0.05)
1228        self.assertTrue(runtime._recover_stale("local", wait=0))
1229        self.assertIsNone(runtime._read_state("local"))
1230        self.assertFalse(marker.exists())
1231        self.assertTrue(runtime.start("local", wait=60, shutdown_timeout=2)["ok"])
1232
1233    def test_a_missing_or_foreign_marker_still_refuses_recovery(self):                           # #4250
1234        state_path, socket_path, _ = runtime._paths("local")
1235        token = "a" * 64
1236        state = {"schema_version": 1, "profile": "local", "socket": "tcp:127.0.0.1:50000" if WINDOWS else str(socket_path),
1237                 "token": token, "host_pid": 999999}
1238        lease = runtime._write_new(state_path, (json.dumps(state) + "\n").encode())
1239        runtime._unlock_file(lease)
1240        os.close(lease)
1241        with self.assertRaisesRegex(profiles.ProfileError, "no valid child ownership record"):
1242            runtime._recover_stale("local", wait=0)
1243        marker = runtime._child_marker("local", token)
1244        marker.write_text(json.dumps({"host_token": token, "phase": "no_child", "pid": os.getpid()}), encoding="utf-8")   # more than the exact record
1245        marker.chmod(0o600)
1246        with self.assertRaisesRegex(profiles.ProfileError, "unverified"):
1247            runtime._recover_stale("local", wait=0)
1248        self.assertTrue(state_path.exists())
1249
1250    # ---- owner transport, attach and identity (POSIX socket and Windows loopback alike)
1251
1252    def _stale_host(self, child_pid, *, started=None, token="a" * 64):
1253        """A state file whose host is gone, and the ownership marker naming `child_pid` as its server."""
1254        state_path, socket_path, _ = runtime._paths("local")
1255        state = {"schema_version": 1, "profile": "local",
1256                 "socket": "tcp:127.0.0.1:50000" if WINDOWS else str(socket_path),
1257                 "token": token, "host_pid": 999999}
1258        lease = runtime._write_new(state_path, (json.dumps(state) + "\n").encode())
1259        runtime._unlock_file(lease)
1260        os.close(lease)
1261        marker = runtime._child_marker("local", token)
1262        record = {"host_token": token, "phase": "owned", "pid": child_pid,
1263                  "ready": str(state_path.parent / "local-fake.ready.json")}
1264        if started is not None:
1265            record["started"] = started
1266        marker.write_text(json.dumps(record), encoding="utf-8")
1267        marker.chmod(0o600)
1268        return state_path, marker
1269
1270    def _send(self, state, token, command):
1271        client = owner_transport.connect(state["socket"], timeout=5)
1272        try:
1273            client.sendall((json.dumps({"token": token, "command": command}) + "\n").encode())
1274            return json.loads(client.recv(4096).split(b"\n")[0])
1275        finally:
1276            client.close()
1277
1278    def test_a_second_client_attaches_from_another_process_and_shares_the_owner(self):
1279        started = runtime.start("local", wait=60, shutdown_timeout=2)
1280        self.assertTrue(started["ok"])
1281        state = runtime._read_state("local")
1282        if WINDOWS:
1283            self.assertRegex(state["socket"], r"^tcp:127\.0\.0\.1:[1-9][0-9]*$")
1284        root = Path(__file__).resolve().parents[2]
1285        done = subprocess.run([sys.executable, "strata.py", "runtime", "status", "--profile", "local",
1286                               "--output", "json"], cwd=root, env=os.environ.copy(), capture_output=True,
1287                              text=True, timeout=30)
1288        self.assertEqual(done.returncode, 0, done.stderr)
1289        other = json.loads(done.stdout)
1290        self.assertEqual((other["state"], other["owner_id"], other["instance_id"], other["host_pid"]),
1291                         ("ready", started["owner_id"], started["instance_id"], started["host_pid"]))
1292        self.assertEqual(runtime.status("local")["owner_id"], started["owner_id"])   # attaching took nothing over
1293        self.assertEqual(runtime.stop("local", timeout=12)["ok"], True)
1294        self.assertEqual(runtime.status("local")["state"], "stopped")
1295
1296    def test_a_wrong_or_stale_token_cannot_stop_the_owner(self):
1297        started = runtime.start("local", wait=60, shutdown_timeout=2)
1298        self.assertTrue(started["ok"])
1299        state = runtime._read_state("local")
1300        wrong_last = "0" if state["token"][-1] != "0" else "1"
1301        for bad in ("0" * 64, state["token"][:-1] + wrong_last, "", "x" * 10):
1302            with self.subTest(token=bad[:6]):
1303                answer = self._send(state, bad, "stop")
1304                self.assertEqual((answer["ok"], answer["error"]), (False, "unauthorized"))
1305        self.assertEqual(runtime.status("local")["instance_id"], started["instance_id"])
1306        self.assertTrue(self._send(state, state["token"], "status")["ok"])     # the real token is what authorises
1307
1308    def test_a_recorded_pid_of_an_unrelated_live_process_is_never_signalled(self):
1309        victim = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"])
1310        try:
1311            state_path, marker = self._stale_host(victim.pid)
1312            with self.assertRaisesRegex(profiles.ProfileError, "still present"):
1313                runtime.start("local", wait=0, shutdown_timeout=2)
1314            with self.assertRaises(profiles.ProfileError):            # nothing answers on the recorded address
1315                runtime.stop("local", timeout=2)
1316            self.assertIsNone(victim.poll(), "an unrelated process was stopped")
1317            self.assertTrue(state_path.exists() and marker.exists())
1318        finally:
1319            victim.kill()
1320            victim.wait(timeout=10)
1321
1322    @unittest.skipUnless(WINDOWS, "a creation time is recorded with the PID on Windows only")
1323    def test_a_reused_pid_with_another_creation_time_is_not_the_recorded_child(self):
1324        victim = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"])
1325        try:
1326            real = runtime.winproc.process_started(victim.pid)
1327            self.assertTrue(runtime._pid_exists(victim.pid, real))
1328            self.assertFalse(runtime._pid_exists(victim.pid, real + 12345))
1329            self._stale_host(victim.pid, started=real + 12345)           # the number was reused by another process
1330            started = runtime.start("local", wait=60, shutdown_timeout=2)
1331            self.assertTrue(started["ok"])                               # recovered: it was not the recorded child
1332            self.assertIsNone(victim.poll(), "the process that reused the PID was stopped")
1333        finally:
1334            victim.kill()
1335            victim.wait(timeout=10)
1336
1337    def test_marker_without_creation_time_ignores_a_reused_pid_of_a_foreign_program(self):
1338        # #3488: the marker had no `started`, the number was reused by another program, every load said "still present".
1339        child = {"pid": 38552}
1340        with mock.patch.object(runtime, "WINDOWS", True), \
1341                mock.patch.object(runtime, "_pid_exists", return_value=True), \
1342                mock.patch.object(runtime.winproc, "process_image", create=True) as image:
1343            image.return_value = r"C:\Windows\System32\svchost.exe"
1344            self.assertFalse(runtime._child_present(child))
1345            image.return_value = r"C:\Users\a\AppData\Local\Strata\python\python.exe"
1346            self.assertTrue(runtime._child_present(child))
1347            image.return_value = None                                    # unreadable: keep refusing, never guess
1348            self.assertTrue(runtime._child_present(child))
1349            image.return_value = r"C:\Windows\System32\svchost.exe"
1350            self.assertTrue(runtime._child_present({"pid": 1, "started": 5}))   # a creation time decides by itself
1351
1352    def test_a_process_created_after_the_marker_was_written_is_not_the_recorded_child(self):
1353        # 2026-10-22: the app was force-killed, its marker had no creation time, the number now belonged to another Python program, and every
1354        # load said "lost host child is still present" until the marker was deleted by hand. The child was started BEFORE its marker was written.
1355        child = {"pid": 4242}
1356        with mock.patch.object(runtime, "_pid_exists", return_value=True), \
1357                mock.patch.object(runtime.winproc, "process_image", create=True, return_value="C:\\Python\\python.exe"), \
1358                mock.patch.object(runtime.procs, "started_epoch") as created:
1359            created.return_value = 1000.0 + 60
1360            self.assertFalse(runtime._child_present(child, written=1000.0), "created a minute after the marker: another process")
1361            created.return_value = 1000.0 - 5
1362            self.assertTrue(runtime._child_present(child, written=1000.0), "created before the marker: could be the child, keep refusing")
1363            created.return_value = 1000.0 + 1.5
1364            self.assertTrue(runtime._child_present(child, written=1000.0), "inside the clock slack: keep refusing")
1365            created.return_value = None
1366            self.assertTrue(runtime._child_present(child, written=1000.0), "creation time unreadable: never guess")
1367            created.return_value = 1000.0 + 60
1368            self.assertTrue(runtime._child_present({"pid": 4242, "started": 7}, written=1000.0) is True, "a recorded creation time decides by itself")
1369            self.assertTrue(runtime._child_present(child), "no marker time: unchanged")
1370
1371    def test_a_marker_left_by_a_killed_app_is_cleaned_up_when_its_number_belongs_to_a_later_program(self):
1372        victim = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"])
1373        try:
1374            state_path, marker = self._stale_host(victim.pid)             # a marker with no creation time (Windows could not read it)
1375            old = time.time() - 3600
1376            os.utime(marker, (old, old))                                  # written an hour ago: the victim started after it
1377            started = runtime.start("local", wait=60, shutdown_timeout=2)
1378            self.assertTrue(started["ok"], started)
1379            self.assertFalse(marker.exists(), "the stale marker was removed")
1380            self.assertIsNone(victim.poll(), "the program that reused the number was left alone")
1381        finally:
1382            victim.kill()
1383            victim.wait(timeout=10)
1384
1385    def test_started_epoch_reads_a_live_process_and_nothing_for_a_dead_number(self):
1386        victim = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"])
1387        try:
1388            now = time.time()
1389            created = procs.started_epoch(victim.pid)
1390            self.assertIsNotNone(created)
1391            self.assertLess(abs(created - now), 60)
1392        finally:
1393            victim.kill()
1394            victim.wait(timeout=10)
1395        self.assertIsNone(procs.started_epoch(victim.pid))
1396        self.assertIsNone(procs.started_epoch(0))
1397        self.assertIsNone(procs.started_epoch(-5))
1398
1399    @unittest.skipUnless(WINDOWS, "os.kill(pid, 0) ends a process on Windows; liveness is a handle query")
1400    def test_liveness_check_does_not_end_the_process_it_asks_about(self):
1401        victim = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"])
1402        try:
1403            for _ in range(5):
1404                self.assertTrue(runtime._pid_exists(victim.pid))
1405            self.assertIsNone(victim.poll())
1406        finally:
1407            victim.kill()
1408            victim.wait(timeout=10)
1409        self.assertFalse(runtime._pid_exists(victim.pid))
1410
1411    @unittest.skipUnless(WINDOWS, "ACLs stand in for mode 0700 on Windows")
1412    def test_runtime_directory_is_owner_only_and_a_shared_one_is_refused(self):
1413        from strata_control import private_files
1414        directory = runtime.runtime_dir()
1415        self.assertTrue(private_files.is_private(directory))
1416        shared = Path(self.temp.name) / "shared-runtime"
1417        shared.mkdir()
1418        done = subprocess.run(["icacls", str(shared), "/grant", "*S-1-1-0:(OI)(CI)R"], capture_output=True)
1419        if done.returncode != 0:
1420            self.skipTest("icacls could not widen the test directory")
1421        with mock.patch.dict(os.environ, {"STRATA_RUNTIME_DIR": str(shared)}):
1422            # a folder that names Everyone is the user's own state folder: it is locked down once and used (never a stop)
1423            self.assertEqual(runtime.runtime_dir(), shared)
1424            self.assertTrue(private_files.is_unshared(shared))
1425        again = Path(self.temp.name) / "shared-runtime-2"
1426        again.mkdir()
1427        subprocess.run(["icacls", str(again), "/grant", "*S-1-1-0:(OI)(CI)R"], capture_output=True)
1428        with mock.patch.dict(os.environ, {"STRATA_RUNTIME_DIR": str(again)}), \
1429                mock.patch.object(private_files, "restrict_to_current_user"), \
1430                mock.patch.object(private_files, "repair_access", return_value=False):
1431            # when the lock-down does not happen it still refuses, in plain words and naming who can open it
1432            with self.assertRaisesRegex(profiles.ProfileError, "Everyone"):
1433                runtime.runtime_dir()
1434
1435    def test_ready_pid_may_be_a_child_of_the_launcher_on_windows_only(self):
1436        # #3683: a Windows venv's python.exe starts the real interpreter as its child, so the server that writes the ready file
1437        # is one process below the pid the host started. It must still match; a stranger or a distant process must not.
1438        parents = {200: 100, 300: 200, 400: 300, 500: 400}
1439        with mock.patch.object(runtime.procs, "parent_of", side_effect=lambda pid: parents.get(pid)):
1440            with mock.patch.object(runtime, "WINDOWS", True):
1441                self.assertTrue(runtime._ready_pid_is_child(100, 100))
1442                self.assertTrue(runtime._ready_pid_is_child(200, 100))
1443                self.assertTrue(runtime._ready_pid_is_child(300, 100))
1444                self.assertTrue(runtime._ready_pid_is_child(400, 100))
1445                self.assertFalse(runtime._ready_pid_is_child(500, 100))      # too far below
1446                self.assertFalse(runtime._ready_pid_is_child(999, 100))      # unrelated
1447                self.assertFalse(runtime._ready_pid_is_child(None, 100))
1448                self.assertFalse(runtime._ready_pid_is_child("200", 100))
1449                self.assertFalse(runtime._ready_pid_is_child(0, 100))
1450            with mock.patch.object(runtime, "WINDOWS", False):
1451                self.assertTrue(runtime._ready_pid_is_child(100, 100))
1452                self.assertFalse(runtime._ready_pid_is_child(200, 100))      # POSIX has no launcher in between
1453
1454    @unittest.skipUnless(WINDOWS, "the venv launcher is a Windows thing")
1455    def test_server_started_through_a_launcher_process_becomes_ready(self):
1456        launcher = self.root / "launcher.cmd"
1457        launcher.write_bytes(f'@echo off\r\n"{sys.executable}" %*\r\n'.encode())
1458        host = runtime.Host("local", shutdown_timeout=2, startup_wait=20)
1459        plan, args, source, original = host._plan()
1460        with mock.patch.object(sys, "executable", str(launcher)):
1461            host._launch(args, source, original, plan["profile_revision"])
1462        try:
1463            result = host._wait_ready(30)
1464            self.assertTrue(result["ok"], result)
1465            self.assertTrue(result["generation_ready"])
1466            ready = json.loads(host.ready_path.read_text(encoding="utf-8"))
1467            self.assertNotEqual(ready["pid"], host.child.pid)               # the server is below the launcher
1468        finally:
1469            host._stop_child()
1470
1471    def test_a_ready_file_that_is_not_ours_is_named_in_the_status_phase(self):
1472        host = runtime.Host("local", shutdown_timeout=2, startup_wait=10)
1473        host.child = mock.Mock(pid=111)
1474        host.child.poll.return_value = None
1475        host.ready_path = self.root / "ready.json"
1476        host.ready_path.write_text(json.dumps({"pid": 222, "instance_id": "a" * 32}), encoding="utf-8")
1477        with mock.patch.object(runtime.procs, "parent_of", return_value=None):
1478            self.assertEqual(host._status()["phase"], "ready_file_not_matched")
1479        host.ready_path.unlink()
1480        self.assertEqual(host._status()["phase"], "loading")
1481
1482    def test_exclusive_lease_waits_for_shared_holders_and_shared_holders_coexist(self):
1483        first = runtime.acquire_activity_lease(shared=True)
1484        second = runtime.acquire_activity_lease(shared=True)
1485        try:
1486            with self.assertRaisesRegex(profiles.ProfileError, "engine lease"):
1487                runtime.acquire_activity_lease(shared=False)
1488        finally:
1489            for descriptor in (first, second):
1490                runtime._unlock_file(descriptor)
1491                os.close(descriptor)
1492        exclusive = runtime.acquire_activity_lease(shared=False)
1493        try:
1494            with self.assertRaisesRegex(profiles.ProfileError, "engine lease"):
1495                runtime.acquire_activity_lease(shared=True)
1496        finally:
1497            runtime._unlock_file(exclusive)
1498            os.close(exclusive)
1499
1500
1501class StartWaitLimit(unittest.TestCase):
1502    def setUp(self):
1503        # A start writes an operation record before the engine runs, so these tests keep their records (and any profile
1504        # lookup) in a scratch folder rather than in the person's own state.
1505        temp = tempfile.TemporaryDirectory(prefix="strata-start-wait-test-")
1506        self.addCleanup(temp.cleanup)
1507        root = Path(temp.name)
1508        (root / "profiles").mkdir()
1509        env = mock.patch.dict(os.environ, {"STRATA_PROFILE_DIR": str(root / "profiles"),
1510                                           "STRATA_RUNTIME_DIR": str(root / "runtime")})
1511        env.start()
1512        self.addCleanup(env.stop)
1513
1514    def test_a_start_may_wait_up_to_thirty_minutes_for_a_big_model(self):                    # #3949
1515        from strata_control import runtime as rt, profiles as pr
1516        self.assertEqual(rt.MAX_START_WAIT, 1800)
1517        with self.assertRaisesRegex(pr.ProfileError, "start wait must be 0..1800"):
1518            rt.start("x", wait=1801)
1519        with mock.patch.object(rt, "_name", side_effect=pr.ProfileError("reached")):
1520            with self.assertRaisesRegex(pr.ProfileError, "reached"):
1521                rt.start("x", wait=1800)
1522
1523    def test_a_long_start_wait_reaches_the_runtime_through_the_cli(self):                     # #3459 #4191
1524        # The desktop app starts models through `strata runtime start --wait`, and that wait is checked three times before
1525        # the engine is reached: by management, by the operation record, and by the runtime itself. When only the runtime's
1526        # ceiling was raised (#3949), a long start died at each of the first two with
1527        # "start wait must be finite seconds in 0..600" / "direct runtime intent has an invalid timeout". So this walks the
1528        # whole way with only the engine itself faked: any layer that still carries the old 600 s shows up here.
1529        from strata_control import journal as jn, management as mg, profiles as pr, runtime as rt
1530        revision = "0123456789abcdef"
1531        for wait in (300, 600, 601, rt.MAX_START_WAIT):
1532            reached = {}
1533            with mock.patch.object(rt, "_name", lambda name: name), \
1534                    mock.patch.object(mg.profiles, "load", lambda name: ("src", revision)), \
1535                    mock.patch.object(rt, "start", lambda name, **kw: (reached.update(kw),
1536                            {"ok": True, "state": "ready", "profile": name})[1]):
1537                result = mg.runtime_action("start", "demo", wait=wait, shutdown_timeout=15)
1538                self.assertEqual(result["state"], "ready")
1539                self.assertEqual(reached["wait"], float(wait),
1540                                 f"a start asked for {wait} s did not reach runtime.start with it")
1541
1542    def test_a_start_wait_above_the_runtime_ceiling_is_named_by_the_runtime(self):             # #3459 #4191
1543        from strata_control import management as mg, profiles as pr, runtime as rt
1544        revision = "0123456789abcdef"
1545        with mock.patch.object(rt, "_name", lambda name: name), \
1546                mock.patch.object(mg.profiles, "load", lambda name: ("src", revision)):
1547            with self.assertRaisesRegex(pr.ProfileError, f"start wait must be finite seconds in 0..{rt.MAX_START_WAIT}"):
1548                mg.runtime_action("start", "demo", wait=rt.MAX_START_WAIT + 1, shutdown_timeout=15)
1549            with self.assertRaisesRegex(pr.ProfileError, f"startup wait must be finite seconds in 1..{rt.MAX_START_WAIT}"):
1550                mg.runtime_action("restart", "demo", startup_wait=rt.MAX_START_WAIT + 1,
1551                                  if_owner_id="0" * 32, if_instance_id="0" * 32)
1552
1553    def test_the_operation_record_takes_the_runtimes_own_start_ceiling(self):
1554        # The record is written before the start runs, so a ceiling kept here would stop a long wait no matter what the
1555        # two validators above allow. Waits that are not a start or a restart keep their own 600 s.
1556        from strata_control import journal as jn, profiles as pr, runtime as rt
1557        for kind, intent, allowed in (
1558                ("runtime.start", {"wait_s": rt.MAX_START_WAIT, "shutdown_timeout_s": 15}, True),
1559                ("runtime.start", {"wait_s": rt.MAX_START_WAIT + 1, "shutdown_timeout_s": 15}, False),
1560                ("runtime.restart", {"wait_s": 1000, "startup_wait_s": rt.MAX_START_WAIT,
1561                                     "expected_profile_revision": "0" * 16,
1562                                     "expected_owner_id": "0" * 32, "expected_instance_id": "0" * 32,
1563                                     "allow_source_switch": False, "allow_source_migration": False,
1564                                     "expected_source_sha256": "0" * 64}, True),
1565                ("runtime.stop", {"wait_s": rt.MAX_START_WAIT}, False),
1566                ("runtime.verify", {"wait_s": rt.MAX_START_WAIT, "load": False}, False)):
1567            with self.subTest(kind=kind, wait=intent["wait_s"]):
1568                if allowed:
1569                    jn._validate_direct_intent(kind, dict(intent))
1570                else:
1571                    with self.assertRaisesRegex(pr.ProfileError, "invalid timeout"):
1572                        jn._validate_direct_intent(kind, dict(intent))
1573
1574
1575if __name__ == "__main__":
1576    unittest.main()