okami.mom/strata

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

Niko1221Merge f-0213-tuicfg (final c6dda74bf) into f-0213-int049ae1c67

main
38.1 KiB751 linesraw
1"""Explicit measure, review and apply steps around Strata's existing calibration.
2
3The current suite measures decode speed. It is not a four-GPU serving benchmark.
4Its report binds a candidate to the run config, engine binary and observed local
5hardware; applying it is a separate operation with a backup and smoke generation.
6"""
7
8from __future__ import annotations
9
10from strata_control.private_files import private_mkdir as _private_mkdir
11import copy
12import hashlib
13import json
14import math
15import os
16import re
17import socket
18import stat
19import tempfile
20import threading
21import time
22import uuid
23from contextlib import contextmanager
24from pathlib import Path
25
26from strata_control import profiles
27from strata_control.doctor import inspect as inspect_components
28from strata_control.profiles import ProfileError
29from strata_control import atomic as _atomic_mod
30from strata_control import posix_owner
31
32
33SUITE = "legacy-decode-v1"
34MAX_REPORT_BYTES = 2 * 1024 * 1024
35MAX_APPLICATION_BYTES = 8 * 1024
36MAX_AGE_SECONDS = 30 * 24 * 3600
37ALLOWED_SETTINGS = {"--pcie-frac", "--spec-min-p", "--pool-workers",
38                    "--adapt-every", "--adapt-swaps", "--adapt-decay"}
39
40
41def _full_folder(name: str):
42    """`setup` and `tools.calibrate` belong to a full Strata folder; the Terminal archive carries neither (it never
43    installs or builds). Use them when they are importable, or when STRATA_INSTALL_DIR names a folder that has both;
44    otherwise refuse in words instead of a traceback."""
45    import importlib
46    import sys
47    try:
48        return importlib.import_module(name)
49    except ImportError:
50        pass
51    raw = os.environ.get("STRATA_INSTALL_DIR")
52    if raw:
53        folder = Path(raw).expanduser()
54        if (folder / "setup.py").is_file() and (folder / "tools" / "calibrate.py").is_file():
55            if str(folder) not in sys.path:
56                sys.path.append(str(folder))
57            try:
58                return importlib.import_module(name)
59            except ImportError:
60                pass
61    raise ProfileError(
62        "engine calibrate needs a full Strata folder (setup.py and tools/calibrate.py); this terminal archive has "
63        "neither. Set STRATA_INSTALL_DIR to such a folder, or use `strata tune run --mode api` to tune from the "
64        "archive", 5) from None
65
66
67def _tools_available() -> bool:
68    """False in the Terminal archive without STRATA_INSTALL_DIR: `--measure` would be refused (see `_full_folder`)."""
69    import importlib.util
70    try:
71        if importlib.util.find_spec("setup") and importlib.util.find_spec("tools.calibrate"):
72            return True
73    except (ImportError, ValueError):
74        pass
75    raw = os.environ.get("STRATA_INSTALL_DIR")
76    if raw:
77        folder = Path(raw).expanduser()
78        return (folder / "setup.py").is_file() and (folder / "tools" / "calibrate.py").is_file()
79    return False
80
81
82def _digest(path: Path) -> str:
83    result = hashlib.sha256()
84    with path.open("rb") as stream:
85        for block in iter(lambda: stream.read(1024 * 1024), b""):
86            result.update(block)
87    return result.hexdigest()
88
89
90def _target(ref: str) -> tuple[Path, dict | None, str | None, dict]:
91    path, profile, revision = profiles.resolve(ref)
92    return path, profile, revision, profiles.read_run_config(path)
93
94
95def preview(ref: str) -> dict:
96    """Inspect a proposed decode sweep without starting the engine or writing files."""
97    path, profile, revision, cfg = _target(ref)
98    components = inspect_components(path, profile_id=profile["id"] if profile else None)
99    source_bytes = path.read_bytes()
100    if json.loads(source_bytes.decode("utf-8-sig")) != cfg:
101        raise ProfileError("run config changed during calibration preview; retry", 6)
102    return {"profile": profile["id"] if profile else None, "profile_revision": revision,
103            "source_config": str(path), "source_sha256": hashlib.sha256(source_bytes).hexdigest(),
104            "model_name": cfg.get("model_name"), "backend": cfg.get("backend") or "unverified",
105            "devices_selected": cfg.get("gpu"), "tool": "tools/calibrate.py",
106            "tool_available": _tools_available(),
107            "estimated_minutes": [15, 30], "requires_exclusive_engine": True,
108            "settings_measured": ["--pcie-frac", "--spec-min-p", "--pool-workers",
109                                  "--adapt-every", "--adapt-swaps", "--adapt-decay"],
110            "component_preflight": components, "hardware_identity": "unverified_until_measurement",
111            "would_start_engine": False, "would_write_config": False}
112
113
114def _resolved(raw: str, cfg: dict, path: Path) -> Path:
115    from strata_control import engine_component
116    if engine_component.is_reference(raw):
117        return Path(engine_component.expand(raw, cfg))
118    value = Path(raw).expanduser()
119    if value.is_absolute():
120        return value
121    cwd = cfg.get("cwd")
122    return (Path(cwd) if isinstance(cwd, str) and cwd else path.parent) / value
123
124
125def _runtime_cfg(cfg: dict, profile: dict | None) -> dict:
126    """Apply the saved engine concurrency settings without changing setup's config."""
127    effective = copy.deepcopy(cfg)
128    if profile is None:
129        return effective
130    overrides = profile["overrides"]
131    if "parallel" in overrides:
132        if any(flag in effective["args"] for flag in ("--batch", "--slots")):
133            raise ProfileError("parallel profile override conflicts with engine args")
134        effective["parallel"] = overrides["parallel"]
135    if "batch_groups" in overrides:
136        if "--batch-groups" in effective["args"]:
137            raise ProfileError("batch_groups profile override conflicts with engine args")
138        effective["args"] += ["--batch-groups", str(overrides["batch_groups"])]
139    return effective
140
141
142def _hardware_key(cfg: dict) -> str:
143    return _full_folder("setup").hardware_key(cfg)
144
145
146def _identity(path: Path, cfg: dict, profile: dict | None, revision: str | None) -> dict:
147    cal = _full_folder("tools.calibrate")
148    engine = _resolved(cfg["exe"], cfg, path)
149    components = inspect_components(path, profile_id=profile["id"] if profile else None)
150    if not components["ok"]:
151        raise ProfileError("required engine/model components are missing; run strata doctor --profile first", 5)
152    files = []
153    for item in components["components"]:
154        if item.get("required") and item.get("kind") == "file" and item.get("name") != "engine":
155            file_path = Path(item["path"])
156            try:
157                details = file_path.stat()
158            except OSError:
159                raise ProfileError(f"component changed during calibration: {item['name']}", 5) from None
160            files.append({"name": item["name"], "path": str(file_path),
161                          "size": details.st_size, "modified_ns": details.st_mtime_ns})
162    return {"source_sha256": _digest(path), "engine_sha256": _digest(engine),
163            "suite_sha256": _digest(Path(cal.__file__)), "hardware_key": _hardware_key(cfg),
164            "model_name": cfg.get("model_name"), "backend": cfg.get("backend"), "gpu": cfg.get("gpu"),
165            "profile_id": profile["id"] if profile else None, "profile_revision": revision,
166            "required_file_metadata": files, "model_integrity": "metadata_only_unverified"}
167
168
169def _validate_settings(settings: object) -> dict[str, str]:
170    if not isinstance(settings, dict) or set(settings) - ALLOWED_SETTINGS:
171        raise ProfileError("calibration report has unsupported settings", 5)
172    out = {}
173    for flag, raw in settings.items():
174        if not isinstance(raw, str) or len(raw) > 32:
175            raise ProfileError(f"calibration setting {flag} must be a short string", 5)
176        try:
177            number = float(raw)
178        except ValueError:
179            raise ProfileError(f"calibration setting {flag} must be numeric", 5) from None
180        if not number == number or number in (float("inf"), float("-inf")):
181            raise ProfileError(f"calibration setting {flag} must be finite", 5)
182        if flag in ("--pcie-frac", "--spec-min-p", "--adapt-decay"):
183            if not 0 <= number <= 1:
184                raise ProfileError(f"calibration setting {flag} must be in 0..1", 5)
185        else:
186            if not raw.isdecimal() or not 1 <= int(raw) <= 8192:
187                raise ProfileError(f"calibration setting {flag} must be a positive whole number", 5)
188        out[flag] = raw
189    return out
190
191
192def _port_active(cfg: dict) -> bool:
193    port = cfg.get("port", 8095)
194    if type(port) is not int or not 1 <= port <= 65535:
195        return False
196    host = cfg.get("host") or "127.0.0.1"
197    address = "127.0.0.1" if host in ("0.0.0.0", "::", "localhost") else host
198    try:
199        with socket.create_connection((address, port), timeout=0.2):
200            return True
201    except OSError:
202        return False
203
204
205def _exclusive_preflight(cfg: dict, profile: dict | None = None) -> None:
206    endpoints = [cfg]
207    overrides = profile["overrides"] if profile else {}
208    if "host" in overrides or "port" in overrides:
209        endpoints.append({**cfg, **{key: overrides[key] for key in ("host", "port") if key in overrides}})
210    if any(_port_active(endpoint) for endpoint in endpoints):
211        raise ProfileError("a server is listening on this profile's port; stop it before calibration", 6)
212
213
214@contextmanager
215def _managed_exclusive():
216    """Keep new owner hosts out for the full calibration engine action."""
217    if os.name not in ("posix", "nt"):
218        yield
219        return
220    from strata_control import runtime
221    lease = runtime.acquire_activity_lease(shared=False)
222    try:
223        active = runtime.active_managed_instances()
224        if active:
225            raise ProfileError("stop managed Strata runtime instances before calibration: " +
226                               ", ".join(item["profile"] for item in active), 6)
227        yield
228    finally:
229        os.close(lease)
230
231
232def _write_new(path: Path, payload: bytes) -> None:
233    if not path.parent.is_dir():
234        raise ProfileError("report output directory does not exist", 5)
235    descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
236    try:
237        with os.fdopen(descriptor, "wb") as stream:
238            stream.write(payload)
239            stream.flush()
240            os.fsync(stream.fileno())
241    except BaseException:
242        path.unlink(missing_ok=True)
243        raise
244
245
246def _report_bytes(report: dict) -> bytes:
247    try:
248        payload = (json.dumps(report, ensure_ascii=False, sort_keys=True, indent=2, allow_nan=False) + "\n").encode("utf-8")
249    except (TypeError, ValueError):
250        raise ProfileError("calibration returned an invalid report", 6) from None
251    if len(payload) > MAX_REPORT_BYTES:
252        raise ProfileError("calibration report exceeds 2 MiB", 6)
253    return payload
254
255
256def _body_sha256(report: dict) -> str:
257    body = {key: value for key, value in report.items() if key != "body_sha256"}
258    try:
259        encoded = json.dumps(body, ensure_ascii=False, sort_keys=True, separators=(",", ":"),
260                             allow_nan=False).encode("utf-8")
261    except (TypeError, ValueError):
262        raise ProfileError("calibration report has invalid values", 5) from None
263    return hashlib.sha256(encoded).hexdigest()
264
265
266def _lock_name(path: Path) -> str:
267    return "cal" + hashlib.sha256(str(path.resolve()).encode("utf-8")).hexdigest()[:24]
268
269
270def measure(ref: str, output: Path, *, exclusive_ack: bool = False, say=print, runner=None,
271            expected_profile_revision: str | None = None,
272            expected_source_sha256: str | None = None, job_id: str | None = None,
273            progress=None, cancel_event=None) -> dict:
274    """Run the existing decode sweep, leaving the run config unchanged."""
275    if not exclusive_ack:
276        raise ProfileError("calibration measure requires an exclusive-access acknowledgement")
277    path, profile, revision, cfg = _target(ref)
278    with profiles._lock(_lock_name(path)), _managed_exclusive():
279        current_path, profile, revision, cfg = _target(ref)
280        if current_path != path or (expected_profile_revision is not None and
281                                    revision != expected_profile_revision) or \
282                (expected_source_sha256 is not None and
283                 _digest(current_path) != expected_source_sha256):
284            raise ProfileError("calibration source changed after review; review again", 6)
285        return _measure_locked(ref, path, profile, revision, cfg, output, say=say, runner=runner,
286                               job_id=job_id, progress=progress, cancel_event=cancel_event)
287
288
289def _measure_locked(ref: str, path: Path, profile: dict | None, revision: str | None, cfg: dict,
290                    output: Path, *, say, runner, job_id: str | None = None,
291                    progress=None, cancel_event=None) -> dict:
292    _exclusive_preflight(cfg, profile)
293    if output.exists() or output.is_symlink():
294        raise ProfileError("calibration report path already exists", 2)
295    if not output.parent.is_dir():                    # before the 19 minute sweep, not after it (#3187)
296        raise ProfileError("report output directory does not exist", 5)
297    identity = _identity(path, cfg, profile, revision)
298    cal =_full_folder("tools.calibrate")
299    execute = runner or cal.run
300    runner_cfg = _runtime_cfg(cfg, profile)
301    runner_cfg["exe"] = str(_resolved(cfg["exe"], cfg, path))
302    runner_cfg["tokenizer"] = str(_resolved(cfg["tokenizer"], cfg, path))
303    try:
304        if cancel_event is not None and cancel_event.is_set():
305            raise cal.CalibrationCancelled("calibration cancelled")
306        result = (execute(runner_cfg, say=say) if progress is None and cancel_event is None else
307                  execute(runner_cfg, say=say, progress=progress, cancel_event=cancel_event))
308    except cal.CalibrationCancelled:
309        raise ProfileError("calibration cancelled by operator; config unchanged", 130) from None
310    except (KeyboardInterrupt, SystemExit):
311        raise
312    except Exception as exc:
313        raise ProfileError(f"calibration measurement failed ({type(exc).__name__}); config unchanged", 6) from None
314    if not isinstance(result, dict) or not isinstance(result.get("report"), dict):
315        raise ProfileError("calibration returned no measurement report", 6)
316    settings = _validate_settings(result.get("settings"))
317    try:
318        end_path, end_profile, end_revision, end_cfg = _target(ref)
319        unchanged = path == end_path and identity == _identity(end_path, end_cfg, end_profile, end_revision)
320    except ProfileError:
321        unchanged = False
322    report = {"schema_version": 1, "kind": "strata.engine.calibration", "suite": SUITE,
323              "report_id": uuid.uuid4().hex, "created_at": time.time(), "source_config": str(path),
324              "identity": identity, "applicable": unchanged, "settings": settings,
325              "measurements": result["report"]}
326    if job_id is not None:
327        if not re.fullmatch(r"[0-9a-f]{32}", job_id):
328            raise ProfileError("calibration job ID is invalid", 5)
329        report["operation_id"] = job_id
330    report["body_sha256"] = _body_sha256(report)
331    if progress is not None:
332        progress("saving_report", 0, 1)
333    _write_new(output, _report_bytes(report))
334    if progress is not None:
335        progress("saving_report", 1, 1)
336    return report
337
338
339def load_report(path: Path) -> dict:
340    try:
341        if not stat.S_ISREG(path.lstat().st_mode) or path.stat().st_size > MAX_REPORT_BYTES:
342            raise ProfileError("calibration report must be a regular file under 2 MiB", 5)
343        report = json.loads(path.read_text(encoding="utf-8"))
344    except (OSError, UnicodeError, ValueError) as exc:
345        if isinstance(exc, ProfileError):
346            raise
347        raise ProfileError(f"cannot read calibration report ({type(exc).__name__})", 5) from None
348    if not isinstance(report, dict) or type(report.get("schema_version")) is not int or \
349            report["schema_version"] != 1 or \
350            report.get("kind") != "strata.engine.calibration" or report.get("suite") != SUITE or \
351            not isinstance(report.get("identity"), dict) or not isinstance(report.get("measurements"), dict) or \
352            not isinstance(report.get("source_config"), str) or \
353            type(report.get("created_at")) not in (int, float) or \
354            not math.isfinite(report["created_at"]) or \
355            not re.fullmatch(r"[0-9a-f]{32}", str(report.get("report_id", ""))):
356        raise ProfileError("unsupported calibration report", 5)
357    _validate_settings(report.get("settings"))
358    if report.get("body_sha256") != _body_sha256(report):
359        raise ProfileError("calibration report contents changed after measurement", 5)
360    return report
361
362
363def review(ref: str, report_path: Path) -> dict:
364    path, profile, revision, cfg = _target(ref)
365    report = load_report(report_path)
366    cal = _full_folder("tools.calibrate")
367    reasons = []
368    if report["source_config"] != str(path):
369        reasons.append("source_config_mismatch")
370    if report.get("applicable") is not True:
371        reasons.append("measurement_became_stale")
372    age = time.time() - report["created_at"]
373    if age < -300 or age > MAX_AGE_SECONDS:
374        reasons.append("report_expired")
375    try:
376        now = _identity(path, cfg, profile, revision)
377        if now != report["identity"]:
378            reasons.append("source_engine_model_or_hardware_changed")
379    except ProfileError as exc:
380        reasons.append(f"identity_unavailable:{exc.exit_code}")
381    after = cal.apply(cfg["args"], report["settings"])
382    return {"schema_version": 1, "report_id": report.get("report_id"), "profile": profile["id"] if profile else None,
383            "source_config": str(path), "applicable": not reasons, "reasons": reasons,
384            "settings": report["settings"], "before_args": cfg["args"], "after_args": after,
385            "measurements": report["measurements"], "model_integrity": "metadata_only_unverified"}
386
387
388def _smoke(cfg: dict, source_path: Path) -> int:
389    """Start the candidate and require at least one generated token before writing it."""
390    import strata_tokenizer as st
391    from serve.server import StrataEngine, child_env, engine_args
392    cal = _full_folder("tools.calibrate")
393    tokdir = _resolved(cfg["tokenizer"], cfg, source_path)
394    vocab = json.loads((tokdir / "vocab.json").read_text(encoding="utf-8"))
395    tokens = [None] * len(vocab)
396    for token, index in vocab.items():
397        tokens[index] = token
398    tok = st.Tokenizer(tokens, (tokdir / "merges.txt").read_text(encoding="utf-8").split("\n"),
399                       json.loads((tokdir / "token_type.json").read_text(encoding="utf-8")))
400    engine = StrataEngine(str(_resolved(cfg["exe"], cfg, source_path)), engine_args(cfg),
401                          cwd=cfg.get("cwd"), log=cfg.get("log"), env=child_env(cfg))
402    try:
403        ids = cal.chat_ids(tok, "Say OK.")
404        count = sum(token is not None for token in engine.generate(ids, 16, {"temperature": 0}, threading.Event()))
405        if count < 1:
406            raise ProfileError("candidate engine produced no tokens in smoke generation", 6)
407        return count
408    finally:
409        cal.close(engine)
410
411
412def _replace_bytes(path: Path, payload: bytes) -> None:
413    descriptor, temp = tempfile.mkstemp(prefix=f".{path.name}-", suffix=".tmp", dir=path.parent)
414    try:
415        with os.fdopen(descriptor, "wb") as stream:
416            stream.write(payload)
417            stream.flush()
418            os.fsync(stream.fileno())
419        _atomic_mod.replace(temp, path)
420    finally:
421        if os.path.exists(temp):
422            os.unlink(temp)
423
424
425def _settings_candidate(hardware_key: str, result: dict) -> tuple[Path, bytes | None, bytes]:
426    """Prepare setup's remembered calibration without accepting a corrupt store."""
427    target = _full_folder("setup").settings_path()
428    try:
429        previous = target.read_bytes()
430        settings = json.loads(previous.decode("utf-8"))
431        if not isinstance(settings, dict):
432            raise ValueError
433    except FileNotFoundError:
434        previous, settings = None, {}
435    except (OSError, UnicodeError, ValueError):
436        raise ProfileError("setup settings could not be read safely; config unchanged", 5) from None
437    if previous is not None and len(previous) > MAX_REPORT_BYTES:
438        raise ProfileError("setup settings exceed the calibration rollback size limit; config unchanged", 5)
439    cal = settings.get("calibration")
440    if cal is None:
441        cal = {}
442        settings["calibration"] = cal
443    if not isinstance(cal, dict):
444        raise ProfileError("setup calibration store is invalid; config unchanged", 5)
445    cal[hardware_key] = {"settings": result["settings"], "tok_s": result["measurements"].get("tok_s"),
446                         "date": time.strftime("%Y-%m-%d")}
447    try:
448        proposed = (json.dumps(settings, indent=1, ensure_ascii=False, allow_nan=False) + "\n").encode("utf-8")
449    except (TypeError, ValueError):
450        raise ProfileError("setup settings cannot be serialized; config unchanged", 5) from None
451    if len(proposed) > MAX_REPORT_BYTES:
452        raise ProfileError("updated setup settings exceed the calibration rollback size limit; config unchanged", 5)
453    return target, previous, proposed
454
455
456def _backup_directory(path: Path, *, create: bool = False) -> Path:
457    directory = path.parent / ".strata-calibration-backups"
458    try:
459        if create:
460            _private_mkdir(directory, exist_ok=True)
461        details = directory.lstat()
462    except FileNotFoundError:
463        raise ProfileError("calibration backup directory is missing", 5) from None
464    except OSError as exc:
465        raise ProfileError(f"cannot access calibration backup directory ({type(exc).__name__})", 5) from None
466    if not stat.S_ISDIR(details.st_mode) or (os.name == "posix" and
467                                            (posix_owner.owner_only_wrong(directory, details))):
468        raise ProfileError(posix_owner.owner_only_text("calibration backup directory must be owner-only and not a symlink", directory), 5)
469    return directory
470
471
472def _application_paths(path: Path, report_id: str, *, create: bool = False) -> tuple[Path, Path, Path]:
473    directory = _backup_directory(path, create=create)
474    return (directory / f"{path.stem}-{report_id}.json",
475            directory / f"settings-{report_id}.json",
476            directory / f"{path.stem}-{report_id}.apply.json")
477
478
479def _sha256(payload: bytes | None) -> str | None:
480    return hashlib.sha256(payload).hexdigest() if payload is not None else None
481
482
483def _load_application(path: Path, report: dict) -> dict:
484    backup, settings_backup, manifest = _application_paths(path, report["report_id"])
485    try:
486        details = manifest.lstat()
487        if not stat.S_ISREG(details.st_mode) or details.st_size > MAX_APPLICATION_BYTES or \
488                (os.name == "posix" and (posix_owner.owner_only_wrong(manifest, details))):
489            raise ProfileError(posix_owner.owner_only_text("calibration application record is not an owner-only regular file", manifest), 5)
490        data = json.loads(manifest.read_text(encoding="utf-8"))
491    except FileNotFoundError:
492        raise ProfileError("calibration application record was not found", 5) from None
493    except (OSError, ValueError, UnicodeError) as exc:
494        if isinstance(exc, ProfileError):
495            raise
496        raise ProfileError(f"cannot read calibration application record ({type(exc).__name__})", 5) from None
497    expected_keys = {"schema_version", "kind", "report_id", "report_body_sha256", "source_config",
498                     "profile_revision", "before_config_sha256", "after_config_sha256",
499                     "settings_path", "before_settings_sha256", "after_settings_sha256"}
500    if not isinstance(data, dict) or set(data) != expected_keys or \
501            type(data.get("schema_version")) is not int or data["schema_version"] != 1 or \
502            data.get("kind") != "strata.engine.calibration.application" or \
503            data.get("report_id") != report["report_id"] or \
504            data.get("report_body_sha256") != report["body_sha256"] or \
505            data.get("source_config") != str(path) or \
506            data.get("profile_revision") != report["identity"].get("profile_revision") or \
507            not isinstance(data.get("settings_path"), str) or \
508            not Path(data["settings_path"]).is_absolute() or \
509            not (data.get("before_settings_sha256") is None or
510                 isinstance(data["before_settings_sha256"], str) and
511                 re.fullmatch(r"[0-9a-f]{64}", data["before_settings_sha256"])) or \
512            not isinstance(data.get("after_settings_sha256"), str) or \
513            not re.fullmatch(r"[0-9a-f]{64}", data["after_settings_sha256"]) or \
514            not all(isinstance(data.get(key), str) and re.fullmatch(r"[0-9a-f]{64}", data[key])
515                    for key in ("before_config_sha256", "after_config_sha256")) or \
516            data["before_config_sha256"] != report["identity"].get("source_sha256"):
517        raise ProfileError("calibration application record has an unsupported shape", 5)
518    try:
519        if data["settings_path"] != str(_full_folder("setup").settings_path()):
520            raise ProfileError("setup settings path changed since calibration apply", 5)
521    except (OSError, ValueError):
522        raise ProfileError("setup settings path is unavailable", 5) from None
523    return {**data, "backup": backup, "settings_backup": settings_backup, "manifest": manifest}
524
525
526def apply_result(ref: str, report_path: Path, *, exclusive_ack: bool = False, smoke=None,
527                 expected_report_sha256: str | None = None) -> dict:
528    """Apply a reviewed result after a candidate smoke test; retain prior config."""
529    if not exclusive_ack:
530        raise ProfileError("calibration apply requires an exclusive-access acknowledgement")
531    path, profile, revision, cfg = _target(ref)
532    with profiles._lock(_lock_name(path)), _managed_exclusive():
533        return _apply_locked(ref, path, profile, revision, cfg, report_path, smoke=smoke,
534                             expected_report_sha256=expected_report_sha256)
535
536
537def _apply_locked(ref: str, path: Path, profile: dict | None, revision: str | None, cfg: dict,
538                  report_path: Path, *, smoke, expected_report_sha256: str | None) -> dict:
539    _exclusive_preflight(cfg, profile)
540    if expected_report_sha256 is not None and \
541            load_report(report_path)["body_sha256"] != expected_report_sha256:
542        raise ProfileError("calibration report changed after review; review again", 6)
543    preview = review(ref, report_path)
544    if not preview["applicable"]:
545        raise ProfileError("calibration report is stale: " + ", ".join(preview["reasons"]), 6)
546    report = load_report(report_path)
547    if expected_report_sha256 is not None and report["body_sha256"] != expected_report_sha256:
548        raise ProfileError("calibration report changed after review; review again", 6)
549    settings_path, previous_settings, new_settings = _settings_candidate(report["identity"]["hardware_key"], report)
550    source = path.read_bytes()
551    if hashlib.sha256(source).hexdigest() != report["identity"]["source_sha256"]:
552        raise ProfileError("run config changed before calibration apply", 6)
553    candidate = copy.deepcopy(cfg)
554    candidate["args"] = preview["after_args"]
555    from strata_control import arg_layers
556    arg_layers.record_calibration(candidate, cfg, report["settings"])     # the origin is kept: a launch puts these over Auto again (#5132)
557    smoke_candidate = _runtime_cfg(candidate, profile)
558    candidate_bytes = (json.dumps(candidate, indent=1, ensure_ascii=False) + "\n").encode("utf-8")
559    if len(source) > MAX_REPORT_BYTES or len(candidate_bytes) > MAX_REPORT_BYTES:
560        raise ProfileError("run config exceeds the calibration rollback size limit; config unchanged", 5)
561    try:
562        token_count = smoke(smoke_candidate) if smoke else _smoke(smoke_candidate, path)
563    except ProfileError:
564        raise
565    except Exception as exc:
566        raise ProfileError(f"candidate smoke generation failed ({type(exc).__name__}); config unchanged", 6) from None
567    if type(token_count) is not int or token_count < 1:
568        raise ProfileError("candidate smoke generation produced no tokens; config unchanged", 6)
569    if path.read_bytes() != source:
570        raise ProfileError("run config changed during smoke generation; config unchanged", 6)
571    end_path, end_profile, end_revision, end_cfg = _target(ref)
572    if end_path != path or _identity(end_path, end_cfg, end_profile, end_revision) != report["identity"]:
573        raise ProfileError("engine, model or hardware changed during smoke generation; config unchanged", 6)
574    _private_mkdir(settings_path.parent, parents=True, exist_ok=True)
575    current_settings = settings_path.read_bytes() if settings_path.exists() else None
576    if current_settings != previous_settings:
577        raise ProfileError("setup settings changed during calibration; config unchanged", 6)
578    backup, settings_backup_path, manifest = _application_paths(path, report["report_id"], create=True)
579    if any(item.exists() or item.is_symlink() for item in (backup, settings_backup_path, manifest)):
580        raise ProfileError("calibration result already has application records; measure again", 6)
581    application = {"schema_version": 1, "kind": "strata.engine.calibration.application",
582                   "report_id": report["report_id"], "report_body_sha256": report["body_sha256"],
583                   "source_config": str(path), "profile_revision": revision,
584                   "before_config_sha256": _sha256(source), "after_config_sha256": _sha256(candidate_bytes),
585                   "settings_path": str(settings_path),
586                   "before_settings_sha256": _sha256(previous_settings),
587                   "after_settings_sha256": _sha256(new_settings)}
588    settings_backup = settings_backup_path if previous_settings is not None else None
589    written = []
590    try:
591        _write_new(backup, source)
592        written.append(backup)
593        if settings_backup is not None:
594            _write_new(settings_backup, previous_settings)
595            written.append(settings_backup)
596        _write_new(manifest, _report_bytes(application))
597        written.append(manifest)
598    except (OSError, ProfileError) as exc:
599        for item in written:
600            item.unlink(missing_ok=True)
601        raise ProfileError(f"cannot save calibration rollback evidence ({type(exc).__name__}); config unchanged", 6) from None
602    try:
603        if candidate_bytes != source:
604            _replace_bytes(path, candidate_bytes)
605        _replace_bytes(settings_path, new_settings)
606    except Exception as exc:
607        # Restore both stores if either write failed; backups remain for manual recovery.
608        failed = False
609        try:
610            _replace_bytes(path, source)
611        except OSError:
612            failed = True
613        try:
614            if previous_settings is None:
615                settings_path.unlink(missing_ok=True)
616            else:
617                _replace_bytes(settings_path, previous_settings)
618        except OSError:
619            failed = True
620        if failed:
621            raise ProfileError(f"calibration apply failed ({type(exc).__name__}); restore from {backup}", 6) from None
622        raise ProfileError(f"calibration apply failed ({type(exc).__name__}); config restored", 6) from None
623    return {"changed": candidate_bytes != source, "report_id": report.get("report_id"), "source_config": str(path),
624            "backup": str(backup), "settings_backup": str(settings_backup) if settings_backup else None,
625            "application_record": str(manifest),
626            "previous_sha256": hashlib.sha256(source).hexdigest(),
627            "current_sha256": hashlib.sha256(candidate_bytes).hexdigest(), "smoke_output_tokens": token_count,
628            "setup_settings_persisted": True}
629
630
631def _saved_bytes(path: Path, *, required: bool = True, owner_only: bool = False) -> bytes | None:
632    try:
633        details = path.lstat()
634    except FileNotFoundError:
635        if not required:
636            return None
637        raise ProfileError("calibration rollback file is missing", 5) from None
638    if not stat.S_ISREG(details.st_mode) or details.st_size > MAX_REPORT_BYTES or \
639            (owner_only and os.name == "posix" and
640             (posix_owner.owner_only_wrong(path, details))):
641        raise ProfileError(posix_owner.owner_only_text("calibration rollback file must be a regular owner-only file under 2 MiB", path), 5)
642    try:
643        return path.read_bytes()
644    except OSError as exc:
645        raise ProfileError(f"cannot read calibration rollback file ({type(exc).__name__})", 5) from None
646
647
648def review_rollback(ref: str, report_path: Path) -> dict:
649    """Preview an exact rollback without touching engine or settings."""
650    path, profile, revision, cfg = _target(ref)
651    report = load_report(report_path)
652    application = _load_application(path, report)
653    reasons: list[str] = []
654    if report["source_config"] != str(path):
655        reasons.append("source_config_mismatch")
656    before_config = _saved_bytes(application["backup"], owner_only=True)
657    if _sha256(before_config) != application["before_config_sha256"]:
658        reasons.append("config_backup_changed")
659    settings_backup = _saved_bytes(application["settings_backup"], required=False, owner_only=True)
660    if _sha256(settings_backup) != application["before_settings_sha256"]:
661        reasons.append("settings_backup_changed")
662    current_config = _saved_bytes(path)
663    if _sha256(current_config) != application["after_config_sha256"]:
664        reasons.append("run_config_changed_after_apply")
665    current_settings = _saved_bytes(Path(application["settings_path"]), required=False)
666    if _sha256(current_settings) != application["after_settings_sha256"]:
667        reasons.append("setup_settings_changed_after_apply")
668    try:
669        identity = _identity(path, cfg, profile, revision)
670        expected = {**report["identity"], "source_sha256": application["after_config_sha256"]}
671        if identity != expected:
672            reasons.append("engine_model_hardware_or_profile_changed")
673    except ProfileError as exc:
674        reasons.append(f"identity_unavailable:{exc.exit_code}")
675    if _port_active(cfg):
676        reasons.append("profile_port_is_active")
677    return {"schema_version": 1, "report_id": report["report_id"],
678            "profile": profile["id"] if profile else None, "source_config": str(path),
679            "applicable": not reasons, "reasons": reasons,
680            "config_would_change": application["before_config_sha256"] != application["after_config_sha256"],
681            "setup_settings_would_be_removed": application["before_settings_sha256"] is None,
682            "backup": str(application["backup"]), "application_record": str(application["manifest"]),
683            "model_integrity": "metadata_only_unverified"}
684
685
686def rollback_result(ref: str, report_path: Path, *, exclusive_ack: bool = False, smoke=None,
687                    expected_report_sha256: str | None = None) -> dict:
688    """Smoke-test and restore the prior config/settings only if the applied state is still exact."""
689    if not exclusive_ack:
690        raise ProfileError("calibration rollback requires an exclusive-access acknowledgement")
691    path, profile, revision, cfg = _target(ref)
692    with profiles._lock(_lock_name(path)), _managed_exclusive():
693        _exclusive_preflight(cfg, profile)
694        if expected_report_sha256 is not None and \
695                load_report(report_path)["body_sha256"] != expected_report_sha256:
696            raise ProfileError("calibration report changed after review; review again", 6)
697        preview = review_rollback(ref, report_path)
698        if not preview["applicable"]:
699            raise ProfileError("calibration rollback is stale: " + ", ".join(preview["reasons"]), 6)
700        report = load_report(report_path)
701        if expected_report_sha256 is not None and report["body_sha256"] != expected_report_sha256:
702            raise ProfileError("calibration report changed after review; review again", 6)
703        application = _load_application(path, report)
704        before_config = _saved_bytes(application["backup"], owner_only=True)
705        before_settings = _saved_bytes(application["settings_backup"], required=False, owner_only=True)
706        current_config = _saved_bytes(path)
707        settings_path = Path(application["settings_path"])
708        current_settings = _saved_bytes(settings_path, required=False)
709        candidate = profiles.read_run_config(application["backup"])
710        smoke_candidate = _runtime_cfg(candidate, profile)
711        try:
712            token_count = smoke(smoke_candidate) if smoke else _smoke(smoke_candidate, path)
713        except ProfileError:
714            raise
715        except Exception as exc:
716            raise ProfileError(f"rollback smoke generation failed ({type(exc).__name__}); config unchanged", 6) from None
717        if type(token_count) is not int or token_count < 1:
718            raise ProfileError("rollback smoke generation produced no tokens; config unchanged", 6)
719        repeated = review_rollback(ref, report_path)
720        if not repeated["applicable"] or _saved_bytes(path) != current_config or \
721                _saved_bytes(settings_path, required=False) != current_settings:
722            raise ProfileError("config or setup settings changed during rollback smoke; config unchanged", 6)
723        try:
724            if before_config != current_config:
725                _replace_bytes(path, before_config)
726            if before_settings is None:
727                settings_path.unlink(missing_ok=True)
728            elif before_settings != current_settings:
729                _replace_bytes(settings_path, before_settings)
730        except Exception as exc:
731            failed = False
732            try:
733                _replace_bytes(path, current_config)
734            except OSError:
735                failed = True
736            try:
737                if current_settings is None:
738                    settings_path.unlink(missing_ok=True)
739                else:
740                    _replace_bytes(settings_path, current_settings)
741            except OSError:
742                failed = True
743            if failed:
744                raise ProfileError(f"calibration rollback failed ({type(exc).__name__}); "
745                                   f"manual recovery may be needed from {application['backup']}", 6) from None
746            raise ProfileError(f"calibration rollback failed ({type(exc).__name__}); applied state restored", 6) from None
747        return {"changed": before_config != current_config or before_settings != current_settings,
748                "report_id": report["report_id"], "source_config": str(path),
749                "restored_config_sha256": _sha256(before_config),
750                "setup_settings_removed": before_settings is None,
751                "smoke_output_tokens": token_count, "backup": str(application["backup"])}