okami.mom/strata

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

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
24.1 KiB531 linesraw
1"""Saved tuning presets: tune once, keep it.
2
3One store for the Terminal and the desktop app: a folder of small JSON files (``presets/`` beside the profiles), so tuning in
4one place covers the other. A preset holds
5
6* the settings the tuner found (``settings``: engine arguments, environment, per-request defaults),
7* what was measured (speeds and the baseline they were compared to),
8* the user's choices it was made for (model, context, KV format, "leave room" or "full performance", chat or coding), and
9* the identity it is valid for: the PC (graphics card and driver, memory, processor), the engine build and the model file.
10
11On every start the **active** preset for the model's choices is applied with no measurement (`overlay`, called by the
12server before it starts the engine). When the identity changed the preset says how much: a new graphics card or model file
13is a *hard* change (settings may not even start, so they are not applied on their own); a new driver or an engine build
14with a new ``tuning_epoch`` is a *soft* change (the preset still applies, and a 2-minute re-check is offered, never forced).
15
16Several named presets per model; activating one keeps the one it replaced, so **undo** restores it exactly. Nothing here
17starts an engine or changes anything but its own folder.
18"""
19
20from __future__ import annotations
21
22import json
23import os
24import re
25import tempfile
26import time
27import uuid
28from pathlib import Path
29from typing import Any
30
31from strata_control import tune_knobs, tune_machine
32from strata_control import atomic as _atomic_mod
33
34SCHEMA = "strata.preset/1"
35RECHECK_SET = "recheck/1"
36DEFAULT_LAST_OK_DAYS = 90
37
38
39class PresetError(ValueError):
40    """A preset is missing or invalid; the message is for the user."""
41
42
43# --------------------------------------------------------------------------- the folder
44
45def preset_dir() -> Path:
46    explicit = os.environ.get("STRATA_PRESET_DIR")
47    if explicit:
48        return Path(explicit).expanduser()
49    from strata_control import profiles
50    return profiles.profile_dir().parent / "presets"
51
52
53def _atomic(path: Path, payload: bytes) -> None:
54    path.parent.mkdir(parents=True, exist_ok=True)
55    fd, tmp = tempfile.mkstemp(prefix=f".{path.name}-", suffix=".tmp", dir=path.parent)
56    try:
57        with os.fdopen(fd, "wb") as fh:
58            fh.write(payload)
59            fh.flush()
60            os.fsync(fh.fileno())
61        _atomic_mod.replace(tmp, path)
62    finally:
63        if os.path.exists(tmp):
64            os.unlink(tmp)
65
66
67def _write_json(path: Path, obj: Any) -> None:
68    _atomic(path, (json.dumps(obj, indent=2, ensure_ascii=False, sort_keys=True) + "\n").encode("utf-8"))
69
70
71def _read_json(path: Path, default: Any) -> Any:
72    try:
73        return json.loads(path.read_text(encoding="utf-8-sig"))
74    except (OSError, ValueError):
75        return default
76
77
78def _path(pid: str) -> Path:
79    if not re.fullmatch(r"[0-9a-f]{32}", pid):
80        raise PresetError("that is not a preset id")
81    return preset_dir() / f"{pid}.json"
82
83
84# --------------------------------------------------------------------------- the choices a preset belongs to
85
86_QUANT = re.compile(r"(UD-Q\d_K_\w+|IQ\d_[A-Z]+|Q\d_K_[A-Z]+|Q\d_K|Q\d_\d|Q\d|BF16|F16)", re.I)
87
88
89def choices_from_config(cfg: dict[str, Any], *, use: str = "chat") -> dict[str, Any]:
90    """What the user chose, read from a run configuration: model, context, KV format, pictures, and whether they asked to
91    leave room for other work. The slot a preset is active in is made from these."""
92    args = [str(a) for a in cfg.get("args") or []]
93
94    def val(flag: str) -> str | None:
95        for i, a in enumerate(args):
96            if a == flag and i + 1 < len(args) and not args[i + 1].startswith("--"):
97                return args[i + 1]
98        return None
99
100    ctx = val("--max-context")
101    native = val("--native") or val("--model") or ""
102    quant = (_QUANT.search(Path(native).name) or _QUANT.search(str(cfg.get("model_name") or "")))
103    profile = cfg.get("ui_resource_profile")
104    reserve = cfg.get("vram_reserve_mib")
105    room = profile == "work"
106    return {
107        "model": str(cfg.get("model_name") or Path(native).stem or "model"),
108        "quant": quant.group(1).upper() if quant else None,
109        "model_file": native,
110        "context": int(ctx) if ctx and ctx.isdigit() else None,
111        "kv": val("--kv") or "int8",
112        "vision": bool(cfg.get("ui_vision_enabled")) or "--vision" in args,
113        "goal": "room" if room else "speed",
114        "reserve_mib": int(reserve) if isinstance(reserve, (int, float)) else 0,
115        "use": use,
116        "family": "qwen36" if (val("--mtp") or "").isdigit() else "flash-next",
117    }
118
119
120def default_name(choices: dict[str, Any]) -> str:
121    ctx = choices.get("context")
122    ctx_s = f"{ctx // 1024}K" if ctx else "?"
123    label = choices.get("quant") or choices.get("model") or "Model"
124    wish = "Work" if choices.get("goal") == "room" else "Full speed"
125    return f"{label} {ctx_s} – {wish}"
126
127
128def slot_key(choices: dict[str, Any], model_digest: str | None) -> str:
129    """Presets of the same model file, context, KV format, pictures and wish compete for the active place."""
130    return tune_machine.stable_hash({"m": model_digest, "ctx": choices.get("context"), "kv": choices.get("kv"),
131                                     "v": bool(choices.get("vision")), "g": choices.get("goal")})
132
133
134# --------------------------------------------------------------------------- identity and staleness
135
136def current_identity(cfg: dict[str, Any], *, exe: str | None = None, pcie: str | None = None) -> dict[str, Any]:
137    """The identity this PC, engine and model file have now."""
138    from strata_control import engine_component
139    args = [str(a) for a in cfg.get("args") or []]
140    files = [a for a in args if a.lower().endswith(".gguf")]
141    native = None
142    for i, a in enumerate(args):
143        if a == "--native" and i + 1 < len(args):
144            native = args[i + 1]
145    first = native or (files[0] if files else None)
146    engine_path = exe
147    if engine_path is None:
148        try:
149            ref = cfg.get("exe")
150            engine_path = engine_component.expand(ref, cfg, full=False) if ref else None
151        except Exception:  # noqa: BLE001
152            engine_path = cfg.get("exe")
153    return {"hardware": tune_machine.hardware_identity(pcie=pcie),
154            "engine": tune_machine.engine_identity(engine_path) if engine_path else {},
155            "model": tune_machine.model_identity([first]) if first and Path(first).is_file() else {}}
156
157
158def staleness(preset: dict[str, Any], now: dict[str, Any], *, today: float | None = None) -> dict[str, Any]:
159    """Compare a preset's identity with the current one: ``state`` is fresh, soft (re-check offered) or hard (settings
160    are not applied on their own; re-tune offered). ``reasons`` are plain words."""
161    old = preset.get("identity") or {}
162    hard: list[str] = []
163    soft: list[str] = []
164    oh, nh = (old.get("hardware") or {}).get("hard") or {}, (now.get("hardware") or {}).get("hard") or {}
165    if oh and nh:
166        if oh.get("gpus") != nh.get("gpus"):
167            hard.append("the graphics card changed")
168        if oh.get("cpu") != nh.get("cpu") or oh.get("logical") != nh.get("logical"):
169            hard.append("the processor changed")
170        a, b = oh.get("ram_gib"), nh.get("ram_gib")
171        if a and b and abs(a - b) / max(a, b) > 0.10:
172            hard.append("the amount of memory changed")
173        if oh.get("pcie") and nh.get("pcie") and oh["pcie"] != nh["pcie"]:
174            hard.append("the PCIe link changed")
175    om, nm = (old.get("model") or {}), (now.get("model") or {})
176    if om.get("sha256_shard1") and nm.get("sha256_shard1") and om["sha256_shard1"] != nm["sha256_shard1"]:
177        hard.append("the model file changed")
178    oe, ne = (old.get("engine") or {}), (now.get("engine") or {})
179    if oe.get("backend") and ne.get("backend") and oe["backend"] != ne["backend"]:
180        hard.append("the engine's graphics backend changed")
181    if oe and ne and int(oe.get("tuning_epoch") or 0) != int(ne.get("tuning_epoch") or 0):
182        soft.append("the engine was updated in a way that can change speed")
183    elif oe.get("version") and ne.get("version") and oe["version"] != ne["version"] and \
184            oe.get("sha256") and ne.get("sha256") and oe["sha256"] != ne["sha256"] and \
185            int(oe.get("tuning_epoch") or 0) != int(ne.get("tuning_epoch") or 0):
186        soft.append("the engine was updated")
187    os_, ns = (old.get("hardware") or {}).get("soft") or {}, (now.get("hardware") or {}).get("soft") or {}
188    if os_.get("driver") and ns.get("driver") and os_["driver"] != ns["driver"]:
189        soft.append("the graphics driver changed")
190    last_ok = ((preset.get("recheck") or {}).get("last_ok_epoch")) or preset.get("created_epoch")
191    if last_ok and (today or time.time()) - last_ok > DEFAULT_LAST_OK_DAYS * 86400:
192        soft.append("it has not been checked for a while")
193    if hard:
194        return {"state": "hard", "reasons": hard + soft}
195    if soft:
196        return {"state": "soft", "reasons": soft}
197    return {"state": "fresh", "reasons": []}
198
199
200# --------------------------------------------------------------------------- the store
201
202def _index() -> dict[str, Any]:
203    idx = _read_json(preset_dir() / "active.json", {})
204    return idx if isinstance(idx, dict) else {}
205
206
207def _save_index(idx: dict[str, Any]) -> None:
208    _write_json(preset_dir() / "active.json", idx)
209
210
211def load(pid: str) -> dict[str, Any]:
212    data = _read_json(_path(pid), None)
213    if not isinstance(data, dict) or data.get("schema") != SCHEMA:
214        raise PresetError("that preset does not exist")
215    return data
216
217
218def find(ref: str) -> dict[str, Any]:
219    """A preset by id, id prefix or exact name (case-insensitive); an ambiguous name is refused."""
220    items = list_presets()
221    exact = [p for p in items if p["id"] == ref]
222    if exact:
223        return exact[0]
224    by_prefix = [p for p in items if len(ref) >= 4 and p["id"].startswith(ref)]
225    by_name = [p for p in items if p["name"].lower() == ref.lower()]
226    found = by_name or by_prefix
227    if not found:
228        raise PresetError(f"no preset called '{ref}'")
229    if len(found) > 1:
230        raise PresetError(f"'{ref}' matches {len(found)} presets; use the id")
231    return found[0]
232
233
234def list_presets(*, model: str | None = None) -> list[dict[str, Any]]:
235    out: list[dict[str, Any]] = []
236    d = preset_dir()
237    if not d.is_dir():
238        return out
239    idx = _index()
240    active_ids = {v.get("active") for v in idx.values() if isinstance(v, dict)}
241    for f in sorted(d.glob("*.json")):
242        if f.name == "active.json":
243            continue
244        data = _read_json(f, None)
245        if not isinstance(data, dict) or data.get("schema") != SCHEMA:
246            continue
247        if model and model.lower() not in json.dumps(data.get("choices", {})).lower():
248            continue
249        data["active"] = data.get("id") in active_ids
250        out.append(data)
251    out.sort(key=lambda p: p.get("created_epoch", 0), reverse=True)
252    return out
253
254
255def _name_taken(name: str, exclude: str | None = None) -> bool:
256    return any(p["name"].lower() == name.lower() and p["id"] != exclude for p in list_presets())
257
258
259def _unique_name(name: str) -> str:
260    if not _name_taken(name):
261        return name
262    n = 2
263    while _name_taken(f"{name} ({n})"):
264        n += 1
265    return f"{name} ({n})"
266
267
268def create(result: dict[str, Any], *, choices: dict[str, Any], identity: dict[str, Any], name: str | None = None,
269           mode: str = "quick", activate: bool = True, base_args: dict[str, Any] | None = None) -> dict[str, Any]:
270    """Save a tune result as a named preset (active at once unless ``activate`` is False)."""
271    settings = result.get("settings") or {"args": {}, "env": {}, "per_request": {}}
272    # (a value only outside the tuner's tested range is kept, #3844; the never list still refuses)
273    problems, _outside = tune_knobs.check_setting_parts(settings.get("args") or {}, settings.get("env") or {},
274                                                        tune_knobs.Context(context_tokens=choices.get("context") or 32768,
275                                                                           family=choices.get("family") or "flash-next"))
276    if problems:
277        raise PresetError("these settings are outside the safe rules and cannot be saved: " + "; ".join(problems))
278    base = result.get("base") or {}
279    chosen = result.get("chosen") or {}
280    pid = uuid.uuid4().hex
281    now = time.time()
282    digest = (identity.get("model") or {}).get("sha256_shard1")
283    preset = {
284        "schema": SCHEMA, "id": pid, "name": _unique_name(name or default_name(choices)),
285        "created": time.strftime("%Y-%m-%dT%H:%M:%S%z", time.localtime(now)), "created_epoch": now,
286        "tuner": {"mode": mode, "version": "1", "seconds": result.get("seconds"), "outcome": result.get("outcome")},
287        "choices": choices, "identity": identity, "slot": slot_key(choices, digest),
288        "settings": {"args": settings.get("args") or {}, "env": settings.get("env") or {},
289                     "per_request": settings.get("per_request") or {}},
290        "answers": result.get("answers") or {"class": "exact", "fields": []},
291        "baseline": {"args": base_args or {}, "decode_tok_s": base.get("decode_tok_s"), "pp4k_tok_s": base.get("pp_tok_s"),
292                     "pairs": result.get("pairs"), "noise_aa_decode": (result.get("noise") or {}).get("aa_gap")},
293        "measured": {"decode_tok_s": chosen.get("decode_tok_s"), "pp4k_tok_s": chosen.get("pp_tok_s"),
294                     "vram_peak_mib": chosen.get("vram_used_mib"), "rss_peak_mib": chosen.get("rss_peak_mib"),
295                     "pairs": result.get("pairs"), "faster_pairs": result.get("faster_pairs"),
296                     "gain_pct": result.get("gain_pct"), "gain_decode_pct": result.get("gain_decode_pct"),
297                     "gain_pp_pct": result.get("gain_pp_pct")},
298        "noise": result.get("noise") or {},
299        "evidence": {"arms": result.get("arms"), "per_request": result.get("per_request"), "notes": result.get("notes"),
300                     "classes": result.get("classes")},
301        "recheck": {"request_set": RECHECK_SET, "last_ok": None, "last_ok_epoch": None, "last_result": None},
302        "previous": None,
303    }
304    _write_json(_path(pid), preset)
305    if activate:
306        activate_preset(pid)
307        preset = load(pid)
308    return preset
309
310
311def activate_preset(ref: str) -> dict[str, Any]:
312    """Make a preset the active one for its slot; the one it replaces is kept for undo."""
313    p = find(ref)
314    idx = _index()
315    entry = idx.get(p["slot"]) if isinstance(idx.get(p["slot"]), dict) else {"active": None, "history": []}
316    if entry.get("active") == p["id"]:
317        return p
318    if entry.get("active"):
319        entry.setdefault("history", []).append(entry["active"])
320        entry["history"] = entry["history"][-20:]
321    p["previous"] = entry.get("active")
322    entry["active"] = p["id"]
323    idx[p["slot"]] = entry
324    _write_json(_path(p["id"]), {k: v for k, v in p.items() if k != "active"})
325    _save_index(idx)
326    p["active"] = True
327    return p
328
329
330def deactivate_slot(slot: str) -> None:
331    """Back to the standard setup for this slot (the active preset is kept for undo)."""
332    idx = _index()
333    entry = idx.get(slot)
334    if isinstance(entry, dict) and entry.get("active"):
335        entry.setdefault("history", []).append(entry["active"])
336        entry["active"] = None
337        _save_index(idx)
338
339
340def undo(slot_or_ref: str) -> dict[str, Any] | None:
341    """Restore the preset that was active before the current one (None = the standard setup). ``slot_or_ref`` is a slot
342    key or any preset of the slot."""
343    idx = _index()
344    slot = slot_or_ref if slot_or_ref in idx else None
345    if slot is None:
346        slot = find(slot_or_ref)["slot"]
347    entry = idx.get(slot)
348    if not isinstance(entry, dict) or not entry.get("history") and entry.get("active") is None:
349        raise PresetError("there is nothing to undo")
350    hist = entry.get("history") or []
351    if not hist:
352        entry["active"] = None
353        _save_index(idx)
354        return None
355    prev = hist.pop()
356    entry["history"] = hist
357    entry["active"] = prev if _path(prev).exists() else None
358    _save_index(idx)
359    return load(entry["active"]) if entry["active"] else None
360
361
362def rename(ref: str, name: str) -> dict[str, Any]:
363    name = name.strip()
364    if not name or len(name) > 80 or re.search(r"[\r\n\0]", name):
365        raise PresetError("choose a name of 1 to 80 characters")
366    p = find(ref)
367    if _name_taken(name, p["id"]):
368        raise PresetError("another preset already has that name")
369    p["name"] = name
370    p.pop("active", None)
371    _write_json(_path(p["id"]), p)
372    return find(p["id"])
373
374
375def delete(ref: str) -> None:
376    p = find(ref)
377    idx = _index()
378    for slot, entry in list(idx.items()):
379        if not isinstance(entry, dict):
380            continue
381        entry["history"] = [h for h in entry.get("history", []) if h != p["id"]]
382        if entry.get("active") == p["id"]:
383            entry["active"] = entry["history"].pop() if entry["history"] else None
384    _save_index(idx)
385    try:
386        _path(p["id"]).unlink()
387    except OSError:
388        pass
389
390
391def export_preset(ref: str) -> dict[str, Any]:
392    p = find(ref)
393    p.pop("active", None)
394    return p
395
396
397def import_preset(data: dict[str, Any]) -> dict[str, Any]:
398    if not isinstance(data, dict) or data.get("schema") != SCHEMA:
399        raise PresetError("that file is not a Strata preset")
400    # (a value only outside the tuner's tested range is kept, #3844; the never list still refuses)
401    problems, _outside = tune_knobs.check_setting_parts((data.get("settings") or {}).get("args") or {},
402                                                        (data.get("settings") or {}).get("env") or {},
403                                                        tune_knobs.Context(context_tokens=(data.get("choices") or {}).get("context") or 32768))
404    if problems:
405        raise PresetError("the preset has settings outside the safe rules: " + "; ".join(problems))
406    data = dict(data)
407    data["id"] = uuid.uuid4().hex
408    data["name"] = _unique_name(str(data.get("name") or "Imported preset"))
409    data["previous"] = None
410    data.pop("active", None)
411    _write_json(_path(data["id"]), data)
412    return find(data["id"])
413
414
415def record_recheck(ref: str, outcome: dict[str, Any]) -> dict[str, Any]:
416    p = find(ref)
417    p.pop("active", None)
418    rc = dict(p.get("recheck") or {})
419    rc["last_result"] = outcome
420    if outcome.get("verdict") == "keep":
421        rc["last_ok"] = time.strftime("%Y-%m-%dT%H:%M:%S%z")
422        rc["last_ok_epoch"] = time.time()
423        # an identity that was soft-stale is refreshed once the settings were checked on this PC
424        if outcome.get("identity"):
425            p["identity"] = outcome["identity"]
426        better = outcome.get("measured")
427        if better and p.get("measured", {}).get("decode_tok_s") and better.get("decode_tok_s") and \
428                better["decode_tok_s"] > 1.03 * p["measured"]["decode_tok_s"]:
429            p["measured"].update({k: v for k, v in better.items() if v is not None})
430    p["recheck"] = rc
431    _write_json(_path(p["id"]), p)
432    return find(p["id"])
433
434
435# --------------------------------------------------------------------------- applying the active preset at every start
436
437def notice(preset: dict[str, Any]) -> str:
438    a = preset.get("answers") or {}
439    if a.get("default_repeatable") is False and a.get("class", "exact") in tune_knobs.ANSWER_NOTICE_UNSTEADY:
440        return tune_knobs.ANSWER_NOTICE_UNSTEADY[a.get("class", "exact")]
441    return tune_knobs.ANSWER_NOTICE.get(a.get("class", "exact"), "")
442
443
444def overlay(cfg: dict[str, Any], *, now: dict[str, Any] | None = None, use: str = "chat") -> tuple[dict[str, Any], dict[str, Any]]:
445    """The run configuration with the active preset for its choices put on top, and what was done.
446
447    No measurement happens here. A preset whose identity changed in a *hard* way is not applied (it says why); a *soft* change
448    applies it and marks it for a re-check. A setting on the never list (measured harmful) is left out, never applied; one
449    that is only outside the range the tuner tries is kept and listed in ``info["warnings"]``. Never raises:
450    a store that cannot be read means "no preset", and the engine starts with the configuration as it is."""
451    info: dict[str, Any] = {"applied": False}
452    try:
453        if not preset_dir().is_dir():
454            return cfg, info
455        choices = choices_from_config(cfg, use=use)
456        now = now or current_identity(cfg)
457        digest = (now.get("model") or {}).get("sha256_shard1")
458        entry = _index().get(slot_key(choices, digest))
459        if not isinstance(entry, dict) or not entry.get("active"):
460            return cfg, info
461        preset = load(entry["active"])
462        stale = staleness(preset, now)
463        info.update({"preset": {"id": preset["id"], "name": preset["name"]}, "state": stale["state"], "reasons": stale["reasons"]})
464        if stale["state"] == "hard":
465            info["why_not"] = "not applied: " + "; ".join(stale["reasons"])
466            return cfg, info
467        s = preset.get("settings") or {}
468        ctx = tune_knobs.Context(context_tokens=choices.get("context") or 32768, family=choices.get("family") or "flash-next")
469        problems, outside = tune_knobs.check_setting_parts(s.get("args") or {}, s.get("env") or {}, ctx)
470        if problems:
471            info["why_not"] = "not applied: " + "; ".join(problems)
472            return cfg, info
473        if outside:   # #3844: a value outside the range the tuner tries was chosen by the user: kept, with a warning
474            info["warnings"] = tune_knobs.keep_warnings(outside)
475        out = json.loads(json.dumps(cfg))
476        out["args"] = tune_knobs.apply_to_argv([str(a) for a in out.get("args") or []], s.get("args") or {})
477        if s.get("env"):
478            out["env"] = tune_knobs.apply_to_env(dict(out.get("env") or {}), s["env"])
479        if s.get("per_request"):
480            sampling = dict(out.get("sampling") or {})
481            sampling.setdefault("strata_tune", {k: v for k, v in s["per_request"].items() if v is not None})
482            out["sampling"] = sampling
483        info.update({"applied": True, "args": s.get("args"), "env": s.get("env"), "per_request": s.get("per_request"),
484                     "answers": preset.get("answers"), "notice": notice(preset)})
485        return out, info
486    except Exception as e:  # noqa: BLE001 - serving must never fail because of the preset store
487        info["error"] = f"{type(e).__name__}: {e}"
488        return cfg, info
489
490
491# --------------------------------------------------------------------------- history of every trial
492
493def history_path() -> Path:
494    return preset_dir() / "history.jsonl"
495
496
497def record_trials(trials: list[dict[str, Any]], *, hw_hash: str, model_digest: str | None, engine_sha: str | None) -> None:
498    rows = []
499    for t in trials:
500        args = {}
501        a = t.get("args") or []
502        rows.append({"at": t.get("at"), "hw": hw_hash, "model": model_digest, "engine": engine_sha, "label": t.get("label"),
503                     "sig": " ".join(str(x) for x in a) + "|" + json.dumps(t.get("env") or {}, sort_keys=True),
504                     "status": t.get("status"), "reason": t.get("reason"), "decode_tok_s": t.get("decode_tok_s"),
505                     "pp_tok_s": t.get("pp_tok_s"), "rss_peak_mib": t.get("rss_peak_mib")})
506    if not rows:
507        return
508    p = history_path()
509    p.parent.mkdir(parents=True, exist_ok=True)
510    with open(p, "a", encoding="utf-8") as fh:
511        for r in rows:
512            fh.write(json.dumps(r, sort_keys=True) + "\n")
513
514
515def bad_signatures(*, hw_hash: str, model_digest: str | None, engine_sha: str | None) -> set[str]:
516    """Candidates that did not start on this PC with this engine and model before (UNSUPPORTED or OOM): never retried.
517    A candidate that also has a PASS row for the same command here is not listed: one busy-card failure after it
518    worked must not switch it off for good (#3502)."""
519    bad: set[str] = set()
520    passed: set[str] = set()
521    try:
522        for line in history_path().read_text(encoding="utf-8").splitlines():
523            r = json.loads(line)
524            if r.get("hw") == hw_hash and r.get("model") == model_digest and r.get("engine") == engine_sha:
525                if r.get("status") in ("UNSUPPORTED", "OOM"):
526                    bad.add(r.get("label") or "")
527                elif r.get("status") == "PASS":
528                    passed.add(r.get("label") or "")
529    except (OSError, ValueError):
530        pass
531    return bad - passed