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
18.0 KiB404 linesraw
1"""Owner-local receipts for reviewed Desktop calibration operations."""
2
3from __future__ import annotations
4
5import errno
6import json
7import math
8import os
9import stat
10import threading
11import time
12from contextlib import contextmanager
13from pathlib import Path
14
15from strata_control import calibration, journal, profiles
16from strata_control.profiles import ProfileError
17from strata_control import posix_owner
18
19
20KINDS = {"measure": "engine.calibrate.measure", "apply": "engine.calibrate.apply",
21         "rollback": "engine.calibrate.rollback"}
22STAGES = frozenset({"preflight", "loading", "pcie_share", "draft_floor", "confirmation",
23                    "cpu_workers", "expert_tier", "saving_report"})
24
25
26#: Windows byte-range locks are mandatory: a locked byte cannot be read through any other handle. The lock
27#: therefore sits far past the marker bytes, so another process can still read who holds the lease.
28WINDOWS_LOCK_OFFSET = 1 << 16
29
30def _directory(profile: str) -> Path:
31    return journal._directory(profile, create=True)
32
33
34def _lease_path(profile: str) -> Path:
35    return _directory(profile) / ".calibration-worker.lock"
36
37
38def _open_lease(profile: str, *, create: bool) -> int | None:
39    flags = os.O_RDWR | (os.O_CREAT if create else 0) | getattr(os, "O_NOFOLLOW", 0)
40    try:
41        descriptor = os.open(_lease_path(profile), flags, 0o600)
42    except FileNotFoundError:
43        return None
44    details = os.fstat(descriptor)
45    if not stat.S_ISREG(details.st_mode) or details.st_nlink != 1 or details.st_size > 32 or \
46            (os.name == "posix" and
47             (posix_owner.owner_only_wrong(_lease_path(profile), details))):
48        os.close(descriptor)
49        raise ProfileError(posix_owner.owner_only_text("calibration worker lease must be owner-only", _lease_path(profile)), 5)
50    return descriptor
51
52
53def _try_lock(descriptor: int) -> None:
54    if os.name == "nt":
55        import msvcrt
56        os.lseek(descriptor, WINDOWS_LOCK_OFFSET, os.SEEK_SET)
57        msvcrt.locking(descriptor, msvcrt.LK_NBLCK, 1)
58    else:
59        import fcntl
60        fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
61
62
63def _unlock(descriptor: int) -> None:
64    if os.name == "nt":
65        import msvcrt
66        os.lseek(descriptor, WINDOWS_LOCK_OFFSET, os.SEEK_SET)
67        msvcrt.locking(descriptor, msvcrt.LK_UNLCK, 1)
68    else:
69        import fcntl
70        fcntl.flock(descriptor, fcntl.LOCK_UN)
71
72
73@contextmanager
74def _worker_lease(profile: str, job_id: str):
75    descriptor = _open_lease(profile, create=True)
76    if descriptor is None:
77        raise ProfileError("calibration worker lease directory is unavailable", 5)
78    try:
79        try:
80            _try_lock(descriptor)
81        except OSError as exc:
82            if exc.errno in (errno.EAGAIN, errno.EACCES) or getattr(exc, "winerror", None) == 33:
83                raise ProfileError("another calibration worker is running for this profile", 6) from None
84            raise
85        try:
86            os.ftruncate(descriptor, 0)
87            os.lseek(descriptor, 0, os.SEEK_SET)
88            if os.write(descriptor, job_id.encode("ascii")) != 32:
89                raise ProfileError("cannot record calibration worker identity", 5)
90            os.fsync(descriptor)
91            yield
92        finally:
93            _unlock(descriptor)
94    finally:
95        os.close(descriptor)
96
97
98def _activity(profile: str, job_id: str) -> str:
99    descriptor = _open_lease(profile, create=False)
100    if descriptor is None:
101        return "untracked"
102    try:
103        try:
104            _try_lock(descriptor)
105        except OSError as exc:
106            if exc.errno not in (errno.EAGAIN, errno.EACCES) and getattr(exc, "winerror", None) != 33:
107                raise
108            os.lseek(descriptor, 0, os.SEEK_SET)
109            marker = os.read(descriptor, 32)
110            return "active" if marker == job_id.encode("ascii") else "other_active"
111        else:
112            try:
113                os.lseek(descriptor, 0, os.SEEK_SET)
114                return "ended" if os.read(descriptor, 32) == job_id.encode("ascii") else "untracked"
115            finally:
116                _unlock(descriptor)
117    finally:
118        os.close(descriptor)
119
120
121def _cancel_path(profile: str, job_id: str) -> Path:
122    return _directory(profile) / f"{job_id}.cancel"
123
124
125def _cancel_requested(profile: str, job_id: str) -> bool:
126    path = _cancel_path(profile, job_id)
127    try:
128        details = path.lstat()
129    except FileNotFoundError:
130        return False
131    if not stat.S_ISREG(details.st_mode) or details.st_nlink != 1 or details.st_size != 1 or \
132            (os.name == "posix" and
133             (posix_owner.owner_only_wrong(path, details))):
134        raise ProfileError("calibration cancellation marker is invalid", 5)
135    descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
136    try:
137        current = os.fstat(descriptor)
138        if current.st_ino != details.st_ino or os.read(descriptor, 2) != b"1":
139            raise ProfileError("calibration cancellation marker changed", 5)
140    finally:
141        os.close(descriptor)
142    return True
143
144
145@contextmanager
146def _cancel_watcher(profile: str, job_id: str):
147    requested = threading.Event()
148    stop = threading.Event()
149
150    def watch():
151        while not stop.wait(0.2):
152            try:
153                if _cancel_requested(profile, job_id):
154                    requested.set()
155                    return
156            except (OSError, ProfileError):
157                requested.set()  # Invalid private state stops the measurement safely.
158                return
159
160    thread = threading.Thread(target=watch, name="strata-calibration-cancel", daemon=True)
161    thread.start()
162    try:
163        yield requested
164    finally:
165        stop.set()
166        thread.join(timeout=1)
167
168
169def _progress_path(profile: str, job_id: str) -> Path:
170    return _directory(profile) / f"{job_id}.progress.json"
171
172
173def _save_progress(profile: str, job_id: str, stage: str, completed: int, total: int) -> None:
174    if stage not in STAGES or type(completed) is not int or type(total) is not int or \
175            not 0 <= completed <= total <= 1000:
176        raise ProfileError("calibration progress is invalid", 5)
177    value = {"schema_version": 1, "job_id": job_id, "stage": stage,
178             "completed": completed, "total": total, "updated_at": time.time()}
179    profiles._atomic(_progress_path(profile, job_id),
180                     (json.dumps(value, sort_keys=True, allow_nan=False) + "\n").encode("utf-8"))
181
182
183def _load_progress(profile: str, job_id: str) -> dict | None:
184    path = _progress_path(profile, job_id)
185    try:
186        details = path.lstat()
187    except FileNotFoundError:
188        return None
189    if not stat.S_ISREG(details.st_mode) or details.st_nlink != 1 or details.st_size > 1024 or \
190            (os.name == "posix" and
191             (posix_owner.owner_only_wrong(path, details))):
192        raise ProfileError(posix_owner.owner_only_text("calibration progress file must be owner-only", path), 5)
193    try:
194        value = json.loads(path.read_text(encoding="utf-8"))
195    except (OSError, UnicodeError, ValueError):
196        raise ProfileError("calibration progress file is invalid", 5) from None
197    if not isinstance(value, dict) or set(value) != {"schema_version", "job_id", "stage",
198                                                 "completed", "total", "updated_at"} or \
199            value["schema_version"] != 1 or value["job_id"] != job_id or \
200            value["stage"] not in STAGES or type(value["completed"]) is not int or \
201            type(value["total"]) is not int or not 0 <= value["completed"] <= value["total"] <= 1000 or \
202            type(value["updated_at"]) not in (int, float) or not math.isfinite(value["updated_at"]):
203        raise ProfileError("calibration progress file is invalid", 5)
204    return value
205
206
207def _intent(params: dict) -> dict:
208    return {"report_path": params["path"], "exclusive_ack": True,
209            "if_source_sha256": params["if_source_sha256"],
210            "if_report_sha256": params.get("if_report_sha256")}
211
212
213def create(profile: str, action: str, params: dict) -> dict:
214    """Create a receipt after management has checked every reviewed precondition."""
215    if action not in KINDS or not isinstance(params.get("job_id"), str) or \
216            not journal.ID.fullmatch(params["job_id"]):
217        raise ProfileError("calibration job ID or action is invalid", 2)
218    if _activity(profile, params["job_id"]) in ("active", "other_active"):
219        raise ProfileError("another calibration worker is running for this profile", 6)
220    record = journal.begin_direct(profile, KINDS[action], params["if_profile_revision"],
221                                  _intent(params), operation_id=params["job_id"])
222    return {"ok": True, "job_id": record["operation_id"], "action": action,
223            "path": record["intent"]["report_path"]}
224
225
226def _record(profile: str, job_id: str) -> dict:
227    if not isinstance(job_id, str) or not journal.ID.fullmatch(job_id):
228        raise ProfileError("calibration job ID must be a 32-character hex value", 2)
229    record = journal.load(profile, job_id)
230    if record.get("kind") not in KINDS.values() or record.get("origin") != "direct" or \
231            "if_source_sha256" not in record["intent"]:
232        raise ProfileError("calibration job ID does not identify a Desktop calibration", 5)
233    return record
234
235
236def run(profile: str, action: str, params: dict, work) -> tuple[str, dict]:
237    job_id = params["job_id"]
238    record = _record(profile, job_id)
239    if record["state"] != "running" or record["kind"] != KINDS[action] or \
240            record["profile_revision"] != params["if_profile_revision"] or \
241            record["intent"] != _intent(params):
242        raise ProfileError("calibration job no longer matches its reviewed request", 6)
243    with _worker_lease(profile, job_id):
244        return _run_owned(profile, action, job_id, work)
245
246
247def _run_owned(profile: str, action: str, job_id: str, work) -> tuple[str, dict]:
248    try:
249        result = work()
250        saved = journal.compact_direct_result(KINDS[action], result)
251        try:
252            journal.finish(profile, job_id, "succeeded", saved)
253        except ProfileError:
254            # A recovery read can reconcile a completed measurement first.
255            current = _record(profile, job_id)
256            if current["state"] != "succeeded" or current["result"] != saved:
257                raise
258        return job_id, result
259    except BaseException as exc:
260        if _record(profile, job_id)["state"] == "running":
261            unknown = isinstance(exc, (KeyboardInterrupt, SystemExit)) or \
262                (isinstance(exc, ProfileError) and exc.exit_code == 8)
263            cancelled = (action == "measure" and isinstance(exc, ProfileError) and
264                         exc.exit_code == 130)
265            journal.finish(profile, job_id, "completion_unknown" if unknown else "failed",
266                           {"error_type": type(exc).__name__,
267                            "cancelled": cancelled,
268                            "exit_code": exc.exit_code if isinstance(exc, ProfileError) else
269                            130 if unknown else 6})
270        raise
271
272
273def execute(profile: str, action: str, params: dict) -> dict:
274    """Run every preflight inside the receipt, including stale review rejection."""
275    from strata_control import management
276
277    def work() -> dict:
278        if action == "measure":
279            try:
280                _save_progress(profile, params["job_id"], "preflight", 0, 1)
281            except (OSError, ProfileError):
282                pass  # Progress is supplementary; the reviewed action still runs.
283        revision, digest = management._calibration_expected_source(profile, params)
284        if management._boolean(params["exclusive_ack"], "exclusive_ack") is not True:
285            raise ProfileError("calibration requires exclusive-access acknowledgement")
286        path = management._local_report_path(params["path"], "calibration report path")
287        if action == "measure":
288            with _cancel_watcher(profile, params["job_id"]) as cancel_event:
289                def progress(stage: str, completed: int, total: int):
290                    try:
291                        _save_progress(profile, params["job_id"], stage, completed, total)
292                    except (OSError, ProfileError):
293                        pass
294
295                progress("preflight", 1, 1)
296                report = calibration.measure(profile, path, exclusive_ack=True, say=lambda _: None,
297                                             expected_profile_revision=revision,
298                                             expected_source_sha256=digest, job_id=params["job_id"],
299                                             progress=progress, cancel_event=cancel_event)
300            return {"ok": True, "report_path": str(path), "report": report}
301        _, report = management._calibration_report(profile, str(path), "calibration report path")
302        expected = management._optional_revision(params["if_report_sha256"], "if_report_sha256")
303        if expected is None or report["body_sha256"] != expected:
304            raise ProfileError("calibration report changed after review; review again", 6)
305        if action == "apply":
306            return {"ok": True, "application": calibration.apply_result(
307                profile, path, exclusive_ack=True, expected_report_sha256=expected)}
308        return {"ok": True, "rollback": calibration.rollback_result(
309            profile, path, exclusive_ack=True, expected_report_sha256=expected)}
310
311    operation_id, outcome = run(profile, action, params, work)
312    if action == "measure":
313        report = outcome["report"]
314        return {"ok": True, "operation_id": operation_id, "path": params["path"],
315                "report_id": report["report_id"], "applicable": report["applicable"],
316                "settings": report["settings"]}
317    return {"ok": True, "operation_id": operation_id,
318            "application" if action == "apply" else "rollback":
319            outcome["application" if action == "apply" else "rollback"]}
320
321
322def cancel(profile: str, job_id: str) -> dict:
323    """Request a stop only for the exact active measurement worker."""
324    status(profile, job_id)  # Reconcile a finished report before accepting a new request.
325    record = _record(profile, job_id)
326    if record["kind"] != KINDS["measure"]:
327        raise ProfileError("only calibration measurement can be cancelled", 6)
328    if record["state"] != "running" or _activity(profile, job_id) != "active":
329        raise ProfileError("the exact calibration measurement is not active", 6)
330    path = _cancel_path(profile, job_id)
331    try:
332        descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL |
333                             getattr(os, "O_NOFOLLOW", 0), 0o600)
334    except FileExistsError:
335        _cancel_requested(profile, job_id)
336    else:
337        try:
338            os.write(descriptor, b"1")
339            os.fsync(descriptor)
340        finally:
341            os.close(descriptor)
342    return {"ok": True, "job_id": job_id, "state": "cancel_requested"}
343
344
345def status(profile: str, job_id: str) -> dict:
346    """Report a bounded receipt; only an exact report may recover measurement success."""
347    record = _record(profile, job_id)
348    action = next(name for name, kind in KINDS.items() if kind == record["kind"])
349    path = Path(record["intent"]["report_path"])
350    report = None
351    recovered = False
352    if action == "measure" and record["state"] in ("running", "succeeded"):
353        try:
354            candidate = calibration.load_report(path)
355            identity = candidate["identity"]
356            if (candidate.get("operation_id") == job_id and
357                    type(candidate.get("applicable")) is bool and
358                    identity.get("profile_id") == profile and
359                    identity.get("profile_revision") == record["profile_revision"] and
360                    identity.get("source_sha256") == record["intent"]["if_source_sha256"]):
361                report = candidate
362        except (ProfileError, OSError):
363            pass
364        if report is not None and record["state"] == "running":
365            try:
366                journal.finish(profile, job_id, "succeeded",
367                               {"ok": True, "report_path": str(path),
368                                "report_id": report["report_id"],
369                                "applicable": report["applicable"]})
370                recovered = True
371            except ProfileError:
372                pass
373            record = _record(profile, job_id)
374    result = None
375    if record["state"] == "succeeded":
376        saved = record["result"]
377        result = {"ok": True, "action": action, "operation_id": job_id,
378                  "report_id": saved.get("report_id")}
379        if action == "measure":
380            result.update(path=str(path), applicable=saved.get("applicable"),
381                          settings=report["settings"] if report is not None else {})
382        else:
383            result.update(changed=saved.get("changed"))
384            if action == "apply":
385                result["application_record"] = saved.get("application_record")
386            else:
387                result["setup_settings_removed"] = saved.get("setup_settings_removed")
388    activity = _activity(profile, job_id)
389    progress = _load_progress(profile, job_id) if action == "measure" else None
390    cancel_requested = _cancel_requested(profile, job_id) if action == "measure" else False
391    state = record["state"]
392    if state == "running":
393        state = "running" if activity == "active" else \
394                "launching" if time.time() - record["started_at"] < 10 else "completion_unknown"
395    elif state == "failed" and record["result"].get("cancelled") is True:
396        state = "cancelled"
397    return {"ok": True, "job": {"job_id": job_id, "action": action, "state": state,
398            "started_at": round(record["started_at"] * 1000),
399            "finished_at": round(record["finished_at"] * 1000) if record["finished_at"] is not None else None,
400            "result": result,
401            "error": "Calibration failed; inspect the saved operation and report." if state == "failed" else
402                     "Calibration completion needs inspection before retrying." if state == "completion_unknown" else None,
403            "outcome": "report_recovered" if recovered else "owner_journal",
404            "activity": activity, "progress": progress, "cancel_requested": cancel_requested}}