okami.mom/strata

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

Niko1221Merge main dbb2d168c (picture-reader fix, GGML_NO_BACKTRACE) into f-own-int2503b206b

main
26.0 KiB612 linesraw
1"""Measure one engine configuration, for the tuning job.
2
3The tuning job (`strata_control/tuning.py`) searches configurations and decides from numbers. This
4module is where those numbers come from: it boots the engine with one candidate's flags, sends the
5declared workload, reads the engine's own output, and returns measurements.
6
7It is deliberately separate from the job, and it is deliberately paranoid:
8
9* **It never invents a number.** If the engine does not start, produces no tokens, or finishes for a
10  reason other than a stop or a length, this raises with the engine's own words. The job records
11  that as a failed candidate — which is a real result — rather than as a slow one.
12* **It measures what the engine reports, not what the wall clock suggests.** The engine prints its
13  own prompt and decode milliseconds, so a measurement does not include this process's scheduling.
14  Client-observed timings are recorded separately and labelled, because they answer a different
15  question.
16* **It runs the declared workload every time**, with a fixed seed, so two candidates are compared on
17  the same work. A "faster" configuration that quietly did less is the classic tuning failure.
18
19The production engine protocol this reads (see `src/program/generate.cpp`):
20
21    READY <max_context> stop
22    PP <processed> <total> <ms> [<tok_s>]      prompt progress
23    T <token_id>                               one generated token
24    DONE <produced> <prompt_tokens> <prompt_ms> <decode_ms> <finish> <drafts_acc> <drafts_off> ...
25
26`finish` is `stop`, `length`, `cancel` or `nonfinite`. A `cancel` or `nonfinite` finish is not a
27measurement, and neither is a run whose `produced` is zero.
28"""
29
30from __future__ import annotations
31
32import os
33import re
34import subprocess
35import time
36from dataclasses import dataclass, field
37from pathlib import Path
38from typing import Any, Sequence
39
40from strata_control.childenv import quiet_crash_env
41
42#: A workload is fixed for the whole sweep: the same prompt, the same number of tokens to generate,
43#: the same sampling. Changing any of these between candidates invalidates the comparison.
44DEFAULT_WORKLOAD = {
45    "prompt_tokens": 512,
46    "max_new": 128,
47    "seed": 1,
48    "temperature": 0.0,      # greedy, so the work is deterministic
49}
50
51
52class MeasurementError(RuntimeError):
53    """The candidate could not be measured. The message is the engine's own reason."""
54
55
56@dataclass
57class EngineMeasurement:
58    """One candidate's measurements, with the units and the source of each.
59
60    `source` distinguishes what the engine reported from what this process observed, because they
61    are not interchangeable: the engine's `prompt_ms`/`decode_ms` exclude process startup and
62    scheduling, while `client_ttft_ms` includes everything a user would wait for.
63    """
64
65    tokens_per_s: float
66    #: Peak resident memory of the measured process tree, in MiB. Tuning that gets faster by
67    #: spilling or by thrashing is not an improvement, and the checklist asks for memory to travel
68    #: with the speed number so the trade is visible rather than hidden.
69    peak_memory_mib: float | None = None
70    prompt_tokens_per_s: float | None = None
71    decode_tokens_per_s: float | None = None
72    ttft_ms: float | None = None            # engine-reported: prompt_ms + the first decode step
73    client_ttft_ms: float | None = None     # observed here, includes process scheduling
74    produced: int = 0
75    prompt_tokens: int = 0
76    finish: str = ""
77    memory_mib: float | None = None
78    source: str = "engine-serve-protocol"
79    #: `protocol` measures the engine's own serve protocol; `api` drives the real HTTP API the agent
80    #: uses. They answer different questions, so the report must not present one as the other.
81    mode: str = "protocol"
82    raw: dict[str, Any] = field(default_factory=dict)
83
84    def to_metrics(self) -> dict[str, float]:
85        """The dict the job's `measure` callable must return.
86
87        Only finite numbers are emitted, so a missing measurement stays missing rather than becoming
88        a zero that a comparison might treat as a very slow result.
89        """
90        out: dict[str, float] = {"tokens_per_s": self.tokens_per_s}
91        for key in ("prompt_tokens_per_s", "decode_tokens_per_s", "ttft_ms", "client_ttft_ms",
92                    "memory_mib", "peak_memory_mib"):
93            value = getattr(self, key)
94            if isinstance(value, (int, float)):
95                out[key] = float(value)
96        return out
97
98
99# --------------------------------------------------------------------------- parsing
100
101_READY = re.compile(r"^READY\s+(\d+)\s+(\S+)\s*$")
102_PP = re.compile(r"^PP\s+(\d+)\s+(\d+)\s+([\d.]+)(?:\s+([\d.]+))?\s*$")
103_DONE = re.compile(r"^DONE\s+(.*)$")
104_TOKEN = re.compile(r"^T\s+(\d+)\s*$")
105
106
107def parse_done(line: str) -> dict[str, Any]:
108    """Parse a `DONE` line.
109
110    The line's tail is variable — the engine appends lookup-chain counters only when that option is
111    on — so the leading fields are read positionally and the rest is kept, never required.
112    """
113    m = _DONE.match(line.strip())
114    if not m:
115        raise MeasurementError(f"not a DONE line: {line[:120]!r}")
116    parts = m.group(1).split()
117    if len(parts) < 5:
118        raise MeasurementError(f"a DONE line with fewer than 5 fields: {line[:120]!r}")
119    try:
120        produced = int(parts[0])
121        prompt_tokens = int(parts[1])
122        prompt_ms = float(parts[2])
123        decode_ms = float(parts[3])
124    except ValueError as e:
125        raise MeasurementError(f"a DONE line with an unreadable number: {line[:120]!r}") from e
126    return {
127        "produced": produced,
128        "prompt_tokens": prompt_tokens,
129        "prompt_ms": prompt_ms,
130        "decode_ms": decode_ms,
131        "finish": parts[4],
132        "drafts_accepted": _int(parts[5]) if len(parts) > 5 else None,
133        "drafts_offered": _int(parts[6]) if len(parts) > 6 else None,
134        "tail": parts[7:],
135    }
136
137
138def _int(text: str) -> int | None:
139    try:
140        return int(text)
141    except ValueError:
142        return None
143
144
145def parse_ready(line: str) -> int:
146    m = _READY.match(line.strip())
147    if not m:
148        raise MeasurementError(f"not a READY line: {line[:120]!r}")
149    return int(m.group(1))
150
151
152def parse_pp(line: str) -> dict[str, float]:
153    m = _PP.match(line.strip())
154    if not m:
155        raise MeasurementError(f"not a PP line: {line[:120]!r}")
156    out = {"processed": float(m.group(1)), "total": float(m.group(2)), "ms": float(m.group(3))}
157    if m.group(4):
158        out["tok_s"] = float(m.group(4))
159    return out
160
161
162def measurement_from_protocol(done: dict[str, Any], *, tokens_seen: int,
163                              client_ttft_ms: float | None = None,
164                              ready_ms: float | None = None) -> EngineMeasurement:
165    """Turn the engine's own report into measurements.
166
167    Rejects a run that did not actually generate: a `cancel`, a `nonfinite`, a zero-token run and a
168    disagreement between the token count and the DONE line are all errors, not slow results.
169    """
170    finish = str(done.get("finish", ""))
171    produced = int(done.get("produced", 0))
172    if finish in ("cancel", "nonfinite"):
173        raise MeasurementError(f"the engine finished with '{finish}', which is not a measurement")
174    if produced <= 0:
175        raise MeasurementError("the engine produced no tokens")
176    if tokens_seen and tokens_seen != produced:
177        # The stream and the summary disagree, so neither can be trusted for a rate.
178        raise MeasurementError(
179            f"the engine reported {produced} tokens but streamed {tokens_seen}; refusing to score it")
180
181    decode_ms = float(done.get("decode_ms") or 0.0)
182    prompt_ms = float(done.get("prompt_ms") or 0.0)
183    prompt_tokens = int(done.get("prompt_tokens") or 0)
184
185    decode_per_s = (produced * 1000.0 / decode_ms) if decode_ms > 0 else None
186    prompt_per_s = (prompt_tokens * 1000.0 / prompt_ms) if prompt_ms > 0 and prompt_tokens else None
187
188    # What "tokens per second" means for the objective: the whole request's decoding rate. Prompt
189    # processing is reported separately because a candidate can move one without the other, and
190    # averaging them would hide exactly the trade the tuner is searching for.
191    total_ms = prompt_ms + decode_ms
192    overall = (produced * 1000.0 / total_ms) if total_ms > 0 else (decode_per_s or 0.0)
193
194    # The engine's own TTFT: reading the prompt plus the first decode step.
195    per_token_ms = (decode_ms / produced) if produced else None
196    ttft = (prompt_ms + per_token_ms) if per_token_ms is not None else (prompt_ms or None)
197
198    return EngineMeasurement(
199        tokens_per_s=overall,
200        prompt_tokens_per_s=prompt_per_s,
201        decode_tokens_per_s=decode_per_s,
202        ttft_ms=ttft,
203        client_ttft_ms=client_ttft_ms,
204        produced=produced,
205        prompt_tokens=prompt_tokens,
206        finish=finish,
207        raw=dict(done),
208    )
209
210
211# --------------------------------------------------------------------------- running
212
213class LineReader:
214    """Read lines from a pipe without ever blocking the caller.
215
216    `readline()` on a pipe has no timeout, so a `while time.monotonic() < deadline` loop around it
217    does not bound anything: an engine that starts and then says nothing hangs the measurement
218    forever. That is a real defect, not a hypothetical — it made the boot-timeout path unreachable
219    and hung this module's own tests.
220
221    A daemon reader thread moves the blocking read off the caller's thread, and the caller polls a
222    queue with a deadline it actually enforces.
223    """
224
225    def __init__(self, stream, name: str = "engine") -> None:
226        import queue
227        import threading
228        self._queue: "queue.Queue[str | None]" = queue.Queue()
229        self._stream = stream
230        self.name = name
231        self._thread = threading.Thread(target=self._pump, daemon=True,
232                                        name=f"strata-{name}-reader")
233        self._thread.start()
234
235    def _pump(self) -> None:
236        try:
237            for line in self._stream:
238                self._queue.put(line)
239        except (OSError, ValueError):
240            pass
241        finally:
242            # A sentinel so a reader knows the stream ended rather than that it is merely quiet.
243            self._queue.put(None)
244
245    def read_line(self, deadline: float) -> str | None:
246        """One line, or None if the deadline passed or the stream ended.
247
248        Raises `EOFError` when the stream has ended, so a caller can distinguish "nothing yet" from
249        "the engine is gone".
250        """
251        import queue
252        remaining = deadline - time.monotonic()
253        if remaining <= 0:
254            return None
255        try:
256            line = self._queue.get(timeout=remaining)
257        except queue.Empty:
258            return None
259        if line is None:
260            raise EOFError(f"the {self.name} stream ended")
261        return line
262
263    def drain_available(self) -> list[str]:
264        """Everything already buffered, without waiting."""
265        import queue
266        out: list[str] = []
267        while True:
268            try:
269                line = self._queue.get_nowait()
270            except queue.Empty:
271                return out
272            if line is None:
273                return out
274            out.append(line)
275
276
277
278def _windows_tree_peak_mib(pid: int) -> float | None:
279    """The same measurement on Windows: peak working set summed over the process and its children.
280
281    ``ps`` does not exist there, so the process list comes from a Toolhelp snapshot and each
282    process's peak from ``GetProcessMemoryInfo``. A process that cannot be opened (another
283    session, already gone) is skipped; if none can be read the answer is absent, not zero.
284    """
285    import ctypes
286    from ctypes import wintypes
287
288    class ProcessEntry(ctypes.Structure):
289        _fields_ = [("dwSize", wintypes.DWORD), ("cntUsage", wintypes.DWORD), ("th32ProcessID", wintypes.DWORD),
290                    ("th32DefaultHeapID", ctypes.c_size_t), ("th32ModuleID", wintypes.DWORD),
291                    ("cntThreads", wintypes.DWORD), ("th32ParentProcessID", wintypes.DWORD),
292                    ("pcPriClassBase", ctypes.c_long), ("dwFlags", wintypes.DWORD), ("szExeFile", ctypes.c_wchar * 260)]
293
294    class MemoryCounters(ctypes.Structure):
295        _fields_ = [("cb", wintypes.DWORD), ("PageFaultCount", wintypes.DWORD), ("PeakWorkingSetSize", ctypes.c_size_t),
296                    ("WorkingSetSize", ctypes.c_size_t), ("QuotaPeakPagedPoolUsage", ctypes.c_size_t),
297                    ("QuotaPagedPoolUsage", ctypes.c_size_t), ("QuotaPeakNonPagedPoolUsage", ctypes.c_size_t),
298                    ("QuotaNonPagedPoolUsage", ctypes.c_size_t), ("PagefileUsage", ctypes.c_size_t),
299                    ("PeakPagefileUsage", ctypes.c_size_t)]
300
301    kernel = ctypes.WinDLL("kernel32", use_last_error=True)
302    psapi = ctypes.WinDLL("psapi", use_last_error=True)
303    kernel.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
304    kernel.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]
305    kernel.Process32FirstW.argtypes = [wintypes.HANDLE, ctypes.POINTER(ProcessEntry)]
306    kernel.Process32NextW.argtypes = [wintypes.HANDLE, ctypes.POINTER(ProcessEntry)]
307    kernel.OpenProcess.restype = wintypes.HANDLE
308    kernel.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
309    kernel.CloseHandle.argtypes = [wintypes.HANDLE]
310    psapi.GetProcessMemoryInfo.argtypes = [wintypes.HANDLE, ctypes.POINTER(MemoryCounters), wintypes.DWORD]
311
312    snapshot = kernel.CreateToolhelp32Snapshot(0x2, 0)       # TH32CS_SNAPPROCESS
313    if snapshot in (None, wintypes.HANDLE(-1).value):
314        return None
315    rows: list[tuple[int, int]] = []
316    try:
317        entry = ProcessEntry()
318        entry.dwSize = ctypes.sizeof(ProcessEntry)
319        more = kernel.Process32FirstW(snapshot, ctypes.byref(entry))
320        while more:
321            rows.append((entry.th32ProcessID, entry.th32ParentProcessID))
322            more = kernel.Process32NextW(snapshot, ctypes.byref(entry))
323    finally:
324        kernel.CloseHandle(snapshot)
325    if pid not in {child for child, _ in rows}:
326        return None
327    wanted = {pid}
328    changed = True
329    while changed:
330        changed = False
331        for child, parent in rows:
332            if parent in wanted and child not in wanted:
333                wanted.add(child)
334                changed = True
335    total = 0
336    for member in wanted:
337        handle = kernel.OpenProcess(0x1000 | 0x0010, False, member)   # QUERY_LIMITED_INFORMATION | VM_READ
338        if not handle:
339            handle = kernel.OpenProcess(0x0400 | 0x0010, False, member)  # QUERY_INFORMATION | VM_READ
340        if not handle:
341            continue
342        try:
343            counters = MemoryCounters()
344            counters.cb = ctypes.sizeof(MemoryCounters)
345            if psapi.GetProcessMemoryInfo(handle, ctypes.byref(counters), counters.cb):
346                total += counters.PeakWorkingSetSize
347        finally:
348            kernel.CloseHandle(handle)
349    return round(total / (1024.0 * 1024.0), 1) if total else None
350
351
352def process_tree_peak_mib(pid: int) -> float | None:
353    """Peak resident memory of a process and its children, in MiB.
354
355    The engine is one process today, but a backend may spawn workers, so the tree is summed rather
356    than the root alone. `ps` is used because it reports each process's own peak (`rss` is current,
357    `vsz` is address space); when it is unavailable the memory is simply absent, which is the honest
358    answer and not a zero.
359    """
360    if os.name == "nt":
361        return _windows_tree_peak_mib(pid)
362    try:
363        out = subprocess.run(["ps", "-o", "rss=,pid=,ppid=", "-ax"], capture_output=True, text=True,
364                             timeout=5).stdout
365    except (OSError, subprocess.SubprocessError):
366        return None
367    rows: list[tuple[int, int, int]] = []
368    for line in out.splitlines():
369        parts = line.split()
370        if len(parts) != 3:
371            continue
372        try:
373            rows.append((int(parts[1]), int(parts[2]), int(parts[0])))
374        except ValueError:
375            continue
376    wanted = {pid}
377    changed = True
378    while changed:                      # transitive closure over ppid
379        changed = False
380        for child, parent, _ in rows:
381            if parent in wanted and child not in wanted:
382                wanted.add(child)
383                changed = True
384    total = sum(rss for child, _, rss in rows if child in wanted)
385    return round(total / 1024.0, 1) if total else None
386
387
388class EngineHarness:
389    """Boot the engine once per candidate and measure the declared workload.
390
391    The engine is a subprocess speaking line protocol over stdout, exactly as `serve/server.py`
392    drives it. One harness is created per candidate: a configuration that changes the expert cache
393    or the KV layout cannot be assumed to take effect in a running engine.
394    """
395
396    def __init__(self, engine: Path, args: dict[str, str], *, workload: dict[str, Any] | None = None,
397                 cwd: Path | None = None, env: dict[str, str] | None = None,
398                 boot_timeout_s: float = 600.0, request_timeout_s: float = 600.0) -> None:
399        self.engine = Path(engine)
400        self.args = dict(args)
401        self.workload = {**DEFAULT_WORKLOAD, **(workload or {})}
402        self.cwd = Path(cwd) if cwd else Path.cwd()
403        if env is None:
404            from strata_control.tuning import engine_env
405            env = engine_env(self.engine)       # an engine package's own folder first on the library path
406        self.env = env
407        self.boot_timeout_s = boot_timeout_s
408        self.request_timeout_s = request_timeout_s
409        self._proc: subprocess.Popen | None = None
410        self._reader: LineReader | None = None
411        self.last_measurement: EngineMeasurement | None = None
412        self._ready_ms: float | None = None
413        self._context: int | None = None
414
415    def _argv(self) -> list[str]:
416        from strata_control.tuning import engine_command, flag_argv
417        argv = [*engine_command(self.engine), "--serve"]
418        for flag, value in self.args.items():
419            argv.extend(flag_argv(flag, value))
420        return argv
421
422    def __enter__(self) -> "EngineHarness":
423        self.start()
424        return self
425
426    def __exit__(self, *exc: object) -> None:
427        self.close()
428
429    def start(self) -> None:
430        if not self.engine.exists():
431            raise MeasurementError(f"the engine binary is not at {self.engine}")
432        started = time.monotonic()
433        try:
434            from serve import lifeline       # the engine ends with this process, however this process ends
435            self._proc = lifeline.popen(
436                self._argv(), "engine", cwd=str(self.cwd), env=None if self.env is None else quiet_crash_env(dict(self.env)),
437                stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
438                text=True, errors="replace", bufsize=1)
439        except OSError as e:
440            raise MeasurementError(f"the engine could not be started: {e}") from e
441
442        self._reader = LineReader(self._proc.stdout, "engine")
443        deadline = time.monotonic() + self.boot_timeout_s
444        while True:
445            if time.monotonic() >= deadline:
446                if self._proc.poll() is not None:
447                    raise MeasurementError(
448                        f"the engine exited with code {self._exit_code()} before it was ready"
449                        + self._stderr_tail())
450                raise MeasurementError(
451                    f"the engine did not report READY within {self.boot_timeout_s:.0f}s")
452            try:
453                line = self._reader.read_line(deadline)
454            except EOFError:
455                raise MeasurementError(
456                    f"the engine exited with code {self._exit_code()} before it was ready"
457                    + self._stderr_tail()) from None
458            if line is None:
459                # Nothing yet. Only a *finished* process means failure; a slow boot does not.
460                if self._proc.poll() is not None:
461                    raise MeasurementError(
462                        f"the engine exited with code {self._exit_code()} before it was ready"
463                        + self._stderr_tail())
464                continue
465            line = line.strip()
466            if line.startswith("READY"):
467                self._context = parse_ready(line)
468                self._ready_ms = (time.monotonic() - started) * 1000.0
469                return
470            if line.startswith("ERR"):
471                raise MeasurementError(f"the engine refused to start: {line}")
472
473    def _exit_code(self) -> int | None:
474        """The engine's exit code, reaped if necessary.
475
476        `poll()` returns None until the process has been waited on, and a reader thread can observe
477        end-of-stream *before* that happens. Reporting "exited with code None" is useless in exactly
478        the case where the code matters most, so this waits briefly for the status.
479        """
480        if self._proc is None:
481            return None
482        if self._proc.poll() is None:
483            try:
484                self._proc.wait(timeout=5)
485            except subprocess.TimeoutExpired:
486                return None
487        return self._proc.returncode
488
489    def _stderr_tail(self, limit: int = 400) -> str:
490        if self._proc is None or self._proc.stderr is None:
491            return ""
492        try:
493            # Only meaningful once the process has ended; a running engine's stderr is still open.
494            if self._proc.poll() is None:
495                return ""
496            text = self._proc.stderr.read() or ""
497            return f"; stderr: {text[-limit:].strip()}"
498        except OSError:
499            return ""
500
501    def measure(self) -> EngineMeasurement:
502        """Send the workload and read one result. Raises `MeasurementError` on anything unusable."""
503        if self._proc is None or self._proc.poll() is not None:
504            raise MeasurementError("the engine is not running")
505        if self._proc.stdin is None or self._proc.stdout is None:
506            raise MeasurementError("the engine has no input/output pipe")
507
508        tokens = self._prompt_tokens()
509        flags = (f" temperature={self.workload['temperature']} seed={self.workload['seed']}")
510        request = f"GEN {int(self.workload['max_new'])}{flags} {','.join(str(t) for t in tokens)}\n"
511
512        client_start = time.monotonic()
513        try:
514            self._proc.stdin.write(request)
515            self._proc.stdin.flush()
516        except (OSError, BrokenPipeError) as e:
517            raise MeasurementError(f"the engine stopped accepting work: {e}" + self._stderr_tail()) from e
518
519        deadline = time.monotonic() + self.request_timeout_s
520        seen = 0
521        client_ttft: float | None = None
522        done: dict[str, Any] | None = None
523        while True:
524            if time.monotonic() >= deadline:
525                break
526            try:
527                raw = self._reader.read_line(deadline)
528            except EOFError:
529                raise MeasurementError(
530                    f"the engine exited with code {self._exit_code()} during the request"
531                    + self._stderr_tail()) from None
532            if raw is None:
533                if self._proc.poll() is not None:
534                    raise MeasurementError(
535                        f"the engine exited with code {self._exit_code()} during the request"
536                        + self._stderr_tail())
537                continue
538            line = raw.strip()
539            if _TOKEN.match(line):
540                seen += 1
541                if client_ttft is None:
542                    client_ttft = (time.monotonic() - client_start) * 1000.0
543            elif line.startswith("DONE"):
544                done = parse_done(line)
545                break
546            elif line.startswith("ERR"):
547                raise MeasurementError(f"the engine reported an error: {line}")
548        if done is None:
549            raise MeasurementError(
550                f"the engine produced no DONE line within {self.request_timeout_s:.0f}s")
551
552        result = measurement_from_protocol(done, tokens_seen=seen, client_ttft_ms=client_ttft,
553                                          ready_ms=self._ready_ms)
554        if self._proc is not None:
555            result.peak_memory_mib = process_tree_peak_mib(self._proc.pid)
556        result.mode = "protocol"
557        self.last_measurement = result
558        return result
559
560    def _prompt_tokens(self) -> Sequence[int]:
561        """The workload's token ids.
562
563        A real sweep substitutes the tokenizer's ids here. The default is a fixed, deterministic
564        sequence of the declared length: it exercises the same code path for every candidate, which
565        is what makes the comparison valid, and it cannot be accused of silently changing the work.
566        """
567        n = max(1, int(self.workload["prompt_tokens"]))
568        return [1000 + (i % 97) for i in range(n)]
569
570    def close(self) -> None:
571        if self._proc is None:
572            return
573        try:
574            if self._proc.poll() is None and self._proc.stdin is not None:
575                self._proc.stdin.write("QUIT\n")
576                self._proc.stdin.flush()
577                try:
578                    self._proc.wait(timeout=10)
579                except subprocess.TimeoutExpired:
580                    self._proc.kill()
581        except (OSError, ValueError):
582            try:
583                self._proc.kill()
584            except OSError:
585                pass
586        finally:
587            for stream in (self._proc.stdin, self._proc.stdout, self._proc.stderr):
588                try:
589                    if stream is not None:
590                        stream.close()
591                except OSError:
592                    pass
593            self._proc = None
594
595
596def make_measure(engine: Path, workload: dict[str, Any] | None = None,
597                 cwd: Path | None = None) -> "callable":
598    """Build the `measure` callable the tuning job expects.
599
600    The returned function boots the engine with the candidate's args, measures once, and returns the
601    metrics. It raises on anything unusable, which the job records as that candidate's status.
602    """
603    def measure(candidate) -> dict[str, float]:
604        harness = EngineHarness(engine, candidate.args if hasattr(candidate, "args") else candidate,
605                                workload=workload, cwd=cwd)
606        try:
607            harness.start()
608            return harness.measure().to_metrics()
609        finally:
610            harness.close()
611
612    return measure