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
21.0 KiB414 linesraw
1"""Reviewed Desktop launch of the same serving benchmark used by the CLI."""
2
3from __future__ import annotations
4
5from strata_control.private_files import private_mkdir as _private_mkdir
6import hashlib
7import errno
8import os
9import re
10import stat
11import time
12from contextlib import contextmanager
13from pathlib import Path
14
15from strata_cli import bench
16from strata_cli.cli import _launch_plan, _source
17from strata_cli.client import ClientError, Endpoint
18from strata_control import journal, profiles, runtime
19from strata_control.profiles import ProfileError
20from strata_control import posix_owner
21
22
23#: Windows byte-range locks are mandatory: a locked byte cannot be read through any other handle. The lock
24#: therefore sits far past the marker bytes, so another process can still read who holds the lease.
25WINDOWS_LOCK_OFFSET = 1 << 16
26
27def _lease_file(profile: str, *, create: bool) -> Path | None:
28    if not profiles.PROFILE_ID.fullmatch(profile):
29        raise ProfileError("benchmark lease needs a saved profile")
30    directory = profiles.profile_dir()
31    if create:
32        _private_mkdir(directory, parents=True, exist_ok=True)
33    elif not directory.exists():
34        return None
35    details = directory.lstat()
36    if not stat.S_ISDIR(details.st_mode) or (os.name == "posix" and
37            (posix_owner.owner_only_wrong(directory, details))):
38        raise ProfileError(posix_owner.owner_only_text("benchmark lease directory must be owner-only", directory), 5)
39    return directory / f".bench-{profile}.lock"
40
41
42def _lease_descriptor(path: Path, *, create: bool) -> int:
43    flags = os.O_RDWR | (os.O_CREAT if create else 0)
44    if hasattr(os, "O_NOFOLLOW"):
45        flags |= os.O_NOFOLLOW
46    descriptor = os.open(path, flags, 0o600)
47    details = os.fstat(descriptor)
48    if not stat.S_ISREG(details.st_mode) or details.st_nlink != 1 or details.st_size > 65 or (os.name == "posix" and
49            (posix_owner.owner_only_wrong(path, details))):
50        os.close(descriptor)
51        raise ProfileError(posix_owner.owner_only_text("benchmark lease file must be owner-only", path), 5)
52    return descriptor
53
54
55def _lock(descriptor: int, *, initialize: bool = False) -> None:
56    if initialize and os.fstat(descriptor).st_size == 0:
57        os.lseek(descriptor, 0, os.SEEK_SET)
58        os.write(descriptor, b"0")
59    if os.name == "nt":
60        import msvcrt
61        os.lseek(descriptor, WINDOWS_LOCK_OFFSET, os.SEEK_SET)
62        msvcrt.locking(descriptor, msvcrt.LK_NBLCK, 1)
63    else:
64        import fcntl
65        fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
66
67
68def _unlock(descriptor: int) -> None:
69    if os.name == "nt":
70        import msvcrt
71        os.lseek(descriptor, WINDOWS_LOCK_OFFSET, os.SEEK_SET)
72        msvcrt.locking(descriptor, msvcrt.LK_UNLCK, 1)
73    else:
74        import fcntl
75        fcntl.flock(descriptor, fcntl.LOCK_UN)
76
77
78def _path_digest(path: Path) -> bytes:
79    return hashlib.sha256(os.fsencode(os.path.abspath(path))).hexdigest().encode("ascii")
80
81
82@contextmanager
83def benchmark_lease(profile: str, path: Path | None = None):
84    """Refuse overlapping local runs for one saved profile across host processes."""
85    target = _lease_file(profile, create=True)
86    descriptor = _lease_descriptor(target, create=True)
87    try:
88        try:
89            _lock(descriptor, initialize=True)
90        except OSError:
91            raise ProfileError("another benchmark is running for this saved profile", 6) from None
92        try:
93            marker = _path_digest(path) if path is not None else b"x" * 64
94            os.lseek(descriptor, 1, os.SEEK_SET)
95            if os.write(descriptor, marker) != len(marker):
96                raise ProfileError("cannot record benchmark lease identity", 5)
97            os.fsync(descriptor)
98            yield
99        finally:
100            _unlock(descriptor)
101    finally:
102        os.close(descriptor)
103
104
105def benchmark_activity(profile: str, path: Path) -> str:
106    """Check the exact saved run's lease, without using PID files or stale timestamps."""
107    target = _lease_file(profile, create=False)
108    if target is None:
109        return "untracked"
110    try:
111        descriptor = _lease_descriptor(target, create=False)
112    except FileNotFoundError:
113        return "untracked"
114    try:
115        if os.name == "nt" and os.fstat(descriptor).st_size == 0:
116            return "untracked"
117        try:
118            _lock(descriptor)
119        except OSError as exc:
120            if exc.errno not in (errno.EAGAIN, errno.EACCES) and getattr(exc, "winerror", None) != 33:
121                raise ProfileError("cannot inspect benchmark lease", 5) from None
122            os.lseek(descriptor, 1, os.SEEK_SET)
123            recorded = os.read(descriptor, 65)
124            if recorded == _path_digest(path):
125                return "active"
126            return "other_active" if re.fullmatch(rb"[0-9a-f]{64}", recorded) else "untracked"
127        else:
128            try:
129                os.lseek(descriptor, 1, os.SEEK_SET)
130                recorded = os.read(descriptor, 65)
131                return "ended" if recorded == _path_digest(path) else "untracked"
132            finally:
133                _unlock(descriptor)
134    finally:
135        os.close(descriptor)
136
137
138def request_cancel(profile: str, path: Path) -> dict:
139    """Request cancellation only for the exact active owner-local benchmark."""
140    directory = path.parent if path.name in ("results.json", "progress.json") else path
141    details = directory.lstat()
142    if not stat.S_ISDIR(details.st_mode) or (os.name == "posix" and
143            (posix_owner.owner_only_wrong(directory, details))):
144        raise ProfileError(posix_owner.owner_only_text("benchmark output directory must be owner-only", directory), 5)
145    if benchmark_activity(profile, directory) != "active":
146        raise ProfileError("the exact benchmark run is not active", 6)
147    if bench.progress(directory)["state"] != "running":
148        raise ProfileError("benchmark already saved its final report", 6)
149    marker = directory / "cancel.request"
150    try:
151        descriptor = os.open(marker, os.O_WRONLY | os.O_CREAT | os.O_EXCL |
152                             getattr(os, "O_NOFOLLOW", 0), 0o600)
153    except FileExistsError:
154        details = marker.lstat()
155        if not stat.S_ISREG(details.st_mode) or details.st_nlink != 1 or details.st_size != 1 or (os.name == "posix" and
156                (posix_owner.owner_only_wrong(marker, details))):
157            raise ProfileError("benchmark cancellation marker is invalid", 5)
158    else:
159        try:
160            os.write(descriptor, b"1")
161            os.fsync(descriptor)
162        finally:
163            os.close(descriptor)
164    current = bench.progress(directory)
165    if current["state"] == "report_saved":
166        raise ProfileError("benchmark already saved its final report", 6)
167    return {"ok": True, "path": str(directory / "results.json"),
168            "state": "cancelled" if current["state"] == "cancelled" else "cancel_requested"}
169
170
171def cancel_requested(directory: Path) -> bool:
172    """Read the private marker without treating a stale marker as process liveness."""
173    marker = directory / "cancel.request"
174    try:
175        details = marker.lstat()
176    except FileNotFoundError:
177        return False
178    if not stat.S_ISREG(details.st_mode) or details.st_nlink != 1 or details.st_size != 1 or (os.name == "posix" and
179            (posix_owner.owner_only_wrong(marker, details))):
180        raise ProfileError("benchmark cancellation marker is invalid", 5)
181    return True
182
183
184def _settings(profile: str, params: dict) -> tuple[dict, dict, Endpoint, Endpoint, Path]:
185    suite, concurrency, repeat = params["suite"], params["concurrency"], params["repeat"]
186    timeout, condition = params["request_timeout"], params["condition"]
187    if suite not in bench.SUITES:
188        raise ProfileError("unknown serving benchmark suite")
189    maximum = 64 if suite == "parallel-overload-v1" else 16
190    if (type(concurrency) is not int or not 1 <= concurrency <= maximum or
191            type(repeat) is not int or not 1 <= repeat <= 5 or
192            type(timeout) not in (int, float) or not 1 <= timeout <= 600):
193        raise ProfileError("benchmark workload settings are outside supported bounds")
194    if condition is not None and (not isinstance(condition, str) or
195                                  not re.fullmatch(r"[a-z][a-z0-9_-]{0,39}", condition)):
196        raise ProfileError("benchmark condition must be a lowercase name up to 40 characters")
197    phase_count = sum(1 if kind in ("warmup", "recovery", "cancel_active",
198                                    "cancel_queued", "cancel_prefill") else repeat
199                      for kind in bench.SUITES[suite])
200    if phase_count * (timeout + 30) > 1700:
201        raise ProfileError("benchmark workload exceeds the Desktop job limit; reduce timeout or repeats")
202    path = Path(params["path"])
203    if path.exists() or path.is_symlink():
204        raise ProfileError("benchmark output directory already exists", 2)
205    if not path.parent.is_dir():
206        raise ProfileError("benchmark output parent directory does not exist", 2)
207    source, saved, revision, cfg = _source(profile)
208    if saved is None or revision is None:
209        raise ProfileError("Desktop benchmark requires a saved profile")
210    launch, _ = _launch_plan(profile)
211    host = launch["effective"]["host"]
212    host = "127.0.0.1" if host in ("0.0.0.0", "::") else host
213    authority = f"[{host}]" if ":" in host and not host.startswith("[") else host
214    url = f"http://{authority}:{launch['effective']['port']}"
215    key = os.environ.get("STRATA_API_KEY")
216    endpoint = Endpoint(url, key, timeout=10)
217    telemetry = Endpoint(url, os.environ.get("STRATA_TELEMETRY_KEY") or key, timeout=3)
218    identity = {"profile": profile, "revision": revision, "source_config": str(source),
219                "source_sha256": hashlib.sha256(source.read_bytes()).hexdigest(),
220                "model_name": cfg.get("model_name"), "gpu": cfg.get("gpu")}
221    return launch, identity, endpoint, telemetry, path
222
223
224def plan(profile: str, params: dict) -> dict:
225    launch, identity, endpoint, telemetry, path = _settings(profile, params)
226    try:
227        snapshot = telemetry.snapshot()
228    except ClientError as exc:
229        raise ProfileError("benchmark telemetry is unavailable: " + str(exc), 5) from None
230    match = bench._managed_match(identity, endpoint.root, snapshot)
231    if not match["matched"]:
232        raise ProfileError("managed benchmark preflight failed: " + match["reason"], 5)
233    owner = runtime.status(profile)
234    owner_id = owner.get("owner_id")
235    if (owner.get("state") != "ready" or owner.get("instance_id") != match["instance_id"] or
236            owner.get("profile_revision") != identity["revision"] or
237            not isinstance(owner_id, str) or
238            not re.fullmatch(r"[0-9a-f]{32}", owner_id)):
239        raise ProfileError("benchmark owner identity is unavailable", 5)
240    if (snapshot.get("model") or {}).get("loaded") is not True:
241        raise ProfileError("benchmark needs a loaded model", 5)
242    work = snapshot.get("work") or {}
243    suite, count, repeat = params["suite"], params["concurrency"], params["repeat"]
244    if suite == "parallel-overload-v1":
245        limit, deadline = work.get("admission_limit"), work.get("queue_timeout_s")
246        if (type(limit) is not int or limit < 1 or type(deadline) not in (int, float) or
247                deadline <= 0 or count <= limit):
248            raise ProfileError("overload benchmark needs configured admission and concurrency above its limit", 5)
249    if suite in ("parallel-cancel-v1", "parallel-prefill-cancel-v1"):
250        slots = work.get("slots_effective")
251        if (type(slots) is not int or not 1 <= slots <= 16 or
252                type(work.get("client_disconnect_cancels")) is not int):
253            raise ProfileError("cancellation benchmark needs 1..16 slots and disconnect telemetry", 5)
254        if suite == "parallel-cancel-v1" and (count < slots or
255                type(work.get("max_queue")) is not int or work["max_queue"] < 1 or
256                type(work.get("queue_timeout_s")) not in (int, float) or
257                work["queue_timeout_s"] < 2):
258            raise ProfileError("cancellation benchmark needs a queue, two-second timeout and all slots", 5)
259        if suite == "parallel-prefill-cancel-v1" and (slots < 2 or count < 2):
260            raise ProfileError("prefill cancellation needs at least two slots and clients", 5)
261    requests = {"serving-smoke": 1 + repeat * (2 + count),
262                "parallel-mixed-v1": 1 + repeat * (2 + 2 * count),
263                "parallel-overload-v1": 2 + repeat * count,
264                "parallel-cancel-v1": (work.get("slots_effective") or 0) + 4,
265                "parallel-prefill-cancel-v1": 4}[suite]
266    return {"profile": profile, "profile_revision": identity["revision"],
267            "source_sha256": identity["source_sha256"], "owner_id": owner_id,
268            "instance_id": match["instance_id"], "endpoint": endpoint.root,
269            "model_id": (snapshot.get("model") or {}).get("id"),
270            "suite": suite, "concurrency": count, "repeat": repeat,
271            "request_timeout": params["request_timeout"], "condition": params["condition"],
272            "path": str(path), "phases": list(bench.SUITES[suite]),
273            "planned_requests": requests, "managed_match": True,
274            "api_credential_env": "STRATA_API_KEY", "telemetry_credential_env": "STRATA_TELEMETRY_KEY"}
275
276
277def create_job(profile: str, params: dict) -> dict:
278    """Save a bounded receipt before the Desktop launches its benchmark worker."""
279    job_id = params["job_id"]
280    intent = {key: value for key, value in params.items() if key != "job_id"}
281    _settings(profile, intent)
282    if benchmark_activity(profile, Path(intent["path"])) in ("active", "other_active"):
283        raise ProfileError("another benchmark is running for this saved profile", 6)
284    record = journal.begin_direct(profile, "bench.run", intent["if_profile_revision"], intent,
285                                  operation_id=job_id)
286    return {"ok": True, "job_id": record["operation_id"],
287            "path": str(Path(intent["path"]) / "results.json")}
288
289
290def _job_record(profile: str, job_id: str) -> dict:
291    if not isinstance(job_id, str) or not journal.ID.fullmatch(job_id):
292        raise ProfileError("benchmark job ID must be a 32-character hex value", 2)
293    record = journal.load(profile, job_id)
294    if record.get("kind") != "bench.run" or record.get("origin") != "direct":
295        raise ProfileError("benchmark job ID does not identify a benchmark", 5)
296    return record
297
298
299def _receipt_result(path: Path, report: dict) -> dict:
300    return {"ok": True, "report_path": str(path / "results.json"),
301            "run_id": report["run_id"], "instance_id": report["instance_id"],
302            "successful": report["successful"], "cancelled": report.get("cancelled", False)}
303
304
305def _report_matches_job(report: dict, intent: dict, profile: str) -> bool:
306    identity = report.get("profile_identity") or {}
307    return (isinstance(identity, dict) and
308            report.get("suite") == intent["suite"] and
309            report.get("condition") == intent["condition"] and
310            report.get("instance_id") == intent["if_instance_id"] and
311            report.get("planned_phases") == bench._planned_phase_kinds(intent["suite"], intent["repeat"]) and
312            identity.get("profile") == profile and
313            identity.get("revision") == intent["if_profile_revision"] and
314            identity.get("source_sha256") == intent["if_source_sha256"])
315
316
317def job_status(profile: str, job_id: str) -> dict:
318    """Recover a Desktop job from its journal, exact lease and private report."""
319    record = _job_record(profile, job_id)
320    directory = Path(record["intent"]["path"])
321    path = directory / "results.json"
322    if directory.exists() or directory.is_symlink():
323        details = directory.lstat()
324        if not stat.S_ISDIR(details.st_mode) or (os.name == "posix" and
325                (posix_owner.owner_only_wrong(directory, details))):
326            raise ProfileError(posix_owner.owner_only_text("benchmark output directory must be owner-only", directory), 5)
327    activity = benchmark_activity(profile, directory)
328    try:
329        phase = bench.progress(directory)
330    except ProfileError:
331        phase = None
332    report = None
333    if phase is not None and phase["state"] in ("report_saved", "cancelled"):
334        candidate = bench.load(directory)
335        if _report_matches_job(candidate, record["intent"], profile):
336            report = candidate
337        else:
338            phase = None
339        if report is not None and record["state"] == "running":
340            try:
341                journal.finish(profile, job_id, "succeeded", _receipt_result(directory, report))
342            except ProfileError:
343                pass  # The benchmark worker may have finished the same receipt.
344            record = _job_record(profile, job_id)
345    if report is not None:
346        state = "cancelled" if report.get("cancelled") else "completed"
347        result = {"ok": True, "path": str(path), "successful": report["successful"],
348                  "cancelled": report.get("cancelled", False), "run_id": report["run_id"],
349                  "instance_id": report["instance_id"], "suite": report["suite"]}
350    elif record["state"] == "succeeded" and isinstance(record.get("result"), dict):
351        saved = record["result"]
352        state = "cancelled" if saved.get("cancelled") else "completed"
353        result = {"ok": True, "path": str(path), "successful": saved.get("successful"),
354                  "cancelled": saved.get("cancelled"), "run_id": saved.get("run_id"),
355                  "instance_id": saved.get("instance_id"), "suite": record["intent"]["suite"]}
356    else:
357        result = None
358        state = ("failed" if record["state"] == "failed" else
359                 "running" if activity == "active" else "completion_unknown")
360        if (state == "completion_unknown" and record["state"] == "running" and phase is None and
361                time.time() - record["started_at"] < 10):
362            state = "launching"
363    return {"ok": True, "job": {"job_id": job_id, "state": state,
364            "started_at": round(record["started_at"] * 1000),
365            "finished_at": round(record["finished_at"] * 1000) if record["finished_at"] is not None else None,
366            "path": str(path), "result": result,
367            "error": ("Benchmark failed before a complete report was saved." if state == "failed" else
368                      "Benchmark completion needs inspection at the saved path."
369                      if state == "completion_unknown" else None),
370            "outcome": "report_recovered" if report is not None and record["state"] != "succeeded"
371                       else "owner_journal", "progress": phase,
372            "activity": activity, "cancel_requested": cancel_requested(directory) if directory.exists() else False}}
373
374
375def run(profile: str, params: dict) -> dict:
376    job_id = params.get("job_id")
377    if job_id is not None:
378        record = _job_record(profile, job_id)
379        if record["state"] != "running" or record["intent"] != {key: value for key, value in params.items()
380                                                    if key != "job_id"}:
381            raise ProfileError("benchmark job no longer matches its reviewed request", 6)
382    try:
383        with benchmark_lease(profile, Path(params["path"])):
384            planned = plan(profile, params)
385            for key in ("profile_revision", "source_sha256", "owner_id", "instance_id"):
386                if planned[key] != params["if_" + key]:
387                    raise ProfileError("benchmark target changed after review; review again", 6)
388            _, identity, endpoint, telemetry, path = _settings(profile, params)
389            try:
390                report = bench.run(endpoint, telemetry, path, suite=params["suite"],
391                                   concurrency=params["concurrency"], repeat=params["repeat"],
392                                   request_timeout=params["request_timeout"], condition=params["condition"],
393                                   profile_identity=identity, require_managed_match=True)
394            except ClientError as exc:
395                raise ProfileError("benchmark connection failed: " + str(exc), exc.exit_code) from None
396        if job_id is not None:
397            saved_result = _receipt_result(path, report)
398            try:
399                journal.finish(profile, job_id, "succeeded", saved_result)
400            except ProfileError:
401                # A concurrent recovery read may have reconciled this final report.
402                recorded = _job_record(profile, job_id)
403                if recorded["state"] != "succeeded" or recorded["result"] != saved_result:
404                    raise
405        return {"ok": True, "path": str(path / "results.json"),
406                "successful": report["successful"], "summary": bench.summary(report)}
407    except BaseException as exc:
408        if job_id is not None and _job_record(profile, job_id)["state"] == "running":
409            unknown = isinstance(exc, (KeyboardInterrupt, SystemExit)) or \
410                (isinstance(exc, ProfileError) and exc.exit_code == 8)
411            journal.finish(profile, job_id, "completion_unknown" if unknown else "failed",
412                           {"error_type": type(exc).__name__,
413                            "exit_code": exc.exit_code if isinstance(exc, ProfileError) else 130 if unknown else 6})
414        raise