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
4.7 KiB107 linesraw
1"""Saved tuning presets after the engine changed: mark them for the short re-check, never delete them.
2
3A tuning preset is valid for one identity (GPU and driver, engine build, model file, context). When an engine update
4changes the engine part of that identity the presets are not wrong, only unconfirmed. The plan (4b) says to offer a short
5check of about two minutes, not a full re-tune, and to keep every preset.
6
7This module is the one thing the updater writes about presets, and it is deliberately not a preset store: it writes a
8small, separate file next to the tuning state, ``<state>/tuning/recheck.json``, and never opens, moves or rewrites a
9preset. The tuner (S5) reads `pending()` when it loads a preset and, once the short check passed or the user re-tuned,
10calls `clear(mark_id)`. The file is created only when an engine identity actually changed, so a PC without an earlier
11engine, or an update to a build with the same identity, writes nothing.
12
13    {"schema_version": 1,
14     "pending": [{"id": "...", "reason": "engine_changed", "component": "strata-engine",
15                  "from": {"version", "build_id", "manifest_sha256", "backend", "platform", "variant"},
16                  "to":   {... same ...}, "marked_at": "<iso>"}]}
17"""
18
19from __future__ import annotations
20
21import datetime as dt
22import json
23import os
24import tempfile
25import uuid
26from pathlib import Path
27
28from strata_control import paths
29from strata_control import atomic as _atomic_mod
30
31SCHEMA_VERSION = 1
32IDENTITY_KEYS = ("version", "build_id", "manifest_sha256", "backend", "platform", "variant")
33
34
35def marks_path(base: Path | None = None) -> Path:
36    return (base or paths.state_base()) / "tuning" / "recheck.json"
37
38
39def identity_of(component, manifest_sha256: str) -> dict:
40    """The engine part of a preset's identity, from an installed `EngineComponent`."""
41    return {"version": component.version, "build_id": component.build_id, "manifest_sha256": manifest_sha256,
42            "backend": component.backend, "platform": component.platform, "variant": component.variant}
43
44
45def _read(path: Path) -> dict:
46    try:
47        data = json.loads(path.read_text(encoding="utf-8-sig"))
48    except (OSError, ValueError):
49        return {"schema_version": SCHEMA_VERSION, "pending": []}
50    if not isinstance(data, dict) or not isinstance(data.get("pending"), list):
51        return {"schema_version": SCHEMA_VERSION, "pending": []}
52    return data
53
54
55def _write(path: Path, data: dict) -> None:
56    path.parent.mkdir(parents=True, exist_ok=True)
57    descriptor, temp = tempfile.mkstemp(prefix=".recheck-", suffix=".tmp", dir=path.parent)
58    try:
59        with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
60            json.dump(data, stream, indent=1, sort_keys=True)
61            stream.write("\n")
62        _atomic_mod.replace(temp, path)
63    finally:
64        if os.path.exists(temp):
65            os.unlink(temp)
66
67
68def pending(base: Path | None = None) -> list[dict]:
69    return list(_read(marks_path(base))["pending"])
70
71
72def mark_engine_changed(before: dict | None, after: dict, *, base: Path | None = None,
73                        now: dt.datetime | None = None) -> dict | None:
74    """Record that presets measured on `before` are unconfirmed on `after`. Returns the mark, or None when nothing is owed:
75    there was no earlier engine, or the identity did not change. Presets are not touched."""
76    if before is None:
77        return None
78    if all(before.get(key) == after.get(key) for key in IDENTITY_KEYS):
79        return None
80    path = marks_path(base)
81    data = _read(path)
82    when = (now or dt.datetime.now(dt.timezone.utc)).isoformat()
83    mark = {"id": uuid.uuid4().hex, "reason": "engine_changed", "component": "strata-engine",
84            "from": {k: before.get(k) for k in IDENTITY_KEYS}, "to": {k: after.get(k) for k in IDENTITY_KEYS},
85            "marked_at": when}
86    # a second change before the check supersedes the first: one pending re-check from the identity the presets were measured on
87    older = [m for m in data["pending"] if m.get("reason") == "engine_changed"]
88    if older:
89        mark["from"] = older[0]["from"]
90        data["pending"] = [m for m in data["pending"] if m.get("reason") != "engine_changed"]
91        if all(mark["from"].get(k) == mark["to"].get(k) for k in IDENTITY_KEYS):
92            _write(path, data)          # rolled back to the identity the presets were measured on: nothing is owed any more
93            return None
94    data["pending"].append(mark)
95    _write(path, data)
96    return mark
97
98
99def clear(mark_id: str, base: Path | None = None) -> bool:
100    path = marks_path(base)
101    data = _read(path)
102    kept = [m for m in data["pending"] if m.get("id") != mark_id]
103    if len(kept) == len(data["pending"]):
104        return False
105    data["pending"] = kept
106    _write(path, data)
107    return True