okami.mom/strata

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

Niko1221Merge f-028-app-p13b8dc8fa3

main
25.8 KiB445 linesraw
1"""Bounded local records for typed recipe and direct operator runs.
2
3Records contain operation identity and compact outcomes, never credentials,
4request bodies or full calibration reports. A running record after a caller
5crash has unknown completion; it is not proof that a worker is still running.
6"""
7
8from __future__ import annotations
9
10from strata_control.private_files import private_mkdir as _private_mkdir
11import json
12import math
13import os
14import re
15import stat
16import time
17import uuid
18from pathlib import Path
19
20from strata_control import profiles, recipes
21from strata_control.profiles import ProfileError
22from strata_control import posix_owner
23
24
25MAX_RECORDS = 500
26MAX_RECORD_BYTES = 64 * 1024
27ID = re.compile(r"[0-9a-f]{32}\Z")
28TERMINAL = frozenset({"succeeded", "failed", "completion_unknown"})
29RESULT_KEYS = frozenset({"ok", "state", "instance_id", "previous_instance_id", "restarted",
30                         "source_switched", "source_migrated", "rollback_source_config",
31                         "rollback_snapshot_cleanup_pending",
32                         "rolled_back", "error", "exit_code", "report_path", "report_id",
33                         "applicable", "issue_codes", "error_type", "changed",
34                         "application_record", "setup_settings_removed", "generation_ready",
35                         "api_identity_verified", "launch_attested", "readiness_state", "verified_now",
36                         "run_id", "successful", "cancelled"})
37RECORD_KEYS = frozenset({"schema_version", "operation_id", "profile", "recipe", "kind",
38                         "recipe_revision", "profile_revision", "owner_pid", "intent",
39                         "state", "started_at", "finished_at", "cancellation_policy",
40                         "events", "result"})
41DIRECT_RECORD_KEYS = (RECORD_KEYS - {"recipe", "recipe_revision"}) | {"origin"}
42DIRECT_KINDS = frozenset({"runtime.start", "runtime.stop", "runtime.restart", "runtime.verify",
43                          "bench.run",
44                          "engine.calibrate.measure", "engine.calibrate.apply", "engine.calibrate.rollback"})
45
46
47def _directory(profile: str, *, create: bool = False) -> Path:
48    directory = recipes._directory(profile, create=create) / ".runs"
49    if create:
50        _private_mkdir(directory, exist_ok=True)
51    if directory.exists() or directory.is_symlink():
52        details = directory.lstat()
53        if not stat.S_ISDIR(details.st_mode):
54            raise ProfileError("operation journal directory must not be a symlink", 5)
55        if os.name == "posix" and (posix_owner.owner_only_wrong(directory, details)):
56            raise ProfileError(posix_owner.owner_only_text("operation journal directory must be owner-only", directory), 5)
57    return directory
58
59
60def _path(profile: str, operation_id: str, *, create: bool = False) -> Path:
61    if not ID.fullmatch(operation_id):
62        raise ProfileError("operation ID must be a 32-character hex value")
63    return _directory(profile, create=create) / f"{operation_id}.json"
64
65
66def _bytes(record: dict) -> bytes:
67    data = (json.dumps(record, sort_keys=True, indent=2, ensure_ascii=False, allow_nan=False) + "\n").encode("utf-8")
68    if len(data) > MAX_RECORD_BYTES:
69        raise ProfileError("operation journal record exceeds 64 KiB", 6)
70    return data
71
72
73def _lock_name(profile: str) -> str:
74    import hashlib
75    return "job" + hashlib.sha256(profile.encode("utf-8")).hexdigest()[:24]
76
77
78def _validate_direct_intent(kind: str, intent: object) -> dict:
79    if kind not in DIRECT_KINDS or not isinstance(intent, dict):
80        raise ProfileError("direct operation kind or intent is unsupported", 5)
81    expected = ({"bench.run": {"path", "suite", "concurrency", "repeat", "request_timeout",
82                               "condition", "if_profile_revision", "if_source_sha256",
83                               "if_owner_id", "if_instance_id"},
84                 "runtime.start": {"wait_s", "shutdown_timeout_s",
85                                    "expected_profile_revision", "expected_source_sha256"},
86                 "runtime.stop": {"wait_s", "expected_owner_id", "expected_instance_id"},
87                 "runtime.restart": {"wait_s", "startup_wait_s", "expected_profile_revision",
88                                     "expected_owner_id", "expected_instance_id",
89                                     "allow_source_switch", "allow_source_migration",
90                                     "expected_source_sha256"},
91                 "runtime.verify": {"wait_s", "load",
92                                    "expected_owner_id", "expected_instance_id"}}
93                .get(kind, {"report_path", "exclusive_ack"}))
94    former_restart = expected - {"expected_owner_id", "expected_instance_id"}
95    legacy_restart = (former_restart, former_restart - {"allow_source_migration"},
96                      former_restart - {"allow_source_switch", "allow_source_migration",
97                                         "expected_source_sha256"})
98    legacy_start = kind == "runtime.start" and set(intent) == expected - {
99        "expected_profile_revision", "expected_source_sha256"}
100    legacy_stop = kind == "runtime.stop" and set(intent) == {"wait_s"}
101    legacy_verify = kind == "runtime.verify" and set(intent) == {"wait_s", "load"}
102    calibration_job = (kind.startswith("engine.calibrate.") and
103                       set(intent) == expected | {"if_source_sha256", "if_report_sha256"})
104    if (set(intent) != expected and not calibration_job and not legacy_start and not legacy_stop and not legacy_verify and
105            not (kind == "runtime.restart" and set(intent) in legacy_restart)):
106        raise ProfileError("direct operation intent has unsupported fields", 5)
107    if kind == "bench.run":
108        from strata_cli import bench
109        path = intent["path"]
110        suite = intent["suite"]
111        maximum = 64 if suite == "parallel-overload-v1" else 16
112        if (not isinstance(path, str) or len(path) > 1024 or not Path(path).is_absolute() or
113                any(ord(char) < 32 or ord(char) == 127 or
114                    0x202a <= ord(char) <= 0x202e or 0x2066 <= ord(char) <= 0x2069
115                    for char in path) or
116                not isinstance(suite, str) or suite not in bench.SUITES or
117                type(intent["concurrency"]) is not int or
118                not 1 <= intent["concurrency"] <= maximum or type(intent["repeat"]) is not int or
119                not 1 <= intent["repeat"] <= 5 or type(intent["request_timeout"]) not in (int, float) or
120                not math.isfinite(intent["request_timeout"]) or
121                not 1 <= intent["request_timeout"] <= 600 or
122                (intent["condition"] is not None and
123                 (not isinstance(intent["condition"], str) or
124                  not re.fullmatch(r"[a-z][a-z0-9_-]{0,39}", intent["condition"]))) or
125                not isinstance(intent["if_profile_revision"], str) or
126                not re.fullmatch(r"[0-9a-f]{16}", intent["if_profile_revision"]) or
127                not isinstance(intent["if_source_sha256"], str) or
128                not re.fullmatch(r"[0-9a-f]{64}", intent["if_source_sha256"]) or
129                any(not isinstance(intent[key], str) or not re.fullmatch(r"[0-9a-f]{32}", intent[key])
130                    for key in ("if_owner_id", "if_instance_id"))):
131            raise ProfileError("direct benchmark intent is invalid", 5)
132    elif kind.startswith("runtime."):
133        # The waits are bounded by the runtime that runs them, so the ceiling is read from it (#3949): a start or a
134        # restart may wait for a big model up to MAX_START_WAIT. Repeating the number here is what broke a long start
135        # twice over - the CLI validator and this record both stopped it at 600 s on their way to the runtime.
136        from strata_control import runtime as _runtime
137        start_wait_max = int(_runtime.MAX_START_WAIT)
138        ranges = {"wait_s": (0, start_wait_max) if kind == "runtime.start" else
139                    (1, 1800) if kind == "runtime.restart" else (1, 600),
140                  "shutdown_timeout_s": (0, 300), "startup_wait_s": (1, start_wait_max)}
141        for key in set(intent) - {"expected_profile_revision", "expected_source_sha256",
142                               "expected_owner_id", "expected_instance_id", "load",
143                               "allow_source_switch", "allow_source_migration"}:
144            value = intent[key]
145            low, high = ranges[key]
146            if type(value) not in (int, float) or not math.isfinite(value) or not low <= value <= high:
147                raise ProfileError("direct runtime intent has an invalid timeout", 5)
148        revision = intent.get("expected_profile_revision")
149        if kind == "runtime.verify" and type(intent["load"]) is not bool:
150            raise ProfileError("direct verification intent has an invalid load flag", 5)
151        if "allow_source_switch" in intent and type(intent["allow_source_switch"]) is not bool:
152            raise ProfileError("direct restart intent has an invalid source switch flag", 5)
153        if "allow_source_migration" in intent and type(intent["allow_source_migration"]) is not bool:
154            raise ProfileError("direct restart intent has an invalid source migration flag", 5)
155        source_digest = intent.get("expected_source_sha256")
156        if kind in ("runtime.start", "runtime.restart") and ((source_digest is not None and
157                                           (not isinstance(source_digest, str) or
158                                            not re.fullmatch(r"[0-9a-f]{64}", source_digest))) or
159                                          ((intent.get("allow_source_switch") is True or
160                                            intent.get("allow_source_migration") is True) and
161                                           source_digest is None)):
162            raise ProfileError("direct runtime intent needs a valid candidate source digest", 5)
163        if kind in ("runtime.start", "runtime.restart") and revision is not None and \
164                (not isinstance(revision, str) or not re.fullmatch(r"[0-9a-f]{16}", revision)):
165            raise ProfileError("direct runtime intent has an invalid profile revision", 5)
166        if kind in ("runtime.stop", "runtime.restart", "runtime.verify"):
167            for key in ("expected_owner_id", "expected_instance_id"):
168                identity = intent.get(key)
169                if identity is not None and (not isinstance(identity, str) or
170                        not re.fullmatch(r"[0-9a-f]{32}", identity)):
171                    raise ProfileError("direct runtime intent has an invalid identity", 5)
172        if kind == "runtime.verify" and (intent.get("expected_owner_id") is None) != \
173                (intent.get("expected_instance_id") is None):
174            raise ProfileError("direct verification intent needs both identities", 5)
175    else:
176        path = intent["report_path"]
177        if not isinstance(path, str) or len(path) > 4096 or not Path(path).is_absolute() or \
178                intent["exclusive_ack"] is not True:
179            raise ProfileError("direct calibration intent needs an absolute report path and exclusive access", 5)
180        if calibration_job and (not isinstance(intent["if_source_sha256"], str) or
181                not re.fullmatch(r"[0-9a-f]{64}", intent["if_source_sha256"]) or
182                (kind == "engine.calibrate.measure" and intent["if_report_sha256"] is not None) or
183                (kind != "engine.calibrate.measure" and
184                 (not isinstance(intent["if_report_sha256"], str) or
185                  not re.fullmatch(r"[0-9a-f]{64}", intent["if_report_sha256"])))):
186            raise ProfileError("direct calibration job intent is invalid", 5)
187    return intent
188
189
190def _load_file(path: Path, profile: str) -> dict:
191    try:
192        details = path.lstat()
193        if not stat.S_ISREG(details.st_mode) or details.st_size > MAX_RECORD_BYTES:
194            raise ProfileError("operation record must be a regular file under 64 KiB", 5)
195        if os.name == "posix" and (posix_owner.owner_only_wrong(path, details)):
196            raise ProfileError(posix_owner.owner_only_text("operation record must be owner-only", path), 5)
197        record = json.loads(path.read_text(encoding="utf-8"))
198    except FileNotFoundError:
199        raise ProfileError("operation record was not found", 5) from None
200    except (OSError, UnicodeError, ValueError) as exc:
201        if isinstance(exc, ProfileError):
202            raise
203        raise ProfileError(f"cannot read operation record ({type(exc).__name__})", 5) from None
204    schema = record.get("schema_version") if isinstance(record, dict) else None
205    expected_keys = RECORD_KEYS if schema == 1 else DIRECT_RECORD_KEYS if schema == 2 else None
206    if not isinstance(record, dict) or expected_keys is None or set(record) != expected_keys or \
207            type(record.get("schema_version")) is not int or \
208            record.get("operation_id") != path.stem or record.get("profile") != profile or \
209            not isinstance(record.get("profile_revision"), str) or \
210            not re.fullmatch(r"[0-9a-f]{16}", record["profile_revision"]) or \
211            not isinstance(record.get("state"), str) or record["state"] not in {"running", *TERMINAL} or \
212            type(record.get("owner_pid")) is not int or record["owner_pid"] < 1 or \
213            not isinstance(record.get("started_at"), (int, float)) or \
214            not math.isfinite(record["started_at"]) or \
215            record.get("cancellation_policy") != "caller_interrupt_may_leave_remote_work_running" or \
216            not isinstance(record.get("events"), list) or not 1 <= len(record["events"]) <= 16 or \
217            (record["state"] == "running" and record.get("finished_at") is not None) or \
218            (record["state"] == "running" and record.get("result") is not None) or \
219            (record["state"] in TERMINAL and not isinstance(record.get("finished_at"), (int, float))) or \
220            (record["state"] in TERMINAL and not math.isfinite(record["finished_at"])) or \
221            (record["state"] in TERMINAL and not isinstance(record.get("result"), dict)):
222        raise ProfileError("operation record has an unsupported shape", 5)
223    try:
224        if schema == 1:
225            if not isinstance(record.get("recipe"), str) or \
226                    not profiles.PROFILE_ID.fullmatch(record["recipe"]) or \
227                    not isinstance(record.get("recipe_revision"), str) or \
228                    not re.fullmatch(r"[0-9a-f]{16}", record["recipe_revision"]):
229                raise ProfileError("operation record has an invalid recipe revision", 5)
230            recipes._validate({"schema_version": 1, "profile": profile, "id": record["recipe"],
231                               "kind": record["kind"], "params": record["intent"]},
232                              profile, record["recipe"])
233        elif record.get("origin") != "direct":
234            raise ProfileError("operation record has an invalid origin", 5)
235        else:
236            _validate_direct_intent(record["kind"], record["intent"])
237    except (ProfileError, TypeError):
238        raise ProfileError("operation record has an unsupported intent", 5) from None
239    if not all(isinstance(event, dict) and set(event) == {"seq", "at", "state"} and
240               type(event["seq"]) is int and event["seq"] == index and
241               isinstance(event["at"], (int, float)) and math.isfinite(event["at"]) and
242               isinstance(event["state"], str) and event["state"] in {"running", *TERMINAL}
243               for index, event in enumerate(record["events"], 1)):
244        raise ProfileError("operation record has invalid events", 5)
245    if record["events"][0]["state"] != "running" or record["events"][-1]["state"] != record["state"]:
246        raise ProfileError("operation record has inconsistent events", 5)
247    if record["result"] is not None and set(record["result"]) - RESULT_KEYS:
248        raise ProfileError("operation record has unsupported result fields", 5)
249    return record
250
251
252def load(profile: str, operation_id: str) -> dict:
253    record = _load_file(_path(profile, operation_id), profile)
254    if record["state"] == "running":
255        return {**record, "completion_unverified": True}
256    return record
257
258
259def list_runs(profile: str, *, limit: int = 20) -> list[dict]:
260    if not 1 <= limit <= 100:
261        raise ProfileError("operation list limit must be 1..100")
262    directory = _directory(profile)
263    if not directory.exists():
264        return []
265    paths = sorted((path for path in directory.glob("*.json") if ID.fullmatch(path.stem)),
266                   key=lambda path: path.lstat().st_mtime, reverse=True)
267    items = []
268    for path in paths[:limit]:
269        try:
270            record = _load_file(path, profile)
271            items.append({"operation_id": record["operation_id"], "recipe": record.get("recipe"),
272                          "origin": "recipe" if record["schema_version"] == 1 else "direct",
273                          "kind": record["kind"], "state": record["state"],
274                          "started_at": record["started_at"], "finished_at": record.get("finished_at"),
275                          "completion_unverified": record["state"] == "running"})
276        except ProfileError as exc:
277            items.append({"operation_id": path.stem, "error": str(exc)})
278    return items
279
280
281def _prune(directory: Path, profile: str) -> None:
282    paths = sorted((path for path in directory.glob("*.json") if ID.fullmatch(path.stem)),
283                   key=lambda path: path.lstat().st_mtime)
284    count = len(paths)
285    for path in paths:
286        if count < MAX_RECORDS:
287            break
288        try:
289            record = _load_file(path, profile)
290        except ProfileError:
291            continue
292        if record["state"] in TERMINAL:
293            path.unlink()
294            (directory / f"{path.stem}.progress.json").unlink(missing_ok=True)
295            (directory / f"{path.stem}.cancel").unlink(missing_ok=True)
296            count -= 1
297    if count >= MAX_RECORDS:
298        raise ProfileError("operation journal is full; archive completed records before running another action", 5)
299
300
301def _save_new(profile: str, record: dict) -> dict:
302    directory = _directory(profile, create=True)
303    path = _path(profile, record["operation_id"])
304    with profiles._lock(_lock_name(profile)):
305        _prune(directory, profile)
306        flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
307        if hasattr(os, "O_NOFOLLOW"):
308            flags |= os.O_NOFOLLOW
309        descriptor = os.open(path, flags, 0o600)
310        try:
311            with os.fdopen(descriptor, "wb") as stream:
312                stream.write(_bytes(record))
313                stream.flush()
314                os.fsync(stream.fileno())
315        except BaseException:
316            path.unlink(missing_ok=True)
317            raise
318    return record
319
320
321def _running_base(profile: str, kind: str, profile_revision: str, intent: dict,
322                  operation_id: str | None = None) -> dict:
323    now = time.time()
324    return {"operation_id": operation_id or uuid.uuid4().hex, "profile": profile, "kind": kind,
325            "profile_revision": profile_revision, "owner_pid": os.getpid(), "intent": intent,
326            "state": "running", "started_at": now, "finished_at": None,
327            "cancellation_policy": "caller_interrupt_may_leave_remote_work_running",
328            "events": [{"seq": 1, "at": now, "state": "running"}], "result": None}
329
330
331def begin(profile: str, recipe: str, kind: str, recipe_revision: str,
332          profile_revision: str, *, intent: dict | None = None) -> dict:
333    if intent is None:
334        intent = {}
335    if not isinstance(intent, dict):
336        raise ProfileError("operation intent must be typed")
337    recipes._validate({"schema_version": 1, "profile": profile, "id": recipe,
338                       "kind": kind, "params": intent}, profile, recipe)
339    if not isinstance(recipe_revision, str) or not isinstance(profile_revision, str) or \
340            not re.fullmatch(r"[0-9a-f]{16}", recipe_revision) or \
341            not re.fullmatch(r"[0-9a-f]{16}", profile_revision):
342        raise ProfileError("operation revisions must be full 16-character values")
343    record = {"schema_version": 1, **_running_base(profile, kind, profile_revision, intent),
344              "recipe": recipe, "recipe_revision": recipe_revision}
345    return _save_new(profile, record)
346
347
348def begin_direct(profile: str, kind: str, profile_revision: str, intent: dict,
349                 *, operation_id: str | None = None) -> dict:
350    _, current_revision = profiles.load(profile)
351    _validate_direct_intent(kind, intent)
352    if not isinstance(profile_revision, str) or not re.fullmatch(r"[0-9a-f]{16}", profile_revision):
353        raise ProfileError("operation profile revision must be a full 16-character value")
354    if profile_revision != current_revision:
355        raise ProfileError("profile changed before direct operation; preview again", 6)
356    if operation_id is not None and (not isinstance(operation_id, str) or
357                                     not ID.fullmatch(operation_id)):
358        raise ProfileError("operation ID must be a 32-character hex value")
359    record = {"schema_version": 2, **_running_base(profile, kind, profile_revision, dict(intent), operation_id),
360              "origin": "direct"}
361    return _save_new(profile, record)
362
363
364def finish(profile: str, operation_id: str, state: str, result: dict) -> dict:
365    if state not in TERMINAL:
366        raise ProfileError("operation terminal state is invalid")
367    if not isinstance(result, dict) or set(result) - RESULT_KEYS:
368        raise ProfileError("operation result contains unsupported fields")
369    path = _path(profile, operation_id)
370    with profiles._lock(_lock_name(profile)):
371        record = _load_file(path, profile)
372        if record["state"] != "running":
373            raise ProfileError("operation has already finished", 6)
374        now = time.time()
375        record.update({"state": state, "finished_at": now, "result": result})
376        record["events"].append({"seq": len(record["events"]) + 1, "at": now, "state": state})
377        profiles._atomic(path, _bytes(record))
378    return record
379
380
381def run_direct(profile: str, kind: str, profile_revision: str, intent: dict, action) -> tuple[str, dict]:
382    """Record one already-authorized CLI action; uncertain interruption stays explicit."""
383    record = begin_direct(profile, kind, profile_revision, intent)
384    try:
385        result = action()
386        if not isinstance(result, dict):
387            raise ProfileError("direct operation returned an invalid result", 6)
388    except BaseException as exc:
389        unknown = isinstance(exc, (KeyboardInterrupt, SystemExit)) or \
390            (isinstance(exc, ProfileError) and exc.exit_code == 8)
391        finish(profile, record["operation_id"], "completion_unknown" if unknown else "failed",
392               {"error_type": type(exc).__name__,
393                "exit_code": exc.exit_code if isinstance(exc, ProfileError) else 130 if unknown else 6})
394        raise
395    state = ("succeeded" if result.get("ok", True) else
396             "completion_unknown" if result.get("exit_code") == 8 else "failed")
397    finish(profile, record["operation_id"], state, compact_direct_result(kind, result))
398    return record["operation_id"], result
399
400
401def compact_direct_result(kind: str, result: dict) -> dict:
402    if kind == "bench.run":
403        summary = result.get("summary") or {}
404        return {"ok": result.get("ok", True), "report_path": result.get("path"),
405                "run_id": summary.get("run_id"), "instance_id": summary.get("instance_id"),
406                "successful": result.get("successful"), "cancelled": summary.get("cancelled")}
407    if kind == "runtime.verify":
408        return {key: result.get(key) for key in ("ok", "state", "instance_id", "error", "exit_code",
409                                                  "api_identity_verified", "launch_attested", "generation_ready",
410                                                  "readiness_state", "verified_now")}
411    if kind.startswith("runtime."):
412        return {key: result.get(key) for key in ("ok", "state", "instance_id", "previous_instance_id",
413                                                  "restarted", "rolled_back", "source_switched",
414                                                  "source_migrated", "rollback_source_config",
415                                                  "rollback_snapshot_cleanup_pending", "launch_attested",
416                                                  "error", "exit_code")}
417    if kind == "engine.calibrate.measure":
418        report = result.get("report") or {}
419        return {"ok": result.get("ok", True), "report_path": result.get("report_path"),
420                "report_id": report.get("report_id"), "applicable": report.get("applicable")}
421    if kind == "engine.calibrate.apply":
422        application = result.get("application") or {}
423        return {"ok": result.get("ok", True), "report_id": application.get("report_id"),
424                "changed": application.get("changed"),
425                "application_record": application.get("application_record")}
426    rollback = result.get("rollback") or {}
427    return {"ok": result.get("ok", True), "report_id": rollback.get("report_id"),
428            "changed": rollback.get("changed"),
429            "setup_settings_removed": rollback.get("setup_settings_removed")}
430
431
432def compact_result(kind: str, result: dict) -> dict:
433    """Only reviewed, bounded fields reach the persistent journal."""
434    if kind == "runtime.restart":
435        return {key: result.get(key) for key in ("ok", "state", "instance_id", "previous_instance_id",
436                                                  "restarted", "rolled_back", "source_switched",
437                                                  "source_migrated", "rollback_source_config",
438                                                  "rollback_snapshot_cleanup_pending", "launch_attested",
439                                                  "error", "exit_code")}
440    if kind == "engine.calibrate.measure":
441        report = result.get("report") or {}
442        return {"ok": result.get("ok"), "report_path": result.get("report_path"),
443                "report_id": report.get("report_id"), "applicable": report.get("applicable")}
444    report = result.get("report") or {}
445    return {"ok": result.get("ok"), "issue_codes": [item.get("code") for item in report.get("issues", [])][:50]}