okami.mom/strata

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

Niko1221Merge f-022-refusals: environmental refusals repair or warn instead of blocking (audit items 1-4, 6, 8-10, 12-15)bcf88b738

main
21.5 KiB439 linesraw
1"""Typed, owner-editable local operation recipes for saved serving profiles.
2
3Recipes contain no executable command text. Each kind routes to an existing
4Strata operation. This is a source-run store; Desktop must later use the same
5schema and operation authority rather than add a separate implementation.
6"""
7
8from __future__ import annotations
9
10from strata_control.private_files import private_mkdir as _private_mkdir
11import hashlib
12import json
13import os
14import re
15import shlex
16import stat
17import subprocess
18import sys
19import tempfile
20import uuid
21from pathlib import Path
22
23from strata_control import profiles
24from strata_control.profiles import ProfileError
25from strata_control import posix_owner
26
27
28KINDS = frozenset({"runtime.restart", "engine.calibrate.measure", "components.verify"})
29MAX_BYTES = 64 * 1024
30
31
32def _identity(profile: str, name: str) -> tuple[str, str]:
33    if not profiles.PROFILE_ID.fullmatch(profile) or not profiles.PROFILE_ID.fullmatch(name):
34        raise ProfileError("recipe profile and name must use lowercase letters, digits, _ or -")
35    return profile, name
36
37
38def _directory(profile: str, *, create: bool = False) -> Path:
39    profiles.load(profile)
40    base = profiles.profile_dir()
41    directory = base / ".ops" / profile
42    for path in (base, directory.parent):
43        if not path.exists() and not path.is_symlink():
44            continue
45        details = path.lstat()
46        if not stat.S_ISDIR(details.st_mode):
47            raise ProfileError("recipe directory must not be a symlink", 5)
48        if os.name == "posix" and (posix_owner.owner_only_wrong(path, details)):
49            raise ProfileError(posix_owner.owner_only_text("recipe directory must be owner-only (mode 0700)", path), 5)
50    if create:
51        _private_mkdir(directory.parent, exist_ok=True)
52        _private_mkdir(directory, exist_ok=True)
53    if directory.exists() or directory.is_symlink():
54        details = directory.lstat()
55        if not stat.S_ISDIR(details.st_mode):
56            raise ProfileError("recipe directory must not be a symlink", 5)
57        if os.name == "posix" and (posix_owner.owner_only_wrong(directory, details)):
58            raise ProfileError(posix_owner.owner_only_text("recipe directory must be owner-only (mode 0700)", directory), 5)
59    return directory
60
61
62def _path(profile: str, name: str, *, create: bool = False) -> Path:
63    _identity(profile, name)
64    return _directory(profile, create=create) / f"{name}.json"
65
66
67def _lock_name(profile: str) -> str:
68    return "ops" + hashlib.sha256(profile.encode("utf-8")).hexdigest()[:24]
69
70
71def _history_dir(profile: str, name: str, *, create: bool = False) -> Path:
72    root = _path(profile, name).parent / ".history"
73    directory = root / name
74    for path in (root, directory):
75        if path.is_symlink():
76            raise ProfileError("recipe history directory must not be a symlink", 5)
77    if create:
78        _private_mkdir(root, exist_ok=True)
79        _private_mkdir(directory, exist_ok=True)
80    for path in (root, directory):
81        if path.exists():
82            details = path.lstat()
83            if not stat.S_ISDIR(details.st_mode) or (os.name == "posix" and
84                    (posix_owner.owner_only_wrong(path, details))):
85                raise ProfileError(posix_owner.owner_only_text("recipe history directory must be owner-only", path), 5)
86    return directory
87
88
89def _bytes(recipe: dict) -> bytes:
90    return (json.dumps(recipe, sort_keys=True, indent=2, ensure_ascii=False, allow_nan=False) + "\n").encode("utf-8")
91
92
93def _validate(recipe: object, profile: str, name: str) -> dict:
94    if not isinstance(recipe, dict) or set(recipe) != {"schema_version", "profile", "id", "kind", "params"}:
95        raise ProfileError("recipe needs schema_version, profile, id, kind and params")
96    if type(recipe["schema_version"]) is not int or recipe["schema_version"] != 1:
97        raise ProfileError("unsupported recipe schema version")
98    if recipe["profile"] != profile or recipe["id"] != name:
99        raise ProfileError("recipe profile or ID does not match its file")
100    kind, params = recipe["kind"], recipe["params"]
101    if not isinstance(kind, str) or kind not in KINDS or not isinstance(params, dict):
102        raise ProfileError("recipe kind or parameters are unsupported")
103    if kind == "runtime.restart":
104        if set(params) != {"startup_wait_s"} or type(params["startup_wait_s"]) is not int or \
105                not 1 <= params["startup_wait_s"] <= 600:
106            raise ProfileError("restart recipe needs startup_wait_s in 1..600")
107    elif kind == "engine.calibrate.measure":
108        directory = params.get("report_dir")
109        if set(params) != {"report_dir"} or not isinstance(directory, str) or not directory or "\x00" in directory or \
110                not Path(directory).is_absolute():
111            raise ProfileError("calibration recipe needs an absolute report_dir")
112    elif set(params) - {"live"} or ("live" in params and type(params["live"]) is not bool):
113        raise ProfileError("component verification recipe accepts only live=true|false")
114    return recipe
115
116
117def _default(profile: str, name: str, kind: str) -> dict:
118    if not isinstance(kind, str) or kind not in KINDS:
119        raise ProfileError("recipe kind is unsupported")
120    if kind == "runtime.restart":
121        params = {"startup_wait_s": 300}
122    elif kind == "engine.calibrate.measure":
123        params = {"report_dir": str(profiles.profile_dir().resolve() / ".reports")}
124    else:
125        params = {}
126    return _validate({"schema_version": 1, "profile": profile, "id": name,
127                      "kind": kind, "params": params}, profile, name)
128
129
130def create(profile: str, name: str, kind: str) -> tuple[dict, str]:
131    profile, name = _identity(profile, name)
132    value = _default(profile, name, kind)
133    path = _path(profile, name, create=True)
134    with profiles._lock(_lock_name(profile)):
135        flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
136        if hasattr(os, "O_NOFOLLOW"):
137            flags |= os.O_NOFOLLOW
138        try:
139            descriptor = os.open(path, flags, 0o600)
140        except FileExistsError:
141            raise ProfileError(f"recipe {name!r} already exists") from None
142        try:
143            with os.fdopen(descriptor, "wb") as stream:
144                stream.write(_bytes(value))
145                stream.flush()
146                os.fsync(stream.fileno())
147        except BaseException:
148            path.unlink(missing_ok=True)
149            raise
150    return load(profile, name)
151
152
153def initialize(profile: str) -> list[str]:
154    profiles.load(profile)
155    defaults = (("restart", "runtime.restart"),
156                ("calibrate", "engine.calibrate.measure"),
157                ("check", "components.verify"))
158    for name, kind in defaults:
159        path = _path(profile, name)
160        if path.exists() or path.is_symlink():
161            saved, _ = load(profile, name)
162            if saved["kind"] != kind:
163                raise ProfileError(f"recipe {name!r} exists with a different kind; choose another name")
164    created = []
165    for name, kind in defaults:
166        path = _path(profile, name)
167        if not path.exists() and not path.is_symlink():
168            try:
169                create(profile, name, kind)
170                created.append(name)
171            except ProfileError as exc:
172                if "already exists" not in str(exc):
173                    raise
174        saved, _ = load(profile, name)
175        if saved["kind"] != kind:
176            raise ProfileError(f"recipe {name!r} exists with a different kind; choose another name")
177    return created
178
179
180def load(profile: str, name: str) -> tuple[dict, str]:
181    path = _path(profile, name)
182    try:
183        details = path.lstat()
184        if not stat.S_ISREG(details.st_mode) or details.st_size > MAX_BYTES:
185            raise ProfileError("recipe must be a regular file under 64 KiB", 5)
186        if os.name == "posix" and (posix_owner.owner_only_wrong(path, details)):
187            raise ProfileError(posix_owner.owner_only_text("recipe file must be owner-only (mode 0600)", path), 5)
188        data = path.read_bytes()
189        value = json.loads(data.decode("utf-8-sig"))
190    except FileNotFoundError:
191        raise ProfileError(f"recipe {name!r} is missing; use strata ops init --profile {profile}", 5) from None
192    except (OSError, UnicodeError, ValueError) as exc:
193        if isinstance(exc, ProfileError):
194            raise
195        raise ProfileError(f"cannot read recipe ({type(exc).__name__})", 5) from None
196    return _validate(value, profile, name), profiles._revision(data)
197
198
199def list_recipes(profile: str) -> list[dict]:
200    directory = _directory(profile)
201    if not directory.exists():
202        return []
203    items = []
204    for path in sorted(directory.glob("*.json")):
205        if profiles.PROFILE_ID.fullmatch(path.stem):
206            try:
207                recipe, revision = load(profile, path.stem)
208                items.append({"id": path.stem, "kind": recipe["kind"], "revision": revision})
209            except ProfileError as exc:
210                items.append({"id": path.stem, "error": str(exc)})
211    return items
212
213
214def save(profile: str, name: str, proposed: dict, expected_revision: str) -> tuple[dict, str]:
215    _validate(proposed, profile, name)
216    with profiles._lock(_lock_name(profile)):
217        current, revision = load(profile, name)
218        if revision != expected_revision:
219            raise ProfileError("recipe changed during edit; reload it before saving", 6)
220        if current == proposed:
221            return current, revision
222        path = _path(profile, name)
223        old = path.read_bytes()
224        if profiles._revision(old) != revision:
225            raise ProfileError("recipe changed during edit; reload it before saving", 6)
226        history_dir = _history_dir(profile, name, create=True)
227        backup = history_dir / f"{revision}.json"
228        if backup.exists() or backup.is_symlink():
229            details = backup.lstat()
230            if not stat.S_ISREG(details.st_mode) or (os.name == "posix" and
231                    (posix_owner.owner_only_wrong(backup, details))) or \
232                    backup.read_bytes() != old:
233                raise ProfileError("recipe history conflicts with the saved revision", 5)
234        else:
235            profiles._atomic(backup, old)
236        profiles._atomic(path, _bytes(proposed))
237    return load(profile, name)
238
239
240def history(profile: str, name: str) -> list[dict]:
241    _, current = load(profile, name)
242    directory = _history_dir(profile, name)
243    entries = []
244    if directory.exists():
245        for path in directory.glob("*.json"):
246            if re.fullmatch(r"[0-9a-f]{16}", path.stem) and path.is_file() and not path.is_symlink():
247                entries.append({"revision": path.stem, "saved_at": path.stat().st_mtime})
248    return [{"revision": current, "current": True},
249            *sorted((item for item in entries if item["revision"] != current),
250                    key=lambda item: item["saved_at"], reverse=True)]
251
252
253def rollback(profile: str, name: str, target_revision: str) -> tuple[dict, str, str]:
254    if not re.fullmatch(r"[0-9a-f]{16}", target_revision):
255        raise ProfileError("rollback target must be a full 16-character revision")
256    _, current_revision = load(profile, name)
257    path = _history_dir(profile, name) / f"{target_revision}.json"
258    try:
259        details = path.lstat()
260        if not stat.S_ISREG(details.st_mode) or details.st_size > MAX_BYTES:
261            raise ProfileError("recipe history must be a regular file under 64 KiB", 5)
262        if os.name == "posix" and (posix_owner.owner_only_wrong(path, details)):
263            raise ProfileError(posix_owner.owner_only_text("recipe history file must be owner-only", path), 5)
264        data = path.read_bytes()
265        if profiles._revision(data) != target_revision:
266            raise ProfileError("recipe history content does not match its revision", 5)
267        proposed = _validate(json.loads(data.decode("utf-8")), profile, name)
268    except FileNotFoundError:
269        raise ProfileError(f"recipe revision {target_revision} was not found", 5) from None
270    except (OSError, UnicodeError, ValueError) as exc:
271        if isinstance(exc, ProfileError):
272            raise
273        raise ProfileError(f"cannot read recipe history ({type(exc).__name__})", 5) from None
274    saved, new_revision = save(profile, name, proposed, current_revision)
275    return saved, current_revision, new_revision
276
277
278def propose_value(profile: str, name: str, assignment: str) -> tuple[dict, str]:
279    current, revision = load(profile, name)
280    key, separator, raw = assignment.partition("=")
281    if not separator or not raw:
282        raise ProfileError("expected a typed recipe parameter as KEY=VALUE")
283    kind = current["kind"]
284    if kind == "runtime.restart" and key == "startup_wait_s":
285        try:
286            value: object = int(raw)
287        except ValueError:
288            raise ProfileError("startup_wait_s must be a whole number") from None
289    elif kind == "engine.calibrate.measure" and key == "report_dir":
290        value = raw
291    elif kind == "components.verify" and key == "live" and raw in ("true", "false"):
292        value = raw == "true"
293    else:
294        raise ProfileError("parameter is not supported by this recipe kind")
295    proposed = {**current, "params": {**current["params"], key: value}}
296    return _validate(proposed, profile, name), revision
297
298
299def edit(profile: str, name: str) -> tuple[dict, str, str]:
300    current, revision = load(profile, name)
301    editor = os.environ.get("VISUAL") or os.environ.get("EDITOR")
302    if not editor:
303        raise ProfileError("set VISUAL or EDITOR, or use strata ops set")
304    command = shlex.split(editor, posix=os.name != "nt")
305    if not command:
306        raise ProfileError("VISUAL or EDITOR is empty")
307    descriptor, temporary = tempfile.mkstemp(prefix=f".{name}-edit-", suffix=".json", dir=_directory(profile))
308    keep = False
309    try:
310        with os.fdopen(descriptor, "wb") as stream:
311            stream.write(_bytes(current))
312        result = subprocess.run([*command, temporary], check=False)
313        if result.returncode:
314            keep = True
315            raise ProfileError(f"editor exited with status {result.returncode}; draft kept at {temporary}", 6)
316        try:
317            proposed = json.loads(Path(temporary).read_text(encoding="utf-8-sig"))
318            saved, new_revision = save(profile, name, proposed, revision)
319        except (OSError, ValueError) as exc:
320            keep = True
321            code = exc.exit_code if isinstance(exc, ProfileError) else 2
322            raise ProfileError(f"invalid recipe edit ({exc}); draft kept at {temporary}", code) from None
323        return saved, revision, new_revision
324    finally:
325        if not keep:
326            Path(temporary).unlink(missing_ok=True)
327
328
329def plan(profile: str, name: str) -> dict:
330    recipe, revision = load(profile, name)
331    kind = recipe["kind"]
332    if kind == "runtime.restart":
333        from strata_control import runtime
334        preflight = runtime.plan_restart(profile)
335        profile_revision = preflight.get("candidate_profile_revision")
336        operation = {"ok": preflight["ok"], "exit_code": preflight.get("exit_code", 6),
337                     "preflight": preflight, "startup_wait_s": recipe["params"]["startup_wait_s"],
338                     "run_effects": {"drain_current_instance": True, "start_new_instance": True,
339                                     "rollback_previous_launch_on_activation_failure": True}}
340    elif kind == "engine.calibrate.measure":
341        from strata_control import calibration
342        preflight = calibration.preview(profile)
343        profile_revision = preflight["profile_revision"]
344        operation = {"ok": preflight["component_preflight"]["ok"], "exit_code": 5,
345                     "preflight": preflight, "report_dir": recipe["params"]["report_dir"],
346                     "run_effects": {"start_engine_for_decode_sweep": True, "write_new_report": True,
347                                     "change_run_config": False, "requires_exclusive_acknowledgement": True}}
348    else:
349        from strata_control.doctor import inspect as inspect_components
350        path, _, _ = profiles.resolve(profile)
351        live = recipe["params"].get("live", False)
352        report = inspect_components(path, profile_id=profile, live=live)
353        profile_revision = profiles.load(profile)[1]
354        operation = {"ok": report["ok"], "exit_code": 5, "preflight": report,
355                     "run_effects": {"read_components": True, "query_host_gpus": live, "write_files": False}}
356    if profile_revision is not None and profile_revision != profiles.load(profile)[1]:
357        raise ProfileError("profile changed during recipe preview; retry", 6)
358    return {"profile": profile, "profile_revision": profile_revision,
359            "recipe": name, "recipe_revision": revision,
360            "kind": kind, "operation": operation, "would_execute": False}
361
362
363def run(profile: str, name: str, *, exclusive_ack: bool = False,
364        expected_revision: str | None = None,
365        expected_profile_revision: str | None = None,
366        expected_owner_id: str | None = None,
367        expected_instance_id: str | None = None,
368        expected_source_sha256: str | None = None) -> dict:
369    recipe, revision = load(profile, name)
370    if expected_revision is not None and revision != expected_revision:
371        raise ProfileError("recipe changed after preview; plan it again before running", 6)
372    if expected_profile_revision is not None and profiles.load(profile)[1] != expected_profile_revision:
373        raise ProfileError("profile changed after preview; plan it again before running", 6)
374    kind = recipe["kind"]
375    if kind == "runtime.restart":
376        from strata_control import runtime
377        if (expected_owner_id is None) != (expected_instance_id is None):
378            raise ProfileError("restart recipe needs both reviewed owner and instance IDs")
379        if any(value is not None for value in (expected_owner_id, expected_instance_id,
380                                               expected_source_sha256)):
381            preflight = runtime.plan_restart(profile)
382            if not preflight["ok"]:
383                raise ProfileError(preflight.get("error", "restart preflight failed"),
384                                   preflight.get("exit_code", 6))
385            if expected_owner_id is not None and preflight["current_owner_id"] != expected_owner_id:
386                raise ProfileError("owner_changed_after_restart_plan", 6)
387            if expected_instance_id is not None and preflight["current_instance_id"] != expected_instance_id:
388                raise ProfileError("instance_changed_after_restart_plan", 6)
389            if (expected_source_sha256 is not None and
390                    preflight["candidate_source_sha256"] != expected_source_sha256):
391                raise ProfileError("source_changed_after_preview", 6)
392    elif any(value is not None for value in (expected_owner_id, expected_instance_id,
393                                             expected_source_sha256)):
394        raise ProfileError("owner, instance and source preconditions require a restart recipe")
395    if kind == "engine.calibrate.measure" and not exclusive_ack:
396        raise ProfileError("calibration recipe requires --exclusive for each run")
397    from strata_control import journal
398    profile_revision = profiles.load(profile)[1]
399    record = journal.begin(profile, name, kind, revision, profile_revision,
400                           intent=dict(recipe["params"]))
401    try:
402        if kind == "runtime.restart":
403            from strata_control import runtime
404            kwargs = {"startup_wait": recipe["params"]["startup_wait_s"]}
405            if expected_profile_revision is not None:
406                kwargs["expected_profile_revision"] = expected_profile_revision
407            if expected_owner_id is not None:
408                kwargs["expected_owner_id"] = expected_owner_id
409                kwargs["expected_instance_id"] = expected_instance_id
410            if expected_source_sha256 is not None:
411                kwargs["expected_source_sha256"] = expected_source_sha256
412            result = runtime.restart(profile, **kwargs)
413        elif kind == "engine.calibrate.measure":
414            from strata_control import calibration
415            directory = Path(recipe["params"]["report_dir"])
416            _private_mkdir(directory, exist_ok=True)
417            if not stat.S_ISDIR(directory.lstat().st_mode):
418                raise ProfileError("report_dir must be a directory, not a symlink", 5)
419            report_path = directory / f"calibration-{uuid.uuid4().hex}.json"
420            report = calibration.measure(profile, report_path, exclusive_ack=True,
421                                         say=lambda message: print(message, file=sys.stderr))
422            result = {"ok": True, "report_path": str(report_path), "report": report,
423                      "requires_review_before_apply": True}
424        else:
425            from strata_control.doctor import inspect as inspect_components
426            path, _, _ = profiles.resolve(profile)
427            report = inspect_components(path, profile_id=profile, live=recipe["params"].get("live", False))
428            result = {"ok": report["ok"], "report": report}
429    except BaseException as exc:
430        unknown = isinstance(exc, (KeyboardInterrupt, SystemExit)) or \
431            (isinstance(exc, ProfileError) and exc.exit_code == 8)
432        journal.finish(profile, record["operation_id"], "completion_unknown" if unknown else "failed",
433                       {"error_type": type(exc).__name__,
434                        "exit_code": exc.exit_code if isinstance(exc, ProfileError) else 130 if unknown else 6})
435        raise
436    journal.finish(profile, record["operation_id"], "succeeded" if result["ok"] else "failed",
437                   journal.compact_result(kind, result))
438    return {"profile": profile, "recipe": name, "recipe_revision": revision,
439            "kind": kind, "operation_id": record["operation_id"], "result": result}