okami.mom/strata

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

Niko1221Merge f-0215-statewait: runtime: a start waiting for its owner reads an empty state file as not there yet (#5601)998077b33

main
86.1 KiB1589 linesraw
1"""Local owner-controlled supervisor for one saved Strata serving profile.
2
3The supervisor holds the Popen handle for the server it started. A client never
4sends a signal to a PID found in a ready file. The control channel and token live
5in an owner-private directory.
6
7POSIX: an owner-private AF_UNIX socket, flock leases, SIGTERM to the server's own
8process group. Windows: a loopback-only TCP listener authorised by the 256-bit
9token (strata_control/owner_transport.py), byte-range leases (winproc.py), a
10protected one-entry ACL on the state directory, and a kill-on-close job object
11around the server tree. A PID in a state file is never signalled: it is only
12compared (with its creation time on Windows) to decide whether the recorded
13child is still there.
14"""
15
16from __future__ import annotations
17
18from strata_control.private_files import private_mkdir as _private_mkdir
19from strata_control.childenv import quiet_crash_env
20import argparse
21import errno
22import hashlib
23import json
24import os
25import re
26import secrets
27import signal
28import socket
29import stat
30import subprocess
31import sys
32import threading
33import time
34import uuid
35from pathlib import Path
36
37try:
38    import fcntl
39except ImportError:  # Windows has no qualified owner transport yet.
40    fcntl = None
41
42from strata_control import owner_transport, paths, posix_owner, private_files, procs, profiles, readiness, winproc
43from serve import launch_identity
44from strata_control.profiles import ProfileError
45
46
47MAX_MESSAGE = 64 * 1024
48ROOT = Path(__file__).resolve().parents[1]
49WINDOWS = os.name == "nt"
50_STARTED_HOSTS: dict[str, subprocess.Popen] = {}
51
52
53def _is_private(details: os.stat_result, path: Path) -> bool:
54    """Owner-only: POSIX owner and no group/other bits; Windows an ACL that shuts out every other account."""
55    if WINDOWS:
56        try:
57            return private_files.is_unshared(path)
58        except OSError:
59            return False
60    return not posix_owner.owner_only_wrong(path, details)
61
62
63def _lock_file(descriptor: int, *, exclusive: bool) -> bool:
64    """Take a lease without waiting: True when taken, False when another holder has it."""
65    if WINDOWS:
66        return winproc.try_lock(descriptor, exclusive=exclusive)
67    try:
68        fcntl.flock(descriptor, (fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH) | fcntl.LOCK_NB)
69    except OSError as exc:
70        if exc.errno in (errno.EWOULDBLOCK, errno.EAGAIN):
71            return False
72        raise
73    return True
74
75
76def _unlock_file(descriptor: int) -> None:
77    """Windows releases a lock only some time after the handle closes: release it now. POSIX closes."""
78    if WINDOWS:
79        winproc.unlock(descriptor)
80
81
82def _supported() -> None:
83    """Refuse only when no transport exists at all.
84
85    POSIX uses an owner-private ``AF_UNIX`` socket. Windows uses a loopback-only TCP listener whose
86    authority rests on the 256-bit control token plus a ``0700`` state directory, because the Python
87    standard library cannot create a named pipe with a security descriptor; the difference is
88    recorded in ``owner_transport`` and in ``history/docs/work/IMPLEMENTATION_STATUS.md`` rather than being
89    presented as equivalent. Anything else is refused.
90    """
91    if os.name == "nt" or (os.name == "posix" and hasattr(socket, "AF_UNIX")):
92        return
93    raise ProfileError("managed runtime has no qualified local control transport on this platform", 5)
94
95
96def _name(value: str) -> str:
97    if not profiles.PROFILE_ID.fullmatch(value):
98        raise ProfileError("runtime commands require a saved profile name")
99    return value
100
101
102def runtime_dir() -> Path:
103    _supported()
104    override = os.environ.get("STRATA_RUNTIME_DIR")
105    if override:
106        base = Path(override).expanduser()
107    else:
108        base = paths.state_base() / "runtime"
109    if not base.is_absolute():
110        raise ProfileError("STRATA_RUNTIME_DIR must be absolute")
111    existed = base.exists()
112    _private_mkdir(base, parents=True, exist_ok=True)
113    details = base.lstat()
114    if WINDOWS and stat.S_ISDIR(details.st_mode):
115        if not private_files.volume_has_acls(base):        # exFAT / FAT: no permissions exist, so there is nothing to check
116            _warn_no_acls(base)
117            return base
118        if not existed:
119            _make_private(base)                            # no mode bits on NTFS: a protected ACL
120        if not _is_private(details, base):
121            # A folder that was there before (made by an elevated install, an older version, or with the parent's ACL inherited) can
122            # name other accounts.  It is the user's own state folder: take that away instead of stopping the launch, then check again.
123            _make_private(base)
124            try:
125                details = base.lstat()
126            except OSError:
127                pass
128    if not stat.S_ISDIR(details.st_mode) or not _is_private(details, base):
129        raise ProfileError(_not_private_message(base), 5)
130    return base
131
132
133def _make_private(base: Path) -> None:
134    """Windows: a protected ACL naming this user; where that is refused (a folder made by an elevated run), take ownership first."""
135    try:
136        private_files.restrict_to_current_user(base, directory=True)
137    except OSError:
138        pass
139    if _is_private(None, base):                             # type: ignore[arg-type] - details are not used on Windows
140        return
141    try:
142        private_files.repair_access(base, tree=False)
143    except OSError:
144        pass
145
146
147_NO_ACL_WARNED: set[str] = set()
148
149
150def _warn_no_acls(base: Path) -> None:
151    if str(base) not in _NO_ACL_WARNED:
152        _NO_ACL_WARNED.add(str(base))
153        print(f"[strata] {base} is on a drive that has no file permissions (FAT or exFAT), so other accounts on this PC could "
154              f"read what Strata keeps there. Use a drive formatted as NTFS if that matters.", file=sys.stderr, flush=True)
155
156
157def _not_private_message(base: Path) -> str:
158    if WINDOWS:
159        try:
160            names = private_files.who_can_reach(base) if base.is_dir() else []
161            readable = True
162        except OSError:
163            names, readable = [], False
164        if not readable:
165            return (f"Strata cannot read the permissions of {base}, the folder where it keeps its running state. Run Strata once as "
166                    f"yourself (not as administrator), or delete that folder: Strata makes a private one again.")
167        who = ", ".join(names) if names else "other accounts"
168        return (f"Strata keeps its running state in {base}, and {who} can open that folder. Strata could not change that. "
169                f"Right-click the folder, choose Properties > Security, and remove those accounts (or delete the folder: Strata "
170                f"makes a private one again).")
171    return "runtime directory must be owner-only (mode 0700)"
172
173
174def acquire_activity_lease(*, shared: bool) -> int:
175    """Let managed hosts coexist while excluding a local calibration run."""
176    directory = runtime_dir()
177    flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0)
178    try:
179        descriptor = os.open(directory / ".activity.lock", flags, 0o600)
180        details = os.fstat(descriptor)
181        if not stat.S_ISREG(details.st_mode) or not _is_private(details, directory / ".activity.lock"):
182            raise ProfileError("runtime activity lock must be owner-only", 5)
183        if not _lock_file(descriptor, exclusive=not shared):
184            raise ProfileError("a managed runtime or calibration owns the local engine lease", 6)
185        return descriptor
186    except BaseException:
187        if "descriptor" in locals():
188            os.close(descriptor)
189        raise
190
191
192def active_managed_instances() -> list[dict]:
193    """Inspect private owner records, including stale or uncertain instances."""
194    directory = runtime_dir()
195    names = [path.stem for path in directory.glob("*.json") if profiles.PROFILE_ID.fullmatch(path.stem)]
196    if len(names) > 64:
197        raise ProfileError("too many managed runtime records to verify exclusive access", 6)
198    active = []
199    for name in names:
200        current = status(name)
201        if current.get("state") != "stopped":
202            active.append({"profile": name, "state": current.get("state", "unknown")})
203    return active
204
205
206def _paths(name: str) -> tuple[Path, Path, Path]:
207    directory = runtime_dir()
208    digest = hashlib.sha256((str(directory) + "\0" + name).encode("utf-8")).hexdigest()[:16]
209    # The address form is the transport's business: POSIX gets a private socket path (with the
210    # short-path fallback for a long home directory), Windows gets its loopback placeholder, which
211    # the listener replaces with the real port when it binds.
212    address = owner_transport.address_for(directory, name)
213    return directory / f"{name}.json", address, directory / f"{name}.host.log"
214
215
216def _read_state(name: str, pending_ok: bool = False) -> dict | None:
217    """The owner's state file, or None when there is none. `pending_ok` (a start waiting for the owner it just launched): an empty or half-written
218    file is that owner still writing its state (it creates the file as its lease, then writes it), so it reads as not there yet instead of
219    unreadable (#5601: the test start of an update failed on a 0-byte read that was 191 bytes 100 ms later)."""
220    path, socket_path, _ = _paths(_name(name))
221    try:
222        details = path.lstat()
223    except FileNotFoundError:
224        return None
225    if pending_ok and stat.S_ISREG(details.st_mode) and details.st_size == 0:
226        return None
227    if not stat.S_ISREG(details.st_mode) or not _is_private(details, path) or details.st_size > 16 * 1024:
228        raise ProfileError("runtime state file is not private or is invalid", 5)
229    try:
230        state = json.loads(path.read_text(encoding="utf-8"))
231    except FileNotFoundError:
232        return None                 # the owner left between the look and the read: there is no state any more
233    except (OSError, UnicodeError, ValueError):
234        if pending_ok:
235            return None
236        raise ProfileError("runtime state file is unreadable", 5) from None
237    # POSIX: the address is the one derived from the profile. Windows: the port is chosen when the owner binds, so
238    # the state file carries it, and the only address a client may be sent to is a loopback port.
239    address_ok = bool(re.fullmatch(r"tcp:127\.0\.0\.1:[1-9][0-9]{0,4}", str(state.get("socket", "")))) \
240        if WINDOWS and isinstance(state, dict) else (isinstance(state, dict) and state.get("socket") == socket_path)
241    if not isinstance(state, dict) or state.get("schema_version") != 1 or state.get("profile") != name or \
242            not address_ok or not isinstance(state.get("token"), str) or \
243            not re.fullmatch(r"[0-9a-f]{64}", state["token"]):
244        raise ProfileError("runtime state file has an unsupported shape", 5)
245    return state
246
247
248def _child_marker(name: str, token: str) -> Path:
249    return runtime_dir() / f"{name}-{token}.child.json"
250
251
252def _pid_exists(pid: int, started: int | None = None) -> bool:
253    """Whether the recorded child is still there. Never signals: on Windows `os.kill(pid, 0)` would END the process,
254    so liveness is a handle query, and `started` (the creation time recorded with the PID) tells the recorded
255    process from a later one that reused the number."""
256    if WINDOWS:
257        return winproc.pid_alive(pid, started)
258    try:
259        os.kill(pid, 0)  # Liveness check only; never signal a PID from saved state.
260    except ProcessLookupError:
261        return False
262    except PermissionError:
263        return True
264    return True
265
266
267_MARKER_SLACK = 2.0   # seconds: the child starts before its marker is written; this much of clock rounding is allowed
268
269
270def _child_present(child: dict, written: float | None = None) -> bool:
271    """Whether the child recorded in an owner marker is still there. A marker without a creation time (Windows could not
272    read it when the child started) cannot tell the recorded server from a later process that reused the number, so
273    a live process that is not a Python or Strata executable is a reused number: the child is gone (#3488).
274
275    `written` is when the marker was written (its file time). The child was started before that, so a process that was created
276    AFTER it cannot be the child, whatever its image: the number was reused. This is what clears a marker left by a force-killed app
277    when the number now belongs to another Python program (2026-10-22: every load said "still present", and removing the marker by
278    hand was the only way out)."""
279    started = child.get("started") if type(child.get("started")) is int else None
280    if not _pid_exists(child["pid"], started):
281        return False
282    if started is None and written is not None:
283        created = procs.started_epoch(child["pid"])
284        if created is not None and created > written + _MARKER_SLACK:
285            return False
286    if WINDOWS and started is None:
287        image = winproc.process_image(child["pid"])
288        if image is not None:
289            name = os.path.basename(image).lower()
290            if "python" not in name and "strata" not in name:
291                return False
292    return True
293
294
295def _host_lease_active(name: str) -> bool:
296    path, _, _ = _paths(name)
297    descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
298    try:
299        if not _lock_file(descriptor, exclusive=True):
300            return True
301        _unlock_file(descriptor)
302        return False
303    finally:
304        os.close(descriptor)
305
306
307def _recover_stale(name: str, *, wait: float) -> bool:
308    """Reclaim private state only after the host lease and owned child are gone."""
309    state = _read_state(name)
310    if state is None:
311        return False
312    state_path, socket_path, _ = _paths(name)
313    flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
314    descriptor = os.open(state_path, flags)
315    try:
316        if os.fstat(descriptor).st_ino != state_path.lstat().st_ino:
317            raise ProfileError("runtime state changed during recovery", 6)
318        if not _lock_file(descriptor, exclusive=True):
319            raise ProfileError("this profile already has a live managed runtime", 6)
320        marker = _child_marker(name, state["token"])
321        try:
322            details = marker.lstat()
323            if not stat.S_ISREG(details.st_mode) or not _is_private(details, marker) or details.st_size > 4096:
324                raise ValueError("invalid owner marker")
325            child = json.loads(marker.read_text(encoding="utf-8"))
326        except (OSError, ValueError):
327            raise ProfileError("lost host has no valid child ownership record; inspect before recovery", 6) from None
328        if not isinstance(child, dict) or child.get("host_token") != state["token"]:
329            raise ProfileError("lost host child launch is unverified; inspect before recovery", 6)
330        # #4250: the owner writes {"phase": "no_child"} before it publishes its state, and "launching" before it starts a server. A host
331        # lost in between has no server by that exact record (this host's token, nothing else in it); a missing or other record proves nothing.
332        prelaunch = child.get("phase") == "no_child"
333        if prelaunch:
334            if set(child) != {"host_token", "phase"}:
335                raise ProfileError("lost host child launch is unverified; inspect before recovery", 6)
336        else:
337            if child.get("phase") != "owned" or type(child.get("pid")) is not int or child["pid"] <= 0:
338                raise ProfileError("lost host child launch is unverified; inspect before recovery", 6)
339            deadline = time.monotonic() + min(45.0, max(5.0, wait))
340            written = details.st_mtime
341            while _child_present(child, written) and time.monotonic() < deadline:
342                time.sleep(0.1)
343            if _child_present(child, written):
344                raise ProfileError("lost host child is still present; retry after it exits", 6)
345            if not isinstance(child.get("ready"), str):
346                raise ProfileError("lost host ready path is invalid; inspect before recovery", 6)
347            ready = Path(child["ready"])
348            if ready.parent != runtime_dir() or not ready.name.startswith(name + "-") or \
349                    not ready.name.endswith(".ready.json"):
350                raise ProfileError("lost host ready path is invalid; inspect before recovery", 6)
351            try:
352                details = ready.lstat()
353                if not stat.S_ISREG(details.st_mode) or not _is_private(details, ready):
354                    raise ProfileError("lost host ready file is invalid; inspect before recovery", 6)
355                ready.unlink()
356            except FileNotFoundError:
357                pass
358        if not owner_transport.WINDOWS:
359            # POSIX: the endpoint is a filesystem socket, so it can be inspected directly. A socket
360            # that is still accepting means a live owner, and nothing may be recovered over it.
361            try:
362                details = Path(socket_path).lstat()
363                if not stat.S_ISSOCK(details.st_mode) or details.st_uid != os.getuid():
364                    raise ProfileError("lost host socket is invalid; inspect before recovery", 6)
365                with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as probe:
366                    probe.settimeout(0.2)
367                    try:
368                        probe.connect(str(socket_path))
369                    except OSError as exc:
370                        if exc.errno not in (errno.ECONNREFUSED, errno.ENOENT):
371                            raise ProfileError(
372                                "lost host socket cannot be verified; inspect before recovery", 6) from None
373                    else:
374                        raise ProfileError(
375                            "a control listener still owns this socket; inspect before recovery", 6)
376                Path(socket_path).unlink()
377            except FileNotFoundError:
378                pass
379        # Windows: the endpoint is a loopback port chosen at bind time, so there is no artifact to
380        # inspect and none to clean up. Recovery rests on the state file, the owner pid and the
381        # token, all of which the caller has already validated.
382        snapshots = list(runtime_dir().glob(f"{name}-{state['token']}-*.rollback.json"))
383        if prelaunch and snapshots:
384            raise ProfileError("lost host prelaunch state has config snapshots; inspect before recovery", 6)
385        if len(snapshots) > 64:
386            raise ProfileError("too many lost-host config snapshots; inspect before recovery", 6)
387        for snapshot in snapshots:
388            details = snapshot.lstat()
389            if not stat.S_ISREG(details.st_mode) or not _is_private(details, snapshot):
390                raise ProfileError("lost-host config snapshot is not private; inspect before recovery", 6)
391            snapshot.unlink()
392        marker.unlink()
393        if WINDOWS:                    # an open file cannot be deleted on Windows: release the lease first
394            _unlock_file(descriptor)
395            os.close(descriptor)
396            descriptor = -1
397        state_path.unlink()
398        return True
399    finally:
400        if descriptor >= 0:
401            os.close(descriptor)
402
403
404def _write_new(path: Path, data: bytes) -> int:
405    descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
406    try:
407        # Keep this lease open in the owner host. The kernel releases it even
408        # after SIGKILL, unlike a PID file or a stale Unix socket.
409        if not _lock_file(descriptor, exclusive=True):
410            raise OSError(errno.EWOULDBLOCK, "the runtime lease is held")
411        with os.fdopen(os.dup(descriptor), "wb") as stream:
412            stream.write(data)
413            stream.flush()
414        os.fsync(descriptor)
415        return descriptor
416    except BaseException:
417        os.close(descriptor)
418        path.unlink(missing_ok=True)
419        raise
420
421
422def _rpc(name: str, command: str, *, timeout: float = 5, params: dict | None = None) -> dict:
423    state = _read_state(name)
424    if state is None:
425        raise ProfileError("runtime is not managed or is stopped", 3)
426    request = {"token": state["token"], "command": command}
427    if params:
428        request.update(params)
429    raw = (json.dumps(request) + "\n").encode("utf-8")
430    # The transport decides the address family: a private POSIX socket, or the loopback listener
431    # on Windows. The token in `raw` is what authorises the request either way.
432    try:
433        client = owner_transport.connect(state["socket"], timeout=timeout)
434    except OSError:      # nothing listens there any more (a lost owner), or it did not answer in time
435        raise ProfileError("runtime control is unavailable; inspect the private host log", 3) from None
436    try:
437        try:
438            client.sendall(raw)
439            answer = bytearray()
440            while len(answer) <= MAX_MESSAGE:
441                chunk = client.recv(4096)
442                if not chunk:
443                    break
444                answer.extend(chunk)
445                if b"\n" in chunk:
446                    break
447        except socket.timeout:
448            raise ProfileError("runtime operation wait expired; inspect runtime status", 8) from None
449        except OSError:
450            raise ProfileError("runtime control is unavailable; inspect the private host log", 3) from None
451    finally:
452        client.close()
453    if len(answer) > MAX_MESSAGE:
454        raise ProfileError("runtime control response is too large", 6)
455    try:
456        result = json.loads(answer.split(b"\n", 1)[0])
457    except (ValueError, UnicodeError):
458        raise ProfileError("runtime control returned an invalid response", 6) from None
459    if not isinstance(result, dict) or type(result.get("ok")) is not bool:
460        raise ProfileError("runtime control returned an invalid response", 6)
461    return result
462
463
464def status(name: str) -> dict:
465    state = _read_state(name)
466    if state is None:
467        return {"ok": True, "profile": name, "state": "stopped"}
468    try:
469        active = _host_lease_active(name)
470    except FileNotFoundError:
471        return {"ok": True, "profile": name, "state": "stopped"}
472    if not active:
473        return {"ok": False, "profile": name, "state": "stale", "error": "owner_host_lost",
474                "next_action": "runtime start will recover after the owned child exits", "exit_code": 6}
475    return _rpc(name, "status")
476
477
478def _start_candidate(name: str) -> tuple[dict, str]:
479    from strata_cli.cli import _launch_plan
480    plan, _ = _launch_plan(name)
481    digest = hashlib.sha256(Path(plan["source_config"]).read_bytes()).hexdigest()
482    return plan, digest
483
484
485def _engine_preflight(plan: dict) -> None:
486    """Refuse a start before any process exists when the run config names its engine as a component and the package for this
487    PC is missing or fails its integrity check (every file's SHA-256). The server checks again when it starts the engine; this
488    check makes the refusal the first thing the user sees, with the file named, instead of a log line behind 'server_exited'."""
489    try:
490        cfg = json.loads(Path(plan["source_config"]).read_text(encoding="utf-8-sig"))
491    except (OSError, ValueError, KeyError, TypeError):
492        return
493    if not isinstance(cfg, dict):
494        return
495    from strata_control import engine_component
496    if not engine_component.is_reference(cfg.get("exe")):
497        return
498    try:
499        engine_component.expand(cfg["exe"], cfg)
500    except engine_component.EngineMissing as exc:
501        raise ProfileError(str(exc), exc.exit_code) from None
502
503
504def _ready_pid_is_child(ready_pid, child_pid: int) -> bool:
505    """Is the process named in the ready file the one this host started?
506
507    Normally the pids are equal. A Windows venv (the python.exe of a source checkout's .venv) starts its real interpreter as a
508    CHILD of the launcher it was given, so the server that writes the ready file is one process below the pid ``Popen`` returned
509    (#3683: the staged engine was ready, this check never matched, and the start waited out its whole deadline). Only on Windows,
510    and only for a process that sits within three parents of the process this host started, so another process cannot pass."""
511    if type(ready_pid) is not int or ready_pid <= 0:
512        return False
513    if ready_pid == child_pid:
514        return True
515    if not WINDOWS:
516        return False
517    current = ready_pid
518    for _ in range(3):
519        parent = procs.parent_of(current)
520        if parent is None or parent <= 0:
521            return False
522        if parent == child_pid:
523            return True
524        current = parent
525    return False
526
527
528def _check_start_candidate(name: str, expected_profile_revision: str | None,
529                           expected_source_sha256: str | None) -> tuple[dict, str]:
530    plan, digest = _start_candidate(name)
531    if expected_profile_revision is not None and plan["profile_revision"] != expected_profile_revision:
532        raise ProfileError("profile_changed_after_start_plan", 6)
533    if expected_source_sha256 is not None and digest != expected_source_sha256:
534        raise ProfileError("source_changed_after_start_plan", 6)
535    return plan, digest
536
537
538def _repair_config_paths(name: str) -> tuple[str | None, str | None]:
539    """Before a start: every path of the saved run configs that names a version folder of Strata's own that an update removed (the Control bundle
540    that ran setup: cwd, --expert-profile; an engine package: the picture reader, library folders) is pointed at the current
541    version and written once (strata_control/cfg_paths.py; the same resolver the config reader applies in memory).  One line of what it did goes to
542    the profile's host log.  Returns (the profile's own run config digest before, after) when it changed that file, for a caller that planned the
543    start on the old digest.  A path that exists in no current version stops the start with the file named."""
544    try:
545        from strata_control import cfg_paths
546        profile, _ = profiles.load(name)
547        own = Path(profile["source_config"])
548        before = hashlib.sha256(own.read_bytes()).hexdigest()
549        configs = [own, *[c for c in cfg_paths.saved_configs() if c != own]]
550        notes, problems = cfg_paths.repair(configs)
551        if notes:
552            _, _, log_path = _paths(name)
553            if log_path.parent.is_dir():
554                with open(log_path, "ab") as stream:
555                    for note in notes:
556                        stream.write(f"{time.strftime('%Y-%m-%dT%H:%M:%S')} config: {note}\n".encode("utf-8"))
557        mine = [p for p in problems if p.startswith(own.name + ":")]
558        after = hashlib.sha256(own.read_bytes()).hexdigest()
559        if mine:
560            raise ProfileError(mine[0], 6)
561        return (before, after) if after != before else (None, None)
562    except ProfileError:
563        raise
564    except Exception:                                    # noqa: BLE001 - a start never fails because of this
565        return None, None
566
567
568def _refuse_deepseek(name: str) -> None:
569    """Before a start: a saved profile whose run config is a DeepSeek one stops here with the plain refusal (the model's folder and size
570    when they can be read; strata_control/retired.py).  Nothing is written, no process is started; a local, bounded check."""
571    from strata_control import retired
572    try:
573        profile, _ = profiles.load(name)
574        source = profile.get("source_config")
575    except Exception:                                    # noqa: BLE001 - the usual checks below say what is wrong with the profile
576        return
577    cfg = retired.read_config(source)
578    if retired.config_reason(cfg) or retired.config_file_reason(source):
579        raise ProfileError(retired.refusal(cfg, retired.title(cfg, source)), 6)
580
581
582CHILD_EXIT_GRACE = 10.0     # seconds a host whose server ended on its own keeps answering "failed" (a waiting client reads why), then leaves (#4574 #4824)
583DIE_WITH_MISSES = 3         # consecutive looks, a second apart, at a process that cannot be found before the owner calls it gone (#4973)
584STATUS_RPC_TIMEOUT = 10.0   # seconds one status question may take; a busy owner is asked again until the start's wait is over (#5177)
585VERIFY_BUDGET = 180.0       # seconds an engine that says it is up may take to answer its first token, whatever is left of the load wait (#5177 #5059)
586MAX_START_WAIT = 1800     # seconds a start may wait for the model: a 250 GB set on a slow disk needs more than 10 minutes (#3949)
587
588
589def start(name: str, *, wait: float = 300, shutdown_timeout: float = 30,
590          expected_profile_revision: str | None = None,
591          expected_source_sha256: str | None = None,
592          die_with_pid: int | None = None, on_status=None) -> dict:
593    """Start the saved profile under a new owner host.
594
595    ``on_status`` (optional) is called with each status answer while the start waits (about every 0.2 s; the caller throttles), so a
596    caller can show progress. The result of a wait that ran out names the last phase (``loading``, ``verifying_generation``,
597    ``ready_file_not_matched``).
598
599    The owner host is a background service: it is not tied to the terminal or the process that ran this command and
600    keeps serving after they end. It stops on `runtime stop`, when its server ends, or - only if `die_with_pid`
601    names a process - when that process is gone (the desktop app uses this for the engines it starts)."""
602    name = _name(name)
603    die_with = None
604    if die_with_pid is not None:
605        token = procs.start_token(die_with_pid) if type(die_with_pid) is int else None
606        if token is None:
607            raise ProfileError("the process to follow with --die-with-pid is not running")
608        die_with = (die_with_pid, token)
609    if not 0 <= wait <= MAX_START_WAIT or not 0 <= shutdown_timeout <= 300:
610        raise ProfileError(f"start wait must be 0..{MAX_START_WAIT} and shutdown timeout 0..300 seconds")
611    if expected_profile_revision is not None and (not isinstance(expected_profile_revision, str) or
612            not re.fullmatch(r"[0-9a-f]{16}", expected_profile_revision)):
613        raise ProfileError("expected profile revision must be 16 lowercase hex characters")
614    if expected_source_sha256 is not None and (not isinstance(expected_source_sha256, str) or
615            not re.fullmatch(r"[0-9a-f]{64}", expected_source_sha256)):
616        raise ProfileError("expected source digest must be 64 lowercase hex characters")
617    _refuse_deepseek(name)                             # before anything is written or started (strata_control/retired.py)
618    changed_from, changed_to = _repair_config_paths(name)
619    if changed_from is not None and expected_source_sha256 == changed_from:
620        expected_source_sha256 = changed_to              # (the caller planned on the file as it was; Strata rewrote it, the caller did not)
621    plan, _ = _check_start_candidate(name, expected_profile_revision, expected_source_sha256)
622    on_status = _progress(on_status, {"ok": True, "profile": name, "state": "starting", "phase": "checking_engine"})
623    _engine_preflight(plan)                # hashes every engine file (1.4 GB or more): minutes on a slow disk, no owner exists yet
624    _, _, log_path = _paths(name)
625    flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND
626    if hasattr(os, "O_NOFOLLOW"):
627        flags |= os.O_NOFOLLOW
628    lock_name = "rt" + hashlib.sha256(name.encode("utf-8")).hexdigest()[:24]
629    with profiles._lock(lock_name):
630        if expected_profile_revision is not None or expected_source_sha256 is not None:
631            _check_start_candidate(name, expected_profile_revision, expected_source_sha256)
632        procs.end_leftovers(profile=name)               # a server or engine a lost owner left behind (verified one by one)
633        if _read_state(name) is not None:
634            _recover_stale(name, wait=wait)
635        descriptor = os.open(log_path, flags, 0o600)
636        with os.fdopen(descriptor, "ab") as stream:
637            command = [sys.executable, "-m", "strata_control.runtime", "--host", name,
638                       "--shutdown-timeout", str(shutdown_timeout),
639                       "--startup-wait", str(wait if wait else 300)]
640            if expected_profile_revision is not None:
641                command += ["--expected-profile-revision", expected_profile_revision]
642            if expected_source_sha256 is not None:
643                command += ["--expected-source-sha256", expected_source_sha256]
644            if die_with is not None:
645                command += ["--die-with-pid", str(die_with[0]), "--die-with-token", die_with[1]]
646            detach = ({"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.CREATE_NO_WINDOW}
647                      if WINDOWS else {"start_new_session": True})
648            proc = subprocess.Popen(command,
649                                    cwd=ROOT, stdin=subprocess.DEVNULL, stdout=stream,
650                                    stderr=subprocess.STDOUT, close_fds=True, **detach)
651        _STARTED_HOSTS[name] = proc
652        deadline = time.monotonic() + max(5.0, wait)
653        while _read_state(name, pending_ok=True) is None and proc.poll() is None and time.monotonic() < deadline:
654            time.sleep(0.05)
655        if _read_state(name, pending_ok=True) is None:
656            if proc.poll() is not None:
657                _STARTED_HOSTS.pop(name, None)
658            raise ProfileError("runtime host failed to start; inspect " + str(log_path), 6)
659    if wait == 0:
660        return {"ok": True, "profile": name, "state": "starting", "plan": plan}
661    return _await_start(name, wait, on_status)
662
663
664def _await_start(name: str, wait: float, on_status=None) -> dict:
665    """Ask the owner how the start is going until it is ready, failed, or `wait` seconds have passed."""
666    deadline = time.monotonic() + wait
667    result: dict = {}
668    while True:
669        now = time.monotonic()
670        # The wait is the time for the model to LOAD. An engine that has said it is up is being checked with its first token, which has
671        # its own budget in the owner (VERIFY_BUDGET): the wait does not end under it (#5177 #5059 #4293)
672        limit = deadline + VERIFY_BUDGET if result.get("phase") == "verifying_generation" else deadline
673        if now >= limit:
674            break
675        try:
676            result = _rpc(name, "status", timeout=min(STATUS_RPC_TIMEOUT, max(1.0, limit - now)))
677        except ProfileError as exc:
678            # An owner that is busy does not answer for a while (its first imports, a slow disk, a virus scan of the engine). One
679            # missed answer is not a failed start: keep asking until the wait is over, as long as the owner is still alive. A lost
680            # owner (its lease is free, or nothing listens any more) is a failure now.
681            if exc.exit_code not in (3, 8) or not _owner_alive(name):
682                raise
683            result = {**result, "state": "starting", "phase": result.get("phase") or "owner_not_answering"}
684            time.sleep(0.2)
685            continue
686        if on_status is not None:
687            try:
688                on_status(result)
689            except Exception:                                   # noqa: BLE001 - progress must never break a start
690                on_status = None
691        if result.get("state") in ("ready", "failed"):
692            return {**result, "ok": result["state"] == "ready",
693                    "exit_code": 6 if result["state"] == "failed" else 0}
694        time.sleep(0.2)
695    return {"ok": False, "profile": name, "state": "starting", "error": "startup_wait_expired",
696            "phase": result.get("phase"), "exit_code": 8}
697
698
699def _progress(on_status, first: dict):
700    """`on_status` after one more answer is shown now: the phase before the owner exists."""
701    if on_status is not None:
702        try:
703            on_status(first)
704        except Exception:                                       # noqa: BLE001 - progress must never break a start
705            return None
706    return on_status
707
708
709def _owner_alive(name: str) -> bool:
710    """Whether the owner host of this profile is still running (its lease is held), without asking it anything."""
711    try:
712        if _read_state(name) is None:
713            return False
714        return _host_lease_active(name)
715    except (ProfileError, OSError):
716        return False
717
718
719def plan_stop(name: str) -> dict:
720    current = status(_name(name))
721    if current.get("state") not in ("ready", "starting", "failed") or not current.get("owner_id"):
722        return {"ok": False, "profile": name, "state": current.get("state", "unknown"),
723                "error": "runtime_not_owned", "exit_code": 6}
724    return {"ok": True, "plan": {"profile": name, "state": current["state"],
725                                 "owner_id": current["owner_id"],
726                                 "instance_id": current.get("instance_id"),
727                                 "profile_revision": current.get("profile_revision"),
728                                 "would_drain": False, "would_stop": False}}
729
730
731def stop(name: str, *, timeout: float = 330,
732         expected_owner_id: str | None = None,
733         expected_instance_id: str | None = None) -> dict:
734    if not 1 <= timeout <= 600:
735        raise ProfileError("stop wait must be 1..600 seconds")
736    name = _name(name)
737    if expected_owner_id is not None and (not isinstance(expected_owner_id, str) or
738            not re.fullmatch(r"[0-9a-f]{32}", expected_owner_id)):
739        raise ProfileError("expected owner ID must be 32 lowercase hex characters")
740    if expected_instance_id is not None and (not isinstance(expected_instance_id, str) or
741            not re.fullmatch(r"[0-9a-f]{32}", expected_instance_id)):
742        raise ProfileError("expected instance ID must be 32 lowercase hex characters")
743    params = {"expected_owner_id": expected_owner_id,
744              "expected_instance_id": expected_instance_id}
745    lost = _stop_lost(name)
746    if lost is not None:
747        return lost
748    result = _rpc(name, "stop", timeout=timeout, params=params)
749    if not result["ok"]:
750        return result
751    owned = _STARTED_HOSTS.pop(name, None)
752    if owned is not None:
753        try:
754            owned.wait(timeout=5)
755        except subprocess.TimeoutExpired:
756            _STARTED_HOSTS[name] = owned
757    return result
758
759
760def _stop_lost(name: str) -> dict | None:
761    """`stop` when there is no live owner host: the host was killed or crashed, so nobody can be asked to stop the
762    server it started. End what it left behind - the recorded server and engine, each re-checked by PID, start time
763    and command line - and clear the private state. None when an owner is running (the normal stop applies)."""
764    try:
765        state = _read_state(name)
766    except ProfileError:
767        state = None
768    if state is not None:
769        try:
770            if _host_lease_active(name):
771                return None
772        except FileNotFoundError:
773            state = None
774    outcome = procs.end_leftovers(profile=name)
775    recovered = False
776    if state is not None:
777        recovered = _recover_stale(name, wait=20)
778    if state is None and not any(outcome[key] for key in ("ended", "stuck", "unverifiable")):
779        return None                                   # nothing recorded: the normal "not managed or is stopped"
780    stuck = bool(outcome["stuck"] or outcome["unverifiable"])
781    return {"ok": not stuck, "profile": name, "state": "failed" if stuck else "stopped", "recovered": recovered,
782            "ended": outcome["ended"], "leftover_unverified": outcome["unverifiable"],
783            "exit_code": 6 if stuck else 0,
784            **({"error": "leftover_process_not_ended"} if stuck else {})}
785
786
787def cleanup(profile: str | None = None) -> dict:
788    """End the servers and engines Strata started whose owner is gone (`strata runtime cleanup`). Owned instances
789    that are running are not touched, and neither is any process that is not exactly what Strata recorded."""
790    if profile is not None:
791        profile = _name(profile)
792    outcome = procs.end_leftovers(profile=profile)
793    if profile is not None:
794        try:
795            if _read_state(profile) is not None and not _host_lease_active(profile):
796                outcome["recovered"] = _recover_stale(profile, wait=20)
797        except (ProfileError, FileNotFoundError):
798            pass
799    stuck = bool(outcome["stuck"] or outcome["unverifiable"])
800    return {"ok": not stuck, "state": "cleaned" if not stuck else "failed", **outcome,
801            "exit_code": 6 if stuck else 0}
802
803
804def verify(name: str, *, timeout: float = 300, load: bool = False,
805           expected_owner_id: str | None = None,
806           expected_instance_id: str | None = None) -> dict:
807    if not 1 <= timeout <= 600 or type(load) is not bool:
808        raise ProfileError("verify wait must be 1..600 seconds and load must be true or false")
809    for label, identity in (("owner", expected_owner_id), ("instance", expected_instance_id)):
810        if identity is not None and (not isinstance(identity, str) or
811                                     not re.fullmatch(r"[0-9a-f]{32}", identity)):
812            raise ProfileError(f"expected {label} ID must be 32 lowercase hex characters")
813    return _rpc(_name(name), "verify", timeout=timeout + 5,
814                params={"wait": timeout, "load": load,
815                        "expected_owner_id": expected_owner_id,
816                        "expected_instance_id": expected_instance_id})
817
818
819def restart(name: str, *, timeout: float = 1000, startup_wait: float = 300,
820            expected_profile_revision: str | None = None,
821            expected_owner_id: str | None = None,
822            expected_instance_id: str | None = None,
823            allow_source_switch: bool = False,
824            allow_source_migration: bool = False,
825            expected_source_sha256: str | None = None) -> dict:
826    if (not 1 <= timeout <= 1800 or not 1 <= startup_wait <= MAX_START_WAIT or
827            type(allow_source_switch) is not bool or type(allow_source_migration) is not bool):
828        raise ProfileError(f"restart wait must be 1..1800 and startup wait 1..{MAX_START_WAIT} seconds")
829    if expected_source_sha256 is not None and (not isinstance(expected_source_sha256, str) or
830                                               not re.fullmatch(r"[0-9a-f]{64}", expected_source_sha256)):
831        raise ProfileError("expected source SHA-256 must be 64 lowercase hex characters")
832    for label, identity in (("owner", expected_owner_id), ("instance", expected_instance_id)):
833        if identity is not None and (not isinstance(identity, str) or
834                                     not re.fullmatch(r"[0-9a-f]{32}", identity)):
835            raise ProfileError(f"expected {label} ID must be 32 lowercase hex characters")
836    if (allow_source_switch or allow_source_migration) and expected_source_sha256 is None:
837        raise ProfileError("source change needs the candidate SHA-256 from runtime restart --plan")
838    params = {"startup_wait": startup_wait, "allow_source_switch": allow_source_switch,
839              "allow_source_migration": allow_source_migration}
840    if expected_source_sha256 is not None:
841        params["expected_source_sha256"] = expected_source_sha256
842    if expected_profile_revision is not None:
843        params["expected_profile_revision"] = expected_profile_revision
844    if expected_owner_id is not None:
845        params["expected_owner_id"] = expected_owner_id
846    if expected_instance_id is not None:
847        params["expected_instance_id"] = expected_instance_id
848    return _rpc(_name(name), "restart", timeout=timeout, params=params)
849
850
851def plan_restart(name: str, *, allow_source_switch: bool = False,
852                 allow_source_migration: bool = False) -> dict:
853    if type(allow_source_switch) is not bool or type(allow_source_migration) is not bool:
854        raise ProfileError("source change options must be true or false")
855    return _rpc(_name(name), "plan_restart", timeout=10,
856                params={"allow_source_switch": allow_source_switch,
857                        "allow_source_migration": allow_source_migration})
858
859
860class Host:
861    def __init__(self, name: str, shutdown_timeout: float, startup_wait: float = 300,
862                 expected_profile_revision: str | None = None,
863                 expected_source_sha256: str | None = None,
864                 die_with: tuple[int, str] | None = None):
865        self.name = _name(name)
866        self.die_with = die_with           # (pid, start token): stop the server when that process is gone
867        self.shutdown_timeout = shutdown_timeout
868        self.expected_profile_revision = expected_profile_revision
869        self.expected_source_sha256 = expected_source_sha256
870        self.state_path, self.socket_path, self.log_path = _paths(name)
871        self.token = secrets.token_hex(32)
872        self.owner_id = uuid.uuid4().hex
873        self.child: subprocess.Popen | None = None
874        self.ready_path: Path | None = None
875        self.args: list[str] | None = None
876        self.source: Path | None = None
877        self.source_bytes: bytes | None = None
878        self.expected_attestation: str | None = None
879        self.revision: str | None = None
880        self.last_error: str | None = None
881        self.running = True
882        self.state_fd: int | None = None
883        self.owner_write_fd: int | None = None
884        self.owner_write = None            # Windows: the server's stdin pipe, whose EOF asks it to drain and stop
885        self.probe_timeout = startup_wait
886        self.gone_at: float | None = None  # when the server was first seen ended (the host leaves CHILD_EXIT_GRACE seconds later)
887        self.exit_status = 0
888        self.die_misses = 0
889        self.starting = False              # the plan and the launch run in a thread (_startup): the owner answers status meanwhile (#5177)
890        self.phase: str | None = None      # what that thread is doing: preparing | launching
891        self._launch_lock = threading.Lock()   # held while the server is being started or stopped, so a stop never races the launch
892        self.probe_deadline = 0.0
893        self.probe_key: tuple[int, str] | None = None
894        self.probe_result: dict | None = None
895        self.rollback_snapshots: set[Path] = set()
896
897    def _mark_child(self, phase: str, *, pid: int | None = None, ready: Path | None = None) -> None:
898        payload = {"host_token": self.token, "phase": phase}
899        if pid is not None and ready is not None:
900            payload.update(pid=pid, ready=str(ready))
901            if WINDOWS:
902                started = winproc.process_started(pid)
903                if started is None:
904                    time.sleep(0.05)
905                    started = winproc.process_started(pid)     # one more try: the child may not be queryable yet
906                if started is not None:
907                    payload["started"] = started   # tells this process from a later one with the same number
908        profiles._atomic(_child_marker(self.name, self.token), (json.dumps(payload) + "\n").encode())
909
910    def _plan(self) -> tuple[dict, list[str], Path, bytes]:
911        from strata_cli.cli import _launch_plan
912        plan, args = _launch_plan(self.name)
913        source = Path(plan["source_config"])
914        return plan, args, source, source.read_bytes()
915
916    def _source_change_check(self, source: Path, source_bytes: bytes,
917                             allow_source_switch: bool,
918                             allow_source_migration: bool) -> tuple[bool, bool, str | None]:
919        """Identify when rollback needs an owner-private copy of the running config."""
920        if source == self.source:
921            migrated = source_bytes != self.source_bytes
922            return False, migrated, ("source_config_changed_restart_requires_migration"
923                                     if migrated and not allow_source_migration else None)
924        if not allow_source_switch:
925            return True, False, "source_switch_requires_opt_in"
926        try:
927            old_stat, new_stat = self.source.lstat(), source.lstat()
928            if (not stat.S_ISREG(old_stat.st_mode) or not stat.S_ISREG(new_stat.st_mode) or
929                    (old_stat.st_dev, old_stat.st_ino) == (new_stat.st_dev, new_stat.st_ino)):
930                return True, False, "source_switch_requires_distinct_regular_files"
931            migrated = self.source.read_bytes() != self.source_bytes
932        except OSError:
933            return True, False, "rollback_source_unavailable"
934        return True, migrated, ("rollback_source_changed" if migrated and not allow_source_migration else None)
935
936    def _snapshot_running_config(self) -> Path:
937        """Save launch bytes before drain; never overwrite the operator's edited file."""
938        path = self.state_path.parent / f"{self.name}-{self.token}-{uuid.uuid4().hex}.rollback.json"
939        descriptor = _write_new(path, self.source_bytes)
940        os.close(descriptor)
941        self.rollback_snapshots.add(path)
942        return path
943
944    def _retire_snapshot(self, path: Path) -> bool:
945        if path in self.rollback_snapshots:
946            try:
947                path.unlink(missing_ok=True)
948            except OSError:
949                return False
950            self.rollback_snapshots.discard(path)
951        return True
952
953    @staticmethod
954    def _config_args(args: list[str], source: Path) -> list[str]:
955        result = list(args)
956        try:
957            index = result.index("--config")
958            result[index + 1] = str(source)
959        except (ValueError, IndexError):
960            raise ProfileError("owned launch has no run config argument", 6) from None
961        return result
962
963    def _launch(self, args: list[str], source: Path, source_bytes: bytes,
964                revision: str | None) -> None:
965        ready = self.state_path.parent / f"{self.name}-{uuid.uuid4().hex}.ready.json"
966        flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND
967        if hasattr(os, "O_NOFOLLOW"):
968            flags |= os.O_NOFOLLOW
969        log = self.state_path.parent / f"{self.name}.server.log"
970        self._mark_child("launching")
971        descriptor = os.open(log, flags, 0o600)
972        # POSIX: an inherited pipe with one writer (this host). Windows: the server's standard input is that pipe.
973        reader, writer = (None, None) if WINDOWS else os.pipe()
974        server_args = [*args, "--ready-file", str(ready),
975                       "--shutdown-timeout", str(self.shutdown_timeout),
976                       "--owner-fd", "0" if WINDOWS else str(reader)]
977        attestation_key = secrets.token_bytes(32)
978        expected_attestation = launch_identity.attestation(attestation_key, source_bytes, server_args)
979        child_env = quiet_crash_env(os.environ.copy())   # the server's engine and reader start no debugger on a user's machine
980        child_env["STRATA_OWNER_ATTEST_KEY"] = attestation_key.hex()
981        child_env["STRATA_NO_ACQUIRE"] = "1"      # a managed server never installs or downloads (acquisition.py)
982        child_env["STRATA_RUNTIME_PROFILE"] = self.name   # the records of its engine say which profile they belong to
983        try:
984            with os.fdopen(descriptor, "ab") as stream:
985                if WINDOWS:
986                    self.child = subprocess.Popen([sys.executable, "-m", "serve.server", *server_args],
987                                                  cwd=ROOT, stdin=subprocess.PIPE, stdout=stream,
988                                                  stderr=subprocess.STDOUT, close_fds=True, env=child_env,
989                                                  creationflags=subprocess.CREATE_NO_WINDOW)
990                    # the whole server tree ends with this host, however the host ends (a kill-on-close job)
991                    from serve import winjob
992                    winjob.contain(self.child)
993                else:
994                    self.child = subprocess.Popen([sys.executable, "-m", "serve.server", *server_args],
995                                                  cwd=ROOT, stdin=subprocess.DEVNULL, stdout=stream,
996                                                  stderr=subprocess.STDOUT, close_fds=True,
997                                                  pass_fds=(reader,), start_new_session=True, env=child_env)
998        except BaseException:
999            if writer is not None:
1000                os.close(writer)
1001            raise
1002        finally:
1003            if reader is not None:
1004                os.close(reader)
1005        if WINDOWS:
1006            self.owner_write = self.child.stdin
1007        else:
1008            self.owner_write_fd = writer
1009        procs.write_record(self.child.pid, "server", profile=self.name)
1010        try:
1011            self._mark_child("owned", pid=self.child.pid, ready=ready)
1012        except BaseException:
1013            # No ownership record means a future start cannot safely reclaim
1014            # this instance. Stop this child immediately instead.
1015            self._kill_child_tree()
1016            self.child.wait(timeout=10)
1017            self._close_owner_pipe()
1018            raise
1019        # (the status answer reads these from another thread: the ready path comes last, it is what makes the rest be read)
1020        self.args, self.source, self.source_bytes, self.revision = list(args), source, source_bytes, revision
1021        self.expected_attestation = expected_attestation
1022        self.last_error = None
1023        self.probe_deadline = time.monotonic() + self.probe_timeout
1024        self.probe_key = None
1025        self.probe_result = None
1026        self.ready_path = ready
1027
1028    def _verify_ready(self, ready: dict, key: tuple[int, str], host: str, source_bytes: bytes,
1029                      expected_attestation: str, timeout: float) -> None:
1030        try:
1031            result = readiness.verify(ready, source_bytes, expected_host=host,
1032                                      expected_instance=key[1],
1033                                      expected_attestation=expected_attestation, timeout=timeout)
1034        except readiness.ReadinessError as exc:
1035            result = {"error": str(exc)}
1036        except Exception:
1037            result = {"error": "probe_internal_error"}
1038        if self.probe_key == key:
1039            self.probe_result = result
1040            if "error" in result:
1041                self.last_error = result["error"]
1042
1043    def _log_tail(self, limit: int = 4096) -> str | None:
1044        """The last lines the server wrote (a failed start is explained by them), or None. Bounded read, never raises."""
1045        try:
1046            with open(self.state_path.parent / f"{self.name}.server.log", "rb") as stream:
1047                stream.seek(0, os.SEEK_END)
1048                stream.seek(max(0, stream.tell() - limit))
1049                lines = [x.rstrip() for x in stream.read().decode("utf-8", "replace").splitlines() if x.strip()]
1050        except OSError:
1051            return None
1052        # not the indented frames of a Python traceback: the engine's own lines and the final exception line say why
1053        plain = [x for x in lines if not x[0].isspace() and not x.startswith("Traceback")]
1054        chosen = plain[-3:] or lines[-1:]
1055        return " | ".join(x[:200] for x in chosen) if chosen else None
1056
1057    def _status(self) -> dict:
1058        child = self.child
1059        base = {"ok": True, "profile": self.name, "host_pid": os.getpid(),
1060                "owner_id": self.owner_id,
1061                "child_pid": child.pid if child else None, "profile_revision": self.revision,
1062                "shutdown_timeout": self.shutdown_timeout}
1063        if child is None:
1064            if self.starting:
1065                return {**base, "state": "starting", "phase": self.phase or "preparing"}
1066            if self.last_error is not None:
1067                return {**base, "ok": False, "state": "failed", "error": self.last_error, "exit_code": 6}
1068            return {**base, "state": "stopped"}
1069        if child.poll() is not None:
1070            # engine_exit_code: how the engine process ended (Windows: 0xC0000135 = a DLL was not found); `exit_code` is
1071            # Control's own and the start command overwrites it with 6, so the engine's code travels under its own name.
1072            return {**base, "ok": False, "state": "failed", "exit_code": child.returncode, "engine_exit_code": child.returncode,
1073                    "error": self.last_error or "server_exited", "log_tail": self._log_tail()}
1074        if self.ready_path is not None:
1075            try:
1076                ready = json.loads(self.ready_path.read_text(encoding="utf-8"))
1077                if _ready_pid_is_child(ready.get("pid"), child.pid) and isinstance(ready.get("instance_id"), str):
1078                    key = (child.pid, ready["instance_id"])
1079                    if self.probe_key != key:
1080                        self.probe_key, self.probe_result = key, None
1081                        host = self.args[self.args.index("--host") + 1]
1082                        threading.Thread(target=self._verify_ready,
1083                                         args=(ready, key, host, self.source_bytes,
1084                                               self.expected_attestation,
1085                                               max(VERIFY_BUDGET, self.probe_deadline - time.monotonic())),
1086                                         name="strata-generation-probe", daemon=True).start()
1087                    if self.probe_result is None:
1088                        return {**base, "state": "starting", "phase": "verifying_generation",
1089                                "instance_id": ready["instance_id"]}
1090                    if "error" in self.probe_result:
1091                        return {**base, "ok": False, "state": "failed", "error": self.probe_result["error"],
1092                                "exit_code": 6, "instance_id": ready["instance_id"]}
1093                    return {**base, "state": "ready", "instance_id": ready["instance_id"],
1094                            "model_state": ready.get("model_state"),
1095                            **self.probe_result}
1096                if isinstance(ready, dict):
1097                    # the server published its ready file but it is not the process this host started: say so, so a wait that
1098                    # ends can name it (before #3683 this looked exactly like a model that was still loading)
1099                    return {**base, "state": "starting", "phase": "ready_file_not_matched"}
1100            except (OSError, ValueError):
1101                pass
1102        return {**base, "state": "starting", "phase": "loading"}
1103
1104    def _wait_ready(self, timeout: float) -> dict:
1105        deadline = time.monotonic() + timeout
1106        while True:
1107            current = self._status()
1108            if current["state"] in ("ready", "failed"):
1109                return current
1110            # an engine that has said it is up is being checked with its first token, which has its own budget (VERIFY_BUDGET)
1111            limit = deadline + VERIFY_BUDGET if current.get("phase") == "verifying_generation" else deadline
1112            if time.monotonic() >= limit:
1113                break
1114            time.sleep(0.15)
1115        current = self._status()
1116        if current["state"] in ("ready", "failed"):
1117            return current
1118        return {**current, "ok": False, "error": "startup_wait_expired", "exit_code": 8}
1119
1120    def _stop_child(self) -> dict:
1121        child = self.child
1122        if child is None or child.poll() is not None:
1123            self._close_owner_pipe()
1124            if self.ready_path is not None:
1125                self.ready_path.unlink(missing_ok=True)
1126            return {"ok": True, "state": "stopped", "exit_code": child.returncode if child else 0}
1127        if WINDOWS:
1128            self._close_owner_pipe()             # EOF on the server's stdin: it drains and stops (no SIGTERM here)
1129        else:
1130            child.send_signal(signal.SIGTERM)
1131        try:
1132            code = child.wait(timeout=self.shutdown_timeout + 8)
1133        except subprocess.TimeoutExpired:
1134            self._kill_child_tree()
1135            child.wait(timeout=10)
1136            self._close_owner_pipe()
1137            return {"ok": False, "state": "failed", "error": "server_stop_deadline_expired", "exit_code": 8}
1138        self._close_owner_pipe()
1139        if self.ready_path is not None:
1140            self.ready_path.unlink(missing_ok=True)
1141        return {"ok": code == 0, "state": "stopped" if code == 0 else "failed",
1142                "exit_code": code, "error": None if code == 0 else "server_stop_failed"}
1143
1144    def _close_owner_pipe(self) -> None:
1145        if self.owner_write_fd is not None:
1146            os.close(self.owner_write_fd)
1147            self.owner_write_fd = None
1148        if self.owner_write is not None:
1149            try:
1150                self.owner_write.close()
1151            except OSError:
1152                pass
1153            self.owner_write = None
1154
1155    def _kill_child_tree(self) -> None:
1156        """The deadline kill of the server this host started, and everything it started. Only our own child: POSIX
1157        signals its process group, Windows ends the job the child was put in (taskkill of our own child's tree if
1158        the job could not be made)."""
1159        child = self.child
1160        if child is None:
1161            return
1162        if WINDOWS:
1163            from serve import winjob
1164            if not winjob.terminate():
1165                subprocess.run(["taskkill", "/T", "/F", "/PID", str(child.pid)], capture_output=True)
1166            try:
1167                child.kill()
1168            except OSError:
1169                pass
1170        else:
1171            os.killpg(child.pid, signal.SIGKILL)
1172
1173    def _restart(self, startup_wait: float, expected_profile_revision: str | None = None,
1174                 allow_source_switch: bool = False,
1175                 allow_source_migration: bool = False,
1176                 expected_source_sha256: str | None = None,
1177                 expected_owner_id: str | None = None,
1178                 expected_instance_id: str | None = None) -> dict:
1179        old = self._status()
1180        if expected_owner_id is not None and old.get("owner_id") != expected_owner_id:
1181            return {"ok": False, "error": "owner_changed_after_restart_plan", "exit_code": 6}
1182        if expected_instance_id is not None and old.get("instance_id") != expected_instance_id:
1183            return {"ok": False, "error": "instance_changed_after_restart_plan", "exit_code": 6}
1184        if old["state"] != "ready":
1185            return {"ok": False, "state": old["state"], "error": "runtime_not_ready", "exit_code": 6}
1186        try:
1187            plan, new_args, source, source_bytes = self._plan()
1188        except (ProfileError, OSError):
1189            return {"ok": False, "state": "ready", "error": "new_profile_preflight_failed", "exit_code": 5}
1190        switched, migrated, source_error = self._source_change_check(
1191            source, source_bytes, allow_source_switch, allow_source_migration)
1192        if source_error:
1193            return {"ok": False, "state": "ready", "error": source_error, "exit_code": 6}
1194        if expected_source_sha256 is not None and \
1195                hashlib.sha256(source_bytes).hexdigest() != expected_source_sha256:
1196            return {"ok": False, "state": "ready", "error": "source_changed_after_preview", "exit_code": 6}
1197        if expected_profile_revision is not None and plan["profile_revision"] != expected_profile_revision:
1198            return {"ok": False, "state": "ready", "error": "profile_changed_after_preview", "exit_code": 6}
1199        current = self._status()
1200        if expected_instance_id is not None and current.get("instance_id") != expected_instance_id:
1201            return {"ok": False, "error": "instance_changed_after_restart_plan", "exit_code": 6}
1202        if current["state"] != "ready":
1203            return {"ok": False, "state": current["state"], "error": "runtime_not_ready", "exit_code": 6}
1204        old_args, old_source, old_bytes, old_revision = self.args, self.source, self.source_bytes, self.revision
1205        rollback_source = old_source
1206        rollback_args = old_args
1207        if migrated:
1208            try:
1209                rollback_source = self._snapshot_running_config()
1210                rollback_args = self._config_args(old_args, rollback_source)
1211            except (OSError, ProfileError):
1212                if rollback_source != old_source:
1213                    self._retire_snapshot(rollback_source)
1214                return {"ok": False, "state": "ready", "error": "rollback_snapshot_failed", "exit_code": 6}
1215        self.probe_timeout = startup_wait
1216        stopped = self._stop_child()
1217        if not stopped["ok"]:
1218            return {**stopped, "profile": self.name, "previous_instance_id": old.get("instance_id")}
1219        try:
1220            if source.read_bytes() != source_bytes:
1221                raise ProfileError("source changed during drain", 6)
1222            self._launch(new_args, source, source_bytes, plan["profile_revision"])
1223            result = self._wait_ready(startup_wait)
1224            if result.get("ok") and result["state"] == "ready":
1225                cleanup_ok = True
1226                if rollback_source != source:
1227                    cleanup_ok = self._retire_snapshot(rollback_source) and cleanup_ok
1228                if old_source != source:
1229                    cleanup_ok = self._retire_snapshot(old_source) and cleanup_ok
1230                return {**result, "previous_instance_id": old.get("instance_id"), "restarted": True,
1231                        "source_switched": switched, "source_migrated": migrated,
1232                        "rollback_snapshot_cleanup_pending": not cleanup_ok}
1233            if self.child is not None and self.child.poll() is None:
1234                self._stop_child()
1235        except (ProfileError, OSError):
1236            result = {"state": "failed", "error": "new_instance_launch_failed", "exit_code": 6}
1237        # The old launch needs its original bytes, even if the operator edited
1238        # the same file. A private snapshot is used only for explicit migration.
1239        try:
1240            old_source_unchanged = rollback_source.read_bytes() == old_bytes
1241        except OSError:
1242            old_source_unchanged = False
1243        if old_source_unchanged:
1244            try:
1245                self._launch(rollback_args, rollback_source, old_bytes, old_revision)
1246                rollback = self._wait_ready(startup_wait)
1247            except (OSError, ProfileError):
1248                rollback = {"state": "failed"}
1249            if rollback.get("ok") and rollback.get("state") == "ready":
1250                cleanup_ok = True
1251                if old_source != rollback_source:
1252                    cleanup_ok = self._retire_snapshot(old_source)
1253                return {"ok": False, "state": "ready", "error": result.get("error", "new_instance_failed"),
1254                        "exit_code": 6, "rolled_back": True,
1255                        "rollback_snapshot_cleanup_pending": not cleanup_ok,
1256                        "rollback_source_config": str(rollback_source),
1257                        "instance_id": rollback.get("instance_id"),
1258                        "previous_instance_id": old.get("instance_id")}
1259        return {"ok": False, "state": "failed", "error": result.get("error", "restart_failed"),
1260                "exit_code": 6, "rolled_back": False}
1261
1262    def _plan_restart(self, allow_source_switch: bool = False,
1263                      allow_source_migration: bool = False) -> dict:
1264        current = self._status()
1265        if current["state"] != "ready":
1266            return {"ok": False, "state": current["state"], "error": "runtime_not_ready", "exit_code": 6}
1267        try:
1268            plan, candidate_args, source, source_bytes = self._plan()
1269        except (ProfileError, OSError):
1270            return {"ok": False, "state": "ready", "error": "new_profile_preflight_failed", "exit_code": 5}
1271        switched, migrated, source_error = self._source_change_check(
1272            source, source_bytes, allow_source_switch, allow_source_migration)
1273        if source_error:
1274            return {"ok": False, "state": "ready", "error": source_error, "exit_code": 6,
1275                    "source_switch": switched, "source_migration": migrated,
1276                    "requires_allow_source_switch": switched and not allow_source_switch,
1277                    "requires_allow_source_migration": migrated and not allow_source_migration}
1278        from strata_cli.cli import _redact_argv
1279        return {"ok": True, "state": "ready", "profile": self.name,
1280                "current_owner_id": current["owner_id"],
1281                "current_instance_id": current["instance_id"],
1282                "current_profile_revision": self.revision,
1283                "candidate_profile_revision": plan["profile_revision"],
1284                "current_source_config": str(self.source), "candidate_source_config": str(source),
1285                "current_source_sha256": hashlib.sha256(self.source_bytes).hexdigest(),
1286                "candidate_source_sha256": hashlib.sha256(source_bytes).hexdigest(),
1287                "source_switch": switched, "source_migration": migrated,
1288                "rollback_snapshot_required": migrated,
1289                "current_server_argv": _redact_argv(self.args),
1290                "candidate_server_argv": _redact_argv(candidate_args),
1291                "changed": switched or migrated or self.args != candidate_args or
1292                           self.revision != plan["profile_revision"],
1293                "shutdown_timeout": self.shutdown_timeout,
1294                "would_drain": False, "would_start": False}
1295
1296    def _handle(self, request: dict) -> dict:
1297        if not secrets.compare_digest(str(request.get("token", "")), self.token):
1298            return {"ok": False, "error": "unauthorized", "exit_code": 4}
1299        command = request.get("command")
1300        if command == "status":
1301            return self._status()
1302        if command == "verify":
1303            timeout, force_load = request.get("wait", 300), request.get("load", False)
1304            if type(timeout) not in (int, float) or not 1 <= timeout <= 600 or type(force_load) is not bool:
1305                return {"ok": False, "error": "invalid_verification_options", "exit_code": 2}
1306            owner = request.get("expected_owner_id")
1307            instance = request.get("expected_instance_id")
1308            for label, identity in (("owner", owner), ("instance", instance)):
1309                if identity is not None and (not isinstance(identity, str) or
1310                                             not re.fullmatch(r"[0-9a-f]{32}", identity)):
1311                    return {"ok": False, "error": f"invalid_expected_{label}_id", "exit_code": 2}
1312            if (owner is None) != (instance is None):
1313                return {"ok": False, "error": "verification_requires_both_identities", "exit_code": 2}
1314            current = self._status()
1315            if owner is not None and owner != self.owner_id:
1316                return {"ok": False, "error": "owner_changed_after_verify_plan", "exit_code": 6}
1317            if instance is not None and current.get("instance_id") != instance:
1318                return {"ok": False, "error": "instance_changed_after_verify_plan", "exit_code": 6}
1319            if current["state"] != "ready" or self.ready_path is None or self.child is None:
1320                return {"ok": False, "state": current["state"], "error": "runtime_not_ready", "exit_code": 6}
1321            try:
1322                ready = json.loads(self.ready_path.read_text(encoding="utf-8"))
1323                if not _ready_pid_is_child(ready.get("pid"), self.child.pid) or ready.get("instance_id") != current["instance_id"]:
1324                    raise readiness.ReadinessError("probe_instance_mismatch")
1325                host = self.args[self.args.index("--host") + 1]
1326                result = readiness.verify(ready, self.source_bytes, expected_host=host,
1327                                          expected_instance=current["instance_id"],
1328                                          expected_attestation=self.expected_attestation, timeout=timeout,
1329                                          force_load=force_load)
1330            except readiness.ReadinessError as exc:
1331                return {"ok": False, "state": current["state"], "instance_id": current["instance_id"],
1332                        "error": str(exc), "exit_code": 6}
1333            except (OSError, ValueError):
1334                return {"ok": False, "state": current["state"], "instance_id": current["instance_id"],
1335                        "error": "probe_invalid_ready_file", "exit_code": 6}
1336            if self.probe_key == (self.child.pid, current["instance_id"]):
1337                self.probe_result = result
1338            return {**self._status(), "verified_now": True}
1339        if command == "stop":
1340            owner = request.get("expected_owner_id")
1341            instance = request.get("expected_instance_id")
1342            if owner is not None and (not isinstance(owner, str) or
1343                    not re.fullmatch(r"[0-9a-f]{32}", owner)):
1344                return {"ok": False, "error": "invalid_expected_owner_id", "exit_code": 2}
1345            if instance is not None and (not isinstance(instance, str) or
1346                    not re.fullmatch(r"[0-9a-f]{32}", instance)):
1347                return {"ok": False, "error": "invalid_expected_instance_id", "exit_code": 2}
1348            if owner is not None and owner != self.owner_id:
1349                return {"ok": False, "error": "owner_changed_after_stop_plan", "exit_code": 6}
1350            if instance is not None and self._status().get("instance_id") != instance:
1351                return {"ok": False, "error": "instance_changed_after_stop_plan", "exit_code": 6}
1352            self.running = False                   # (a launch that has not begun will not)
1353            with self._launch_lock:
1354                result = self._stop_child()
1355            return {**result, "profile": self.name}
1356        if command == "restart":
1357            startup_wait = request.get("startup_wait", 300)
1358            if type(startup_wait) not in (int, float) or not 1 <= startup_wait <= MAX_START_WAIT:
1359                return {"ok": False, "error": "invalid_startup_wait", "exit_code": 2}
1360            revision = request.get("expected_profile_revision")
1361            if revision is not None and (not isinstance(revision, str) or
1362                                         not re.fullmatch(r"[0-9a-f]{16}", revision)):
1363                return {"ok": False, "error": "invalid_profile_revision", "exit_code": 2}
1364            allow_source_switch = request.get("allow_source_switch", False)
1365            if type(allow_source_switch) is not bool:
1366                return {"ok": False, "error": "invalid_source_switch_option", "exit_code": 2}
1367            allow_source_migration = request.get("allow_source_migration", False)
1368            if type(allow_source_migration) is not bool:
1369                return {"ok": False, "error": "invalid_source_migration_option", "exit_code": 2}
1370            expected_source_sha256 = request.get("expected_source_sha256")
1371            if (allow_source_switch or allow_source_migration) and \
1372                    (not isinstance(expected_source_sha256, str) or
1373                     not re.fullmatch(r"[0-9a-f]{64}", expected_source_sha256)):
1374                return {"ok": False, "error": "source_change_needs_candidate_digest", "exit_code": 2}
1375            if expected_source_sha256 is not None and (not isinstance(expected_source_sha256, str) or
1376                                                       not re.fullmatch(r"[0-9a-f]{64}", expected_source_sha256)):
1377                return {"ok": False, "error": "invalid_source_digest", "exit_code": 2}
1378            expected_owner_id = request.get("expected_owner_id")
1379            expected_instance_id = request.get("expected_instance_id")
1380            if expected_owner_id is not None and (not isinstance(expected_owner_id, str) or
1381                                                  not re.fullmatch(r"[0-9a-f]{32}", expected_owner_id)):
1382                return {"ok": False, "error": "invalid_expected_owner_id", "exit_code": 2}
1383            if expected_instance_id is not None and (not isinstance(expected_instance_id, str) or
1384                                                     not re.fullmatch(r"[0-9a-f]{32}", expected_instance_id)):
1385                return {"ok": False, "error": "invalid_expected_instance_id", "exit_code": 2}
1386            return self._restart(startup_wait, revision, allow_source_switch,
1387                                 allow_source_migration, expected_source_sha256,
1388                                 expected_owner_id, expected_instance_id)
1389        if command == "plan_restart":
1390            allow_source_switch = request.get("allow_source_switch", False)
1391            allow_source_migration = request.get("allow_source_migration", False)
1392            if type(allow_source_switch) is not bool or type(allow_source_migration) is not bool:
1393                return {"ok": False, "error": "invalid_source_change_options", "exit_code": 2}
1394            return self._plan_restart(allow_source_switch, allow_source_migration)
1395        return {"ok": False, "error": "unsupported_runtime_command", "exit_code": 2}
1396
1397    def _say(self, line: str) -> None:
1398        """One line to the host log (the host's stderr is that file), so a host that ends says why."""
1399        try:
1400            print(f"{time.strftime('%Y-%m-%dT%H:%M:%S')} [strata runtime] profile {self.name}: {line}", file=sys.stderr, flush=True)
1401        except (OSError, ValueError):
1402            pass
1403
1404    def _husk(self) -> bool:
1405        """Whether this host has nothing left to supervise: its server ended, or the start failed before one existed."""
1406        child = self.child
1407        if child is not None:
1408            return child.poll() is not None
1409        return not self.starting and self.last_error is not None
1410
1411    def _die_with_gone(self) -> bool:
1412        """Whether the process this instance lives for (the desktop app's host) is gone. A look that cannot read the process (the macOS
1413        `ps` that timed out, a handle that was refused) is not an answer: the engine used to be stopped on it, cleanly and without a word,
1414        hours into an idle session (#4973). A different start time is a later process with that number: gone at once. Nothing found is
1415        confirmed against a plain liveness check, and has to repeat DIE_WITH_MISSES times."""
1416        pid, token = self.die_with
1417        found = procs.start_token(pid)
1418        if found == token:
1419            self.die_misses = 0
1420            return False
1421        if found is not None:
1422            return True
1423        if _pid_exists(pid):
1424            self.die_misses = 0
1425            return False
1426        self.die_misses += 1
1427        return self.die_misses >= DIE_WITH_MISSES
1428
1429    def _startup(self) -> None:
1430        """The first launch, in a thread. Planning imports the server and asks the machine about its cards, which takes seconds on a slow
1431        disk or a PC with a virus scanner; with it in the accept loop's way a status question went unanswered and `runtime start` gave up
1432        with "runtime operation wait expired" while the engine loaded fine (#5177). Now the owner answers (phase "preparing", then
1433        "launching", then the server's own "loading" and "verifying_generation") the whole time."""
1434        try:
1435            self.phase = "preparing"
1436            plan, args, source, source_bytes = self._plan()
1437            if (self.expected_profile_revision is not None and
1438                    plan["profile_revision"] != self.expected_profile_revision):
1439                raise ProfileError("profile_changed_after_start_plan", 6)
1440            if (self.expected_source_sha256 is not None and
1441                    hashlib.sha256(source_bytes).hexdigest() != self.expected_source_sha256):
1442                raise ProfileError("source_changed_after_start_plan", 6)
1443            with self._launch_lock:
1444                if not self.running:               # a stop (or a signal) came while the plan was made: nothing is started
1445                    return
1446                self.phase = "launching"
1447                self._launch(args, source, source_bytes, plan["profile_revision"])
1448        except (ProfileError, OSError) as exc:
1449            self.last_error = str(exc) if isinstance(exc, ProfileError) else type(exc).__name__
1450        except BaseException as exc:               # noqa: BLE001 - a thread that dies silently would leave "preparing" forever
1451            self.last_error = type(exc).__name__
1452        finally:
1453            self.starting = False
1454            self.phase = None
1455
1456    def serve(self) -> int:
1457        activity_lease = acquire_activity_lease(shared=True)
1458        listener = owner_transport.Listener(self.socket_path, timeout=1.0)
1459        try:
1460            # `bind()` returns the address the client must use, which differs from the requested one
1461            # on Windows (the OS assigns the port).
1462            bound_address = listener.bind()
1463            def shutdown(signum, frame):
1464                self.running = False
1465            signal.signal(signal.SIGTERM, shutdown)
1466            signal.signal(signal.SIGINT, shutdown)
1467            if hasattr(signal, "SIGBREAK"):      # Windows: the signal a console Ctrl+Break / a closing console sends
1468                signal.signal(signal.SIGBREAK, shutdown)
1469            self._mark_child("no_child")           # (#4250) before the state exists: a host lost from here on, before it starts a server, is recoverable
1470            self.state_fd = _write_new(self.state_path, (json.dumps({"schema_version": 1, "profile": self.name,
1471                                                                     "socket": bound_address, "token": self.token,
1472                                                                     "host_pid": os.getpid()}) + "\n").encode())
1473            self.starting = True
1474            threading.Thread(target=self._startup, name="strata-owner-startup", daemon=True).start()
1475            while self.running:
1476                if self.die_with is not None and self._die_with_gone():
1477                    self._say(f"the process this instance lives for (pid {self.die_with[0]}) is gone: stopping the server and leaving")
1478                    self.running = False         # the process this instance lives for is gone: stop (drained) and leave
1479                    break
1480                if self.probe_result is not None and "error" in self.probe_result and \
1481                        self.child is not None and self.child.poll() is None:
1482                    self._stop_child()
1483                if self._husk():
1484                    # The server this host started has ended (or never started) and nothing is serving: a host that stays holds the profile's
1485                    # state and lease, and every later start refuses it until a person kills a pid that status does not point at (#4574 #4824).
1486                    # Status says "failed" and why for CHILD_EXIT_GRACE seconds, long enough for a client waiting for it; then the host leaves.
1487                    now = time.monotonic()
1488                    if self.gone_at is None:
1489                        self.gone_at = now
1490                        child = self.child
1491                        self._say("the server ended on its own" + (f" (exit code {child.returncode})" if child is not None else
1492                                                                  f" ({self.last_error})") + f"; this host leaves in {CHILD_EXIT_GRACE:.0f} s")
1493                    elif now - self.gone_at >= CHILD_EXIT_GRACE:
1494                        self.exit_status = 6
1495                        self.running = False
1496                        break
1497                else:
1498                    self.gone_at = None
1499                try:
1500                    connection = listener.accept()
1501                except socket.timeout:
1502                    continue
1503                if connection is None:
1504                    # A quiet timeout: the owner loops so it can still service its child.
1505                    continue
1506                with connection:
1507                    connection.settimeout(5)
1508                    raw = bytearray()
1509                    try:
1510                        while len(raw) <= MAX_MESSAGE and b"\n" not in raw:
1511                            chunk = connection.recv(4096)
1512                            if not chunk:
1513                                break
1514                            raw.extend(chunk)
1515                        if len(raw) > MAX_MESSAGE:
1516                            raise ValueError("message too large")
1517                        request = json.loads(raw.split(b"\n", 1)[0])
1518                        if not isinstance(request, dict):
1519                            raise ValueError("request must be an object")
1520                        response = self._handle(request)
1521                    except (OSError, ValueError):
1522                        response = {"ok": False, "error": "invalid_control_request", "exit_code": 2}
1523                    try:
1524                        connection.sendall((json.dumps(response, ensure_ascii=False) + "\n").encode())
1525                    except OSError:
1526                        pass
1527        finally:
1528            self.running = False
1529            with self._launch_lock:                # no launch can begin after this, and one that is under way has finished
1530                if self.child is not None and self.child.poll() is None:
1531                    self._stop_child()
1532                self._close_owner_pipe()
1533            listener.close()
1534            if WINDOWS and self.state_fd is not None:
1535                # an open file cannot be deleted on Windows: the lease ends just before the state file does
1536                _unlock_file(self.state_fd)
1537                os.close(self.state_fd)
1538                self.state_fd = None
1539            try:
1540                current = _read_state(self.name)
1541                if current and current.get("token") == self.token:
1542                    self.state_path.unlink(missing_ok=True)
1543            except ProfileError:
1544                pass
1545            if not owner_transport.WINDOWS:
1546                # POSIX leaves a socket file behind; Windows leaves nothing (the listener's close
1547                # releases the port). `Listener.close()` already unlinks the POSIX path, so this is
1548                # a second, defensive attempt for the path the caller recorded.
1549                Path(self.socket_path).unlink(missing_ok=True)
1550            if self.ready_path is not None:
1551                self.ready_path.unlink(missing_ok=True)
1552            _child_marker(self.name, self.token).unlink(missing_ok=True)
1553            for snapshot in tuple(self.rollback_snapshots):
1554                self._retire_snapshot(snapshot)
1555            if self.state_fd is not None:
1556                os.close(self.state_fd)
1557            _unlock_file(activity_lease)
1558            os.close(activity_lease)
1559        return self.exit_status
1560
1561
1562def main(argv: list[str] | None = None) -> int:
1563    quiet_crash_env()                                   # the host's children inherit it (strata_control/childenv.py)
1564    parser = argparse.ArgumentParser(prog="strata-runtime-host")
1565    parser.add_argument("--host", required=True)
1566    parser.add_argument("--shutdown-timeout", type=float, default=30)
1567    parser.add_argument("--startup-wait", type=float, default=300)
1568    parser.add_argument("--expected-profile-revision")
1569    parser.add_argument("--expected-source-sha256")
1570    parser.add_argument("--die-with-pid", type=int)
1571    parser.add_argument("--die-with-token")
1572    args = parser.parse_args(argv)
1573    if not 0 <= args.shutdown_timeout <= 300 or not 1 <= args.startup_wait <= MAX_START_WAIT:
1574        parser.error("shutdown timeout must be 0..300")
1575    if args.expected_profile_revision is not None and not re.fullmatch(r"[0-9a-f]{16}", args.expected_profile_revision):
1576        parser.error("expected profile revision must be 16 lowercase hex characters")
1577    if args.expected_source_sha256 is not None and not re.fullmatch(r"[0-9a-f]{64}", args.expected_source_sha256):
1578        parser.error("expected source digest must be 64 lowercase hex characters")
1579    try:
1580        die_with = (args.die_with_pid, args.die_with_token) if args.die_with_pid and args.die_with_token else None
1581        return Host(args.host, args.shutdown_timeout, args.startup_wait,
1582                    args.expected_profile_revision, args.expected_source_sha256, die_with).serve()
1583    except (ProfileError, OSError) as exc:
1584        print(f"[strata runtime] host failed: {type(exc).__name__}: {exc}", file=sys.stderr)
1585        return 6
1586
1587
1588if __name__ == "__main__":
1589    raise SystemExit(main())