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
17.1 KiB401 linesraw
1"""Applying a tuning recommendation: explicit, verified and reversible (checklist T07).
2
3A sweep ends at a report, and a report changes nothing. This module is the separate, deliberate step
4that turns one reviewed recommendation into a change to the active run configuration — and it is
5built around the fact that the most dangerous moment in tuning is the gap between measuring a
6configuration and running it for real.
7
8Four things make that safe, and each exists because of a specific way this goes wrong:
9
101. **Explicit, and only from a completed sweep.** There is no default and no automatic application.
11   The job must have reached a terminal state with a recommendation, and the report must still hash
12   to what was reviewed — a report edited after review is refused, because the review was of
13   different numbers.
14
152. **Identity is re-checked before anything is written.** A recommendation measured against one
16   engine or one model says nothing about another. If the engine digest, model digest, backend,
17   workload or context has changed since the sweep, the apply is refused *with the reason* rather
18   than applied to a configuration it was never measured against.
19
203. **The candidate is verified by running it.** The proposed configuration is started and required
21   to produce at least one token before the change is written. A configuration that boots but cannot
22   generate is the exact failure a benchmark cannot see, because the benchmark never ran the real
23   path.
24
254. **Reversal keeps the previous bytes.** The prior configuration is copied aside by digest before
26   the write, and rollback restores those bytes — so "apply" is never a one-way door.
27
28The active profile is untouched until the apply step: exploration and application are separate
29commands with separate leases, and neither can be triggered by the other.
30"""
31
32from __future__ import annotations
33
34import hashlib
35import json
36import os
37import shutil
38import tempfile
39import time
40from dataclasses import dataclass
41from pathlib import Path
42from typing import Any, Callable, Sequence
43
44from strata_control import user_args
45from strata_control import atomic as _atomic_mod
46
47SCHEMA_VERSION = 1
48
49
50class ApplyError(RuntimeError):
51    """An apply was refused. The message is the reason, and nothing was written."""
52
53    def __init__(self, message: str, code: int = 6) -> None:
54        super().__init__(message)
55        self.code = code
56
57
58def _sha256(payload: bytes) -> str:
59    return hashlib.sha256(payload).hexdigest()
60
61
62def _atomic_write(path: Path, payload: bytes) -> None:
63    """Replace a file's contents in one step, so a crash cannot leave it half-written."""
64    descriptor, temp = tempfile.mkstemp(prefix=f".{path.name}-", suffix=".tmp", dir=path.parent)
65    try:
66        with os.fdopen(descriptor, "wb") as stream:
67            stream.write(payload)
68            stream.flush()
69            os.fsync(stream.fileno())
70        _atomic_mod.replace(temp, path)
71    finally:
72        if os.path.exists(temp):
73            os.unlink(temp)
74
75
76# --------------------------------------------------------------------------- args and configs
77
78def args_to_argv(args: dict[str, Any]) -> list[str]:
79    """The recommendation's flags, as argv.
80
81    Order is sorted so the same recommendation always produces the same bytes: an apply that
82    reshuffled its own output would produce a different digest each time and break the rollback
83    comparison.
84    """
85    from strata_control.tuning import flag_argv
86    out: list[str] = []
87    for flag in sorted(args):
88        value = args[flag]
89        if value is None or value is False:
90            continue
91        if value is True:
92            out.append(flag)
93            continue
94        out.extend(flag_argv(flag, value))
95    return out
96
97
98def find_config_files(root: Path, *, limit: int = 200) -> list[Path]:
99    """Every `strata-*.json` run configuration under `root`.
100
101    The project keeps one configuration per installed model, and the naming is the project's own
102    (`strata-<model>.json`, as `setup.py` writes them). Anything that does not parse as a JSON object
103    with an `args` list is not a run configuration and is ignored rather than guessed at.
104    """
105    out: list[Path] = []
106    for path in sorted(Path(root).rglob("strata-*.json")):
107        if len(out) >= limit:
108            break
109        try:
110            data = json.loads(path.read_text(encoding="utf-8"))
111        except (OSError, json.JSONDecodeError):
112            continue
113        if isinstance(data, dict) and isinstance(data.get("args"), list):
114            out.append(path)
115    return out
116
117
118def apply_args_to_config(config: dict[str, Any], argv: Sequence[str]) -> dict[str, Any]:
119    """Set a recommendation's flags on a configuration, leaving everything else alone.
120
121    The rules are narrow on purpose:
122
123    * a flag the configuration already carries has **all** of its occurrences replaced, because a
124      half-replaced flag is a configuration that does nothing;
125    * a flag it does not carry is appended;
126    * no other key is touched, so unknown fields, aliases, `env` and `vision` survive — an apply
127      that dropped a user's API token would be worse than no apply at all.
128
129    `--flag value` and `--flag=value` are both produced as two argv elements, which the engine's
130    parser accepts either way.
131    """
132    candidate = json.loads(json.dumps(config))          # deep copy, values are JSON
133    existing = list(candidate.get("args") or [])
134
135    # The recommendation's flags, paired.
136    wanted: dict[str, list[str]] = {}
137    i = 0
138    while i < len(argv):
139        flag = argv[i]
140        value = argv[i + 1] if i + 1 < len(argv) and not argv[i + 1].startswith("--") else None
141        wanted[flag] = [flag] if value is None else [flag, value]
142        i += 2 if value is not None else 1
143
144    # Strip every occurrence of each recommended flag, then append the recommendation once.
145    stripped: list[str] = []
146    i = 0
147    while i < len(existing):
148        item = str(existing[i])
149        if item in wanted:
150            i += 2 if (i + 1 < len(existing) and not str(existing[i + 1]).startswith("--")) else 1
151            continue
152        stripped.append(existing[i])
153        i += 1
154
155    for flag in sorted(wanted):
156        stripped.extend(wanted[flag])
157    candidate["args"] = stripped
158    # The person's own options (user_args, strata_control/user_args.py) are kept, except the flags this recommendation sets: a tuning
159    # the person asks for is their newer choice.  The hand edits so far are recorded first, so writing "args" here loses none.
160    if candidate.get(user_args.WRITTEN_KEY) is not None or candidate.get(user_args.USER_KEY):
161        mine = user_args.capture(config)
162        mine = user_args.flat([g for g in user_args.groups(mine) if user_args.flag_of(g) not in wanted])
163        user_args.stamp(candidate, mine)
164        if user_args.WRITTEN_KEY not in config:
165            candidate.pop(user_args.WRITTEN_KEY, None)
166    return candidate
167
168
169# --------------------------------------------------------------------------- the plan
170
171@dataclass
172class ApplyPlan:
173    """What an apply would do, computed before anything is written."""
174
175    job_id: str
176    config_path: Path
177    before_args: list[str]
178    after_args: list[str]
179    added: list[str]
180    removed: list[str]
181    before_sha256: str
182    after_sha256: str
183    report_sha256: str
184    reasons: list[str]                                   # non-empty means it will not apply
185
186    @property
187    def applicable(self) -> bool:
188        return not self.reasons
189
190    def to_dict(self) -> dict[str, Any]:
191        return {
192            "job_id": self.job_id,
193            "config_path": str(self.config_path),
194            "before_args": self.before_args,
195            "after_args": self.after_args,
196            "added": self.added,
197            "removed": self.removed,
198            "before_sha256": self.before_sha256,
199            "after_sha256": self.after_sha256,
200            "report_sha256": self.report_sha256,
201            "applicable": self.applicable,
202            "reasons": self.reasons,
203        }
204
205
206def _diff(before: Sequence[str], after: Sequence[str]) -> tuple[list[str], list[str]]:
207    """Which flags appeared and which disappeared, as `flag value` strings."""
208    def pairs(items: Sequence[str]) -> dict[str, str]:
209        out: dict[str, str] = {}
210        i = 0
211        while i < len(items):
212            item = str(items[i])
213            if item.startswith("--") and i + 1 < len(items) and not str(items[i + 1]).startswith("--"):
214                out[item] = str(items[i + 1])
215                i += 2
216            else:
217                out[item] = ""
218                i += 1
219        return out
220
221    b, a = pairs(before), pairs(after)
222    added = [f"{k} {v}".strip() for k, v in sorted(a.items()) if b.get(k) != v]
223    removed = [f"{k} {v}".strip() for k, v in sorted(b.items()) if a.get(k) != v]
224    return added, removed
225
226
227def review_apply(*, job: dict[str, Any], config_path: Path,
228                 current_identity: dict[str, Any] | None,
229                 report_sha256: str | None = None) -> ApplyPlan:
230    """Decide whether this job's recommendation may be applied to this configuration.
231
232    Every refusal names what is wrong. An apply that silently proceeded on a stale or incompatible
233    report would be the single most damaging thing this module could do, so the checks are exhaustive
234    and each one is a reason rather than a bare `False`.
235    """
236    reasons: list[str] = []
237    report = job.get("report") or {}
238    job_id = str(job.get("id") or "")
239
240    if job.get("state") != "completed":
241        reasons.append(f"the sweep is {job.get('state')}, not completed; its result is not final")
242    if not report.get("recommendation_available") or not report.get("recommendation"):
243        reasons.append("the sweep recommended no change: " + str(report.get("reason") or "no reason recorded"))
244    if report.get("drift_material"):
245        drift = report.get("drift") or {}
246        reasons.append(
247            f"the machine drifted by {float(drift.get('relative', 0)) * 100:+.1f}% during the sweep, "
248            "so the comparison does not support a change")
249    if not config_path.exists():
250        reasons.append(f"no run configuration at {config_path}")
251        return ApplyPlan(job_id, config_path, [], [], [], [], "", "", "", reasons)
252
253    source = config_path.read_bytes()
254    before = json.loads(source.decode("utf-8"))
255    before_args = [str(x) for x in (before.get("args") or [])]
256
257    rec = report.get("recommendation") or {}
258    argv = args_to_argv(rec.get("args") or {})
259    if not argv:
260        reasons.append("the recommendation carries no flags, so there is nothing to apply")
261
262    candidate = apply_args_to_config(before, argv)
263    after_args = [str(x) for x in candidate["args"]]
264    added, removed = _diff(before_args, after_args)
265    if not added and not removed:
266        reasons.append("the configuration already carries this recommendation; nothing would change")
267
268    # The report has to be the one that was reviewed.
269    if report_sha256 is not None and report_sha256 != _report_digest(job):
270        reasons.append("the sweep report changed after review; review it again")
271
272    # And it has to have been measured on what is installed now.
273    if current_identity is not None:
274        from strata_control import tune_history
275        recorded = report.get("identity") or {}
276        if not recorded:
277            reasons.append("the sweep recorded no artifact identity, so it cannot be matched to what "
278                           "is installed now")
279        else:
280            differences = tune_history.incomparable_reasons(recorded, current_identity)
281            if differences:
282                reasons.append("the sweep was measured against a different configuration: "
283                               + ", ".join(differences))
284
285    after_bytes = (json.dumps(candidate, indent=1, ensure_ascii=False) + "\n").encode("utf-8")
286    return ApplyPlan(
287        job_id=job_id, config_path=config_path, before_args=before_args, after_args=after_args,
288        added=added, removed=removed, before_sha256=_sha256(source), after_sha256=_sha256(after_bytes),
289        report_sha256=_report_digest(job), reasons=reasons)
290
291
292def _report_digest(job: dict[str, Any]) -> str:
293    """A digest of the report, so a review cannot be reused for edited numbers."""
294    body = json.dumps(job.get("report") or {}, sort_keys=True, separators=(",", ":"))
295    return _sha256(body.encode("utf-8"))
296
297
298# --------------------------------------------------------------------------- applying
299
300def _application_dir(root: Path) -> Path:
301    d = Path(root) / "applications"
302    d.mkdir(parents=True, exist_ok=True)
303    return d
304
305
306def apply_recommendation(*, job: dict[str, Any], config_path: Path,
307                         current_identity: dict[str, Any] | None,
308                         state_dir: Path,
309                         verify: Callable[[dict[str, Any]], int] | None = None,
310                         expected_report_sha256: str | None = None) -> dict[str, Any]:
311    """Verify the candidate by running it, then write it — keeping the previous bytes.
312
313    `verify` receives the candidate configuration and must return the number of tokens generated.
314    A result below 1 is a refusal, not a warning: a configuration that cannot produce a token has not
315    been verified, whatever the sweep measured.
316    """
317    plan = review_apply(job=job, config_path=config_path, current_identity=current_identity,
318                        report_sha256=expected_report_sha256)
319    if not plan.applicable:
320        raise ApplyError("; ".join(plan.reasons))
321
322    before = json.loads(config_path.read_text(encoding="utf-8"))
323    candidate = apply_args_to_config(before, args_to_argv(
324        (job.get("report") or {}).get("recommendation", {}).get("args") or {}))
325
326    verified_tokens: int | None = None
327    if verify is not None:
328        try:
329            tokens = verify(candidate)
330        except Exception as exc:                                   # noqa: BLE001
331            raise ApplyError(
332                f"the candidate configuration failed verification ({type(exc).__name__}: {exc}); "
333                "the run configuration is unchanged") from None
334        if type(tokens) is not int or tokens < 1:
335            raise ApplyError("the candidate configuration generated no tokens; the run "
336                             "configuration is unchanged")
337        verified_tokens = int(tokens)
338
339    # Re-read after verification: a user edit during a long verification must not be overwritten.
340    if _sha256(config_path.read_bytes()) != plan.before_sha256:
341        raise ApplyError("the run configuration changed during verification; nothing was written")
342
343    application_id = f"{time.strftime('%Y%m%dT%H%M%SZ', time.gmtime())}-{plan.job_id[:12]}"
344    directory = _application_dir(state_dir) / application_id
345    if directory.exists():
346        raise ApplyError(f"an application record already exists at {directory}")
347    directory.mkdir(parents=True)
348    shutil.copy2(config_path, directory / "before.json")
349    (directory / "candidate.json").write_bytes(
350        (json.dumps(candidate, indent=1, ensure_ascii=False) + "\n").encode("utf-8"))
351
352    _atomic_write(config_path, (json.dumps(candidate, indent=1, ensure_ascii=False) + "\n").encode("utf-8"))
353
354    record = {
355        "schema_version": SCHEMA_VERSION,
356        "kind": "strata.tuning.application",
357        "application_id": application_id,
358        "job_id": plan.job_id,
359        "applied_at": time.time(),
360        "config_path": str(config_path),
361        "before_sha256": plan.before_sha256,
362        "after_sha256": plan.after_sha256,
363        "report_sha256": plan.report_sha256,
364        "added": plan.added,
365        "removed": plan.removed,
366        "verified_tokens": verified_tokens,
367        "rolled_back": False,
368    }
369    (directory / "application.json").write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8")
370    return {"application": record, "directory": str(directory), "plan": plan.to_dict()}
371
372
373def rollback(*, application_id: str, state_dir: Path) -> dict[str, Any]:
374    """Restore the configuration that was in place before an apply.
375
376    Refuses if the configuration has been edited since the apply, because restoring would then
377    discard a deliberate change: the user's edit wins, and the conflict is reported.
378    """
379    directory = _application_dir(state_dir) / application_id
380    record_path = directory / "application.json"
381    if not record_path.exists():
382        raise ApplyError(f"no application record at {record_path}", 404)
383    record = json.loads(record_path.read_text(encoding="utf-8"))
384    if record.get("rolled_back"):
385        raise ApplyError("this application has already been rolled back")
386    before = directory / "before.json"
387    if not before.exists():
388        raise ApplyError(f"the previous configuration was not retained at {before}")
389    target = Path(record["config_path"])
390    if not target.exists():
391        raise ApplyError(f"the run configuration is gone: {target}")
392    current = _sha256(target.read_bytes())
393    if current != record["after_sha256"]:
394        raise ApplyError(
395            "the run configuration changed after this apply, so restoring would discard a newer "
396            "change; nothing was written", 409)
397    _atomic_write(target, before.read_bytes())
398    record["rolled_back"] = True
399    record["rolled_back_at"] = time.time()
400    record_path.write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8")
401    return {"application": record, "restored": str(target)}