Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

terminal: strata_cli, strata_control, bin/strata and the terminal tests

Niko122164a91dcdc0b6
diff --git a/.github/workflows/terminal-minimal-server.yml b/.github/workflows/terminal-minimal-server.yml
new file mode 100644
index 000000000..e2c753161
--- /dev/null
+++ b/.github/workflows/terminal-minimal-server.yml
@@ -0,0 +1,65 @@
+name: Minimal serving runtime
+
+on:
+ push:
+ paths:
+ - .github/workflows/terminal-minimal-server.yml
+ - requirements.txt
+ - strata.py
+ - strata_cli/**
+ - strata_control/**
+ - serve/**
+ - tests/terminal/test_runtime.py
+ - tools/minimal_server_smoke.py
+ - tools/strata_tokenizer.py
+ pull_request:
+ paths:
+ - .github/workflows/terminal-minimal-server.yml
+ - requirements.txt
+ - strata.py
+ - strata_cli/**
+ - strata_control/**
+ - serve/**
+ - tests/terminal/test_runtime.py
+ - tools/minimal_server_smoke.py
+ - tools/strata_tokenizer.py
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ fake-engine:
+ name: Linux / runtime requirements only
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ steps:
+ - uses: actions/checkout@v7
+ with:
+ persist-credentials: false
+ - uses: actions/setup-python@v7
+ with:
+ python-version: '3.11'
+ - name: Install only pinned runtime requirements
+ shell: bash
+ run: |
+ python -m venv "$RUNNER_TEMP/strata-runtime-venv"
+ "$RUNNER_TEMP/strata-runtime-venv/bin/python" -m pip install -r requirements.txt
+ - name: Check fake-engine serving without terminal packages
+ shell: bash
+ run: |
+ python - <<'PY'
+ import os
+ import subprocess
+ from pathlib import Path
+
+ report = Path(os.environ['RUNNER_TEMP']) / 'minimal-server-smoke.json'
+ python = str(Path(os.environ['RUNNER_TEMP']) / 'strata-runtime-venv' / 'bin' / 'python')
+ subprocess.run([python, 'tools/minimal_server_smoke.py',
+ '--report', str(report)], check=True)
+ print(report.read_text())
+ PY
+ - name: Run full server suite without terminal packages
+ shell: bash
+ run: |
+ "$RUNNER_TEMP/strata-runtime-venv/bin/python" -m unittest discover -s serve -p 'test_*.py'
diff --git a/.github/workflows/terminal-portable-monitor.yml b/.github/workflows/terminal-portable-monitor.yml
new file mode 100644
index 000000000..905e7c40f
--- /dev/null
+++ b/.github/workflows/terminal-portable-monitor.yml
@@ -0,0 +1,115 @@
+name: Portable monitor client
+
+on:
+ push:
+ paths:
+ - .github/workflows/terminal-portable-monitor.yml
+ - packaging/monitor_bundle.py
+ - strata.py
+ - strata_cli/**
+ - strata_control/**
+ - tools/minimal_cli_smoke.py
+ - tools/portable_monitor_smoke.py
+ - tools/portable_monitor_pty_smoke.py
+ - requirements-monitor.txt
+ - LICENSE
+ pull_request:
+ paths:
+ - .github/workflows/terminal-portable-monitor.yml
+ - packaging/monitor_bundle.py
+ - strata.py
+ - strata_cli/**
+ - strata_control/**
+ - tools/minimal_cli_smoke.py
+ - tools/portable_monitor_smoke.py
+ - tools/portable_monitor_pty_smoke.py
+ - requirements-monitor.txt
+ - LICENSE
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ client:
+ name: ${{ matrix.os }} / Python ${{ matrix.python }}
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, windows-latest]
+ python: ['3.10', '3.11']
+ steps:
+ - uses: actions/checkout@v7
+ with:
+ persist-credentials: false
+ - uses: actions/setup-python@v7
+ with:
+ python-version: ${{ matrix.python }}
+ - name: Check source CLI without optional packages
+ shell: bash
+ run: |
+ python - <<'PY'
+ import os
+ import subprocess
+ import sys
+ from pathlib import Path
+
+ report = Path(os.environ['RUNNER_TEMP']) / 'minimal-cli-smoke.json'
+ subprocess.run([sys.executable, 'tools/minimal_cli_smoke.py',
+ '--report', str(report)], check=True)
+ print(report.read_text())
+ PY
+ - name: Build and smoke test without site packages
+ shell: bash
+ run: |
+ python - <<'PY'
+ import os
+ import subprocess
+ import sys
+ from pathlib import Path
+
+ bundle = Path(os.environ['RUNNER_TEMP']) / 'strata-monitor.pyz'
+ report = bundle.with_name('monitor-stdlib-smoke.json')
+ subprocess.run([sys.executable, 'packaging/monitor_bundle.py',
+ 'build', str(bundle)], check=True)
+ subprocess.run([sys.executable, 'tools/portable_monitor_smoke.py',
+ '--bundle', str(bundle), '--report', str(report)], check=True)
+ print(report.read_text())
+ PY
+ - name: Install optional Textual dependency
+ if: matrix.python == '3.11'
+ run: python -m pip install -r requirements-monitor.txt
+ - name: Smoke test packaged interactive Overview
+ if: matrix.python == '3.11'
+ shell: bash
+ run: |
+ python - <<'PY'
+ import os
+ import subprocess
+ import sys
+ from pathlib import Path
+
+ bundle = Path(os.environ['RUNNER_TEMP']) / 'strata-monitor.pyz'
+ report = bundle.with_name('monitor-interactive-smoke.json')
+ subprocess.run([sys.executable, 'tools/portable_monitor_smoke.py',
+ '--bundle', str(bundle), '--interactive',
+ '--report', str(report)], check=True)
+ print(report.read_text())
+ PY
+ - name: Check POSIX terminal restoration
+ if: matrix.os == 'ubuntu-latest' && matrix.python == '3.11'
+ shell: bash
+ run: |
+ python - <<'PY'
+ import os
+ import subprocess
+ import sys
+ from pathlib import Path
+
+ bundle = Path(os.environ['RUNNER_TEMP']) / 'strata-monitor.pyz'
+ report = bundle.with_name('monitor-pty-smoke.json')
+ subprocess.run([sys.executable, 'tools/portable_monitor_pty_smoke.py',
+ '--bundle', str(bundle), '--report', str(report)], check=True)
+ print(report.read_text())
+ PY
diff --git a/README.md b/README.md
index 81be3848b..328c6e006 100644
--- a/README.md
+++ b/README.md
@@ -192,6 +192,9 @@ every expert (Strata's arena mode, for example Q2_0 or IQ3_XXS on a 64 GB PC). O
```
Restart Strata (`START-HERE.bat` or `./setup.sh`) after the change. To undo, remove the two entries.
+Developers testing the terminal client in this source branch can start with the
+[terminal quick start](docs/TERMINAL_QUICKSTART.md). It covers read-only status and Monitor, plus explicit local
+profile, component, calibration and benchmark commands. The terminal client is still being qualified for release.
## Something went wrong?
diff --git a/bin/strata b/bin/strata
new file mode 100644
index 000000000..bc52d91ec
--- /dev/null
+++ b/bin/strata
@@ -0,0 +1,128 @@
+#!/bin/sh
+# Strata Terminal launcher.
+#
+# An end user must not need a development checkout, a global interpreter, pip or a compiler. This
+# script finds a usable Python in a fixed order and hands over to the CLI; it installs nothing and
+# downloads nothing.
+#
+# Search order:
+# 1. $STRATA_PYTHON — an explicit override, always wins
+# 2. <this dir>/python/bin/python3 — the private runtime shipped with the distribution
+# 3. A Python 3.10+ found on PATH — a developer convenience, never a requirement
+#
+# The private runtime is a *relocatable* CPython plus this distribution's dependencies, staged into
+# `python/` beside this script. `docs/work/QUALIFICATION-KIT.md` gives the staging command. When it
+# is absent the launcher still works anywhere a 3.10+ interpreter exists, and says so clearly rather
+# than failing obscurely.
+set -eu
+
+# Resolve this script's real directory, following symlinks, so `strata` can live on PATH.
+self=$0
+while [ -L "$self" ]; do
+ dir=$(CDPATH= cd -- "$(dirname -- "$self")" && pwd -P)
+ target=$(readlink "$self")
+ case $target in
+ /*) self=$target ;;
+ *) self=$dir/$target ;;
+ esac
+done
+HERE=$(CDPATH= cd -- "$(dirname -- "$self")" && pwd -P)
+
+pick_python() {
+ if [ -n "${STRATA_PYTHON:-}" ]; then
+ if [ -x "$STRATA_PYTHON" ]; then printf '%s\n' "$STRATA_PYTHON"; return 0; fi
+ echo "strata: STRATA_PYTHON=$STRATA_PYTHON is not executable" >&2
+ return 1
+ fi
+
+ # The private runtime shipped with the distribution.
+ #
+ # Two layouts are supported, and the relative depth differs between them:
+ # * an installed distribution: <root>/bin/strata with the runtime at <root>/python/
+ # * a source checkout: <root>/bin/strata with no bundled runtime at all
+ # So the parent directory is checked as well as this one. Getting this wrong is silent: the
+ # launcher falls through to whatever Python is on PATH and the bundle stops being self-contained.
+ for candidate in \
+ "$HERE/../python/bin/python3" "$HERE/python/bin/python3" \
+ "$HERE/../python/bin/python" "$HERE/python/bin/python"; do
+ if [ -x "$candidate" ]; then printf '%s\n' "$candidate"; return 0; fi
+ done
+
+ # Anything on PATH that is new enough, then the usual places an interpreter lives on macOS
+ # without being on a non-interactive PATH (Homebrew, python.org, and the interpreter a DeepSeek
+ # Harness installation already ships, which is a legitimate Python 3.12 to reuse rather than
+ # download a second copy of). Strata needs 3.10 or newer; macOS's own /usr/bin/python3 is 3.9 and
+ # is correctly rejected below.
+ for candidate in \
+ "$(command -v python3 2>/dev/null || true)" \
+ "$(command -v python 2>/dev/null || true)" \
+ /opt/homebrew/bin/python3 /usr/local/bin/python3 \
+ /Library/Frameworks/Python.framework/Versions/3.13/bin/python3 \
+ /Library/Frameworks/Python.framework/Versions/3.12/bin/python3 \
+ /Library/Frameworks/Python.framework/Versions/3.11/bin/python3 \
+ "/Applications/DeepSeek Harness.app/Contents/Resources/runtime/primary-runtime/dependencies/python/bin/python3" \
+ /usr/bin/python3
+ do
+ [ -n "$candidate" ] || continue
+ [ -x "$candidate" ] || continue
+ if "$candidate" -c 'import sys; raise SystemExit(0 if sys.version_info[:2] >= (3, 10) else 1)' 2>/dev/null; then
+ printf '%s\n' "$candidate"; return 0
+ fi
+ done
+
+ return 1
+}
+
+if ! PY=$(pick_python); then
+ cat >&2 <<'MSG'
+strata: no usable Python found.
+
+This distribution is meant to run on its own. If you are seeing this, the private runtime is
+missing from the install and no Python 3.10+ is on your PATH.
+
+ * Reinstall the distribution, which restores the bundled runtime, or
+ * set STRATA_PYTHON=/path/to/python3 (3.10 or newer), or
+ * install Python 3.10+ and run this launcher again.
+MSG
+ exit 5
+fi
+
+# Find the application root. Two layouts are supported so the same launcher works from a checkout
+# (`bin/strata` beside `strata.py`) and from an installed distribution (`<root>/bin/strata` with the
+# code under `<root>/`).
+if [ -f "$HERE/strata.py" ]; then
+ APP=$HERE
+elif [ -f "$HERE/../strata.py" ]; then
+ APP=$(CDPATH= cd -- "$HERE/.." && pwd -P)
+else
+ echo "strata: cannot find strata.py next to $HERE or its parent; the installation looks incomplete" >&2
+ exit 5
+fi
+
+# Only the API server needs third-party packages. `--help`, `status`, `monitor`, `timeskip` and
+# `tune plan` are deliberately stdlib-only — the CLI imports `serve.*` lazily inside the functions
+# that need it — so they must keep working on a bare interpreter. Checking them here anyway was a
+# real defect: it made `strata --help` refuse to run on an interpreter that could have answered it.
+#
+# A missing dependency is reported as a typed, actionable failure rather than a traceback, and
+# nothing is ever installed here.
+case "${1:-}" in
+ serve|bench)
+ if ! "$PY" - <<'PROBE' 2>/dev/null
+import importlib.util, sys
+need = ("jinja2", "yaml", "regex", "psutil", "requests", "numpy", "PIL")
+missing = [m for m in need if importlib.util.find_spec(m) is None]
+if missing:
+ sys.stderr.write("missing: " + ", ".join(missing) + "\n")
+ raise SystemExit(1)
+PROBE
+ then
+ echo "strata: the interpreter $PY is missing packages the API server needs." >&2
+ echo " Run: $PY -m pip install -r \"$APP/requirements.txt\"" >&2
+ echo " (strata status, monitor, timeskip and tune plan do not need them)" >&2
+ exit 5
+ fi
+ ;;
+esac
+
+exec "$PY" "$APP/strata.py" "$@"
diff --git a/docs/DEVELOPER_INTEGRATION_HANDOFF.md b/docs/DEVELOPER_INTEGRATION_HANDOFF.md
new file mode 100644
index 000000000..c226ea4a5
--- /dev/null
+++ b/docs/DEVELOPER_INTEGRATION_HANDOFF.md
@@ -0,0 +1,260 @@
+# Strata developer integration handoff
+
+11 October 2026 - execution brief for joining the current Strata engine, Desktop UI, serving CLI, monitor TUI and coding harness.
+
+**Purpose.** The developer should use the current UI handover zip, the owner's forthcoming DeepSeek harness repository and TUI zip, and the current GitHub repository to deliver one working product. This document adds the missing operator workflow: editable ways to restart a model, calibrate the engine, verify components and repeat a serving setup. Read it with `strata-development-work-plan.md`, `strata-architecture-plan.md` and `strata-terminal-implementation-plan.md`. Their release, security, model support and hardware gates still apply.
+
+## 1. What exists now
+
+| Input | Verified checkpoint | Developer action |
+| --- | --- | --- |
+| Current Strata source | Public `Niko1221/Strata` `main` fetched on 11 October 2026 at `61b3fb5dd3f1e8ec09cf7e4e05208bc6d3c46406`, including the newer replica, queue keepalive and request-validation work. The developer must refresh this identity at intake. | Keep the current engine scheduler and API behavior; review later upstream changes against the integration branch. |
+| Terminal milestone | Separate `Strata-TUI-CLI` checkout, branch `feat/terminal-cli-monitor-current`, merges that public `main` with the terminal milestone. It adds named serving profiles and separate monitor connections, editable recipes and journal, component checks with an optional live NVIDIA card inventory, calibration, benchmarks, POSIX owner runtime, a versioned owner-local runtime operation bridge, ready file and optional monitor bundle. `code` is a missing-component stub. | Split the integrated result into reviewable PRs. Qualify shared authority, recovery and Windows transport before release. |
+| Serving monitor | Versioned `/v1/telemetry` and optional six-view TUI. Its YASD-inspired Overview shows Serving, Performance, Batching/Parallel, four GPU histories, Requests and Activity together at 80+ columns; detailed views show request/slot/group/sensor rows, admission and queue counts, server first-token timing, reported layer ranges when a startup log is available, opt-in grouped-pipeline stage in-flight host spans and a bounded redacted request-activity snapshot for Logs. | Qualify batch/stage samples on native hardware, add GPU kernel occupancy and client TTFT, obtain a log-free topology source, and run real hardware qualification. Preserve `/metrics` and API clients. |
+| Existing calibration | The source CLI and native Desktop bridge offer separate decode-sweep plan, measure, apply and exact rollback operations. Legacy `setup.py --calibrate` still updates config and may start the engine; macOS hardware identity now reads RAM through `sysctl`. | Migrate the legacy setup path to the reviewed workflow; qualify progress, stop latency, receipt recovery and GPU exclusivity on target hosts. |
+| UI handover | Editable React and Node source from the 11 October ZIP is staged in `desktop/`. Opt-in, single-profile native mode uses shared Python operations for Serving Start/Stop/Restart/Verify, six-panel Monitor, Models and GGUF preflight, Components, Profile edits, reviewed managed Benchmark runs, exact-run cancellation, saved reports and reviewed Calibration measure/apply/rollback. The host checks local Origin/Host, bounds browser fields and retains telemetry credentials. It disables prototype mutations and inference. Chat, the original Tuning design and browser profile store remain prototype; benchmark jobs now have owner-only journal receipts, and their reports persist. | Confirm font rights, preserve the visual design and map remaining screens to shared services. |
+| Owner-supplied assets | The UI handover ZIP is available locally; the DeepSeek harness repository and owner's TUI ZIP have not been received or audited in this checkout. | Hash, license-check and map each asset at M0. Do not claim harness or final UI parity until integration passes. |
+
+**UI handover identity:** `strata-ui-handover-2026-10-11.zip` in the parent `output/` directory has SHA-256 `9491197bc5512a501a6ed5cbd2fcbce482c6cee9eb9bd1bb8aab1216fc2e4182`. Its ZIP CRC and all 684 file sizes and SHA-256 digests in `CONTENTS-MANIFEST.json` were verified. Recheck this identity when the developer receives the copy; license and runtime integration review remain separate gates.
+
+**Verified local checks:** 215 terminal tests passed on this macOS worktree with mock/fake engines and Textual installed. The merged public-main server suite passed 706 tests with 11 skipped. The terminal tests include private saved monitor connections, proxy-prefix and credential-reference resolution in both the source CLI and portable bundle, bounded engine-stage log parsing, untrusted map rejection, opt-in batch-window sample validation and profile override precedence, responsive live/recent request detail and scrolling, device/slot drilldowns, keyboard paging, stable selection and restart invalidation, prompt-reading progress, server first-engine-token display, frozen queue-age behavior and a portable monitor bundle exercised without site packages. A live mock request produced redacted, sequenced activity through the read-only telemetry key; malformed event fields were excluded from terminal rendering. The source and portable `logs` commands read the same bounded activity with a read-only credential; follow polling deduplicates transitions, reports sequence gaps and resets on an instance change. The live TUI now marks observed sequence gaps in Overview and Logs, preserves the display while frozen and clears an old gap when the serving instance changes. An offline monitor-only install, hash-pinned update, rollback, commit and removal were verified without changing the server; failure injection restored the active client, and unexpected files block removal. The parallel tests cover serial and batched queue deadlines, API error formats, waiting age, overload, active, queued and partial-prompt disconnects, and recovery. The benchmark CLI produced privacy-safe JSON reports against both mock and fake batched servers. A live mock stream stopped through the exact-run owner-local cancel action; the saved report and progress marked the run cancelled, and the lease released. A benchmark job receipt was read from a fresh owner-bridge process, and a final report reconciled an unfinished receipt. A distinct-file profile source switch and an in-place edit were previewed, digest-pinned and generation-verified on a POSIX-owned fake engine; failed activation restored the prior launch, including from a private old-config snapshot. A managed benchmark matched a POSIX-owned fake-engine launch before and after the workload; mismatches were refused before output or retained as failed evidence after the workload. Calibration rollback tests covered absent and existing setup settings, stale records, file-change races, symlink refusal and write-failure recovery. Direct saved-profile management records were checked alongside recipe records, including failed and uncertain outcomes and compact privacy-safe results. The POSIX host previewed a restart, then started, generation-verified, restarted and stopped an owned fake-engine instance, including failed-activation rollback and hard-killed host recovery after its child exited. Authenticated, lazy-model and failed-generation checks covered the new verification command and restart rollback. A typed recipe preview and run also restarted that owned instance. The standalone C++ batch/stage sampler passed a C++20 clang build/test on macOS, and a fake batched engine carried PSTAT through telemetry; native CUDA/HIP/SYCL builds and four-RTX-6000 performance remain unverified; record the exact card generation, VRAM, driver, model and topology for acceptance.
+
+Desktop calibration now creates an owner-only journal receipt before launching measure, apply or rollback. The browser can retrieve that receipt by job ID after a Desktop host restart. Measurement reports carry the exact job ID, so a saved report can reconcile a receipt left running after report write; a different report cannot. Preflight failures finish the receipt as failed. An exact owner-local worker lease now distinguishes an active job from an orphaned receipt. The measurement writes bounded stages and sample counts; Desktop can request a stop only for the exact active measurement, and the final receipt records whether cancellation occurred. Abrupt worker-death cleanup, stop latency on real hardware and target-host qualification remain open; see `docs/MANAGEMENT_PROTOCOL.md` for the wire contract.
+
+The normal setup dependency list now excludes CMake and Ninja. A local engine or image-encoder compile installs only missing pinned helpers from `requirements-build.txt`; existing system tools can be used offline. The dependency boundary passed focused Python 3.10 and 3.11 tests, and 92 hardware-independent setup checks passed on macOS. `doctor` reports the optional Textual monitor as missing, pinned-version present or version-unverified without importing it into serving. A fresh ready-made-engine install and local compile still need Windows/Linux qualification.
+
+Foreground `strata serve --output jsonl` now emits versioned starting, ready, stopping, draining and stopped records while human diagnostics remain on stderr. The fake-engine subprocess test generated one response and checked JSON-only stdout and exit codes for both SIGTERM (0) and Ctrl-C (130). All 43 parser leaves offering human/JSON output expose `--json`; focused source and portable-client tests check the shortcut and streaming rejection. Both clients reject JSON monitor output without `--once` before opening a connection. `--quiet` suppresses successful human output, keeps failures on stderr and retains JSON/JSONL records; a fake-engine process test checked quiet JSONL serving through one generation request. The direct legacy server entry point retains its existing human output. Windows console-stop and real-engine lifecycle qualification remain open.
+
+The terminal renderer now clips sanitized remote labels by display cells and pads fixed columns with display width. Focused cases cover combining marks, CJK device and request labels, regional-indicator flags and joined emoji across 110-, 80-, 60- and 40-column layouts. Bidi controls remain excluded. This is a stdlib fallback; ambiguous-width rendering still depends on the operator's terminal.
+
+A 30-minute synthetic 0.5-second Monitor soak also passed: it observed two disconnect windows and one instance restart, returned to a healthy snapshot, retained at most 32 activity and 50 request rows, kept one HTTP collection in flight and left the synthetic server readable after detach. The raw JSON and a 45-sample combined-process RSS series are in the transfer packet. This checks client stability; real-server and four-card overhead remain release gates.
+
+The interactive Monitor now opens in a connecting state without a blocking initial request. A failed poll labels the retained snapshot stale immediately and hides cached answer, prompt and aggregate output rates; repeated transport failures become disconnected. Authentication and telemetry-schema failures require a manual refresh after correction, while transport failures retry with bounded backoff and jitter. A reachable older server without telemetry or metrics keeps its accessible model/status fields under a clear `NO TELEMETRY` label; live work and rates remain unavailable. Headless and portable-client tests cover these states and recovery.
+
+A separate 60-second synthetic run on an earlier Monitor lifecycle revision opened through `CONNECTING`, observed `STALE` during two deliberate outages, recovered after a synthetic server restart, kept one HTTP collection in flight and detached without stopping the test server. The raw report is included separately from the earlier 30-minute soak.
+
+A fresh 60.29-second synthetic run with the output trend enabled also passed: two outages, one restart, 32 bounded valid output-rate samples, one maximum in-flight collection, recovered monitor state and a readable server after detach. Its raw report is `monitor-soak-60s-trend-2026-10-11.json`; it is client stability evidence, not GPU throughput evidence.
+
+Ten fresh fake batched-engine active/queued cancellation cycles also passed, with generation and recovery each time, engine child exit after unload, and closed HTTP listeners. The raw per-cycle report is in the transfer packet. Real-model/driver cycle qualification remains open.
+
+**Current public-main merge qualification.** The separate `feat/terminal-cli-monitor-current` branch merges public `main` at `61b3fb5d`. Its conflict resolution keeps upstream replica serving, serial queue keepalives, logit bias, request validation and reasoning defaults alongside the terminal ownership, bounded queue deadlines and read-only telemetry. On this macOS checkout, the merged server suite passed 706 tests with 11 skipped. The standalone batch/stage sampler passed a C++20 clang build with warnings treated as errors. A broad setup suite ran 465 tests with two failures and four errors; representative CUDA build and prebuilt-download failures were reproduced on a clean checkout of the same public `main`, and the HIP errors require a ROCm environment unavailable on this Mac. Treat setup and backend packaging as open qualification work. A fake two-replica HTTP test now correlates requests to global slots and globally distinct pipeline groups, with configured GPU-card labels; the 110- and 80-column Overview fixtures plus Engine and Hardware replica detail captures show that layout. The monitor now shows each child’s opt-in BSTAT rows/window and PSTAT host-stage span independently, with sample age. A child’s startup log can report its stage/layer ranges and selected card when launch visibility matches the configured replica group. Server-wide rows/window and stage timing stay unavailable because replica sample windows are separate; host spans are not GPU utilization. Native four-card correlation and performance remain unqualified.
+
+## 2. Required final behavior
+
+The Desktop UI and CLI must act on the **same installed profiles, runtime instances, component inventory and operation records**. The TUI is an attachable, read-only monitor for Server users. The coding CLI and Desktop chat must use the same harness session/approval service. The engine is not copied into each front end.
+
+```text
+Owner's UI controls CLI operator commands Monitor TUI
+ | | read only
+ +----------- typed local management API ------------+
+ |
+ profile store + operation journal + inventory
+ |
+ runtime worker / Python API / existing C++ engine
+ |
+ model pack + backend + telemetry
+
+Desktop Chat -------- shared harness session/approval service -------- strata code
+```
+
+The source-run CLI and a trusted Desktop host can call the same typed runtime path through `strata_control.management`; see `docs/MANAGEMENT_PROTOCOL.md` for the one-shot local JSON contract. Desktop start must take the profile revision and source digest from `runtime.start.plan`; the bridge checks both before journaling and the owner host checks them again before engine launch. Reviewed Stop and Restart commands pin the owner and instance IDs shown by their plans, checked again inside the owner before drain. Restart also pins the candidate profile revision and source digest. The imported Node host now has an internal `native-runtime.mjs` child-process adapter and an opt-in `/api/native/runtime` route for one host-configured saved profile. Native mode shows Serving, Monitor, Models, Profile and Components. Serving presents owner status and reviewed Start/Stop/Restart/Verify; a 90-second single-use server-side plan pins the action. Verify also pins the reviewed owner and instance IDs, rechecked inside the owner before an optional one-token generation; loading an unloaded model is a separate explicit choice. Monitor reads bounded `/v1/telemetry` from the owned local instance, checks its instance ID and keeps the read-only key on the host. Components calls `components.inspect` through the same Python management bridge as the CLI, bounds fields before browser delivery and runs the host GPU probe only after a manual request. Models calls `models.installed`, `models.inspect` and `models.import.plan` through that bridge; the browser sees bounded report fields and never receives a claim of verified engine compatibility. Profile reads the saved profile and installed run configs, then uses a single-use server-side review; Python rechecks the old revision and source digest before saving, and the running instance remains unchanged until a separate reviewed restart. A changed source or edited config triggers an explicit source-change review in Serving before the owner drains the old instance. The route requires a loopback bind and local Host/Origin, and action POSTs need JSON plus a custom header. This is a local preview boundary, not audited Desktop authentication. With `STRATA_NATIVE_PROFILE` set, all prototype HTTP mutations and `/v1` inference are rejected, the prototype monitor sampler is not started, and `STRATA_REAL_ENGINE=1` is incompatible. Its separate browser profile store and remaining prototype views must be mapped or retired after parity checks. There is one lifecycle authority per runtime instance. Every operation has an instance/profile ID, owner, plan, progress events, result, cancellation policy and audit record. The UI and CLI are clients of that authority; neither builds a second installer or calls arbitrary shell strings from a browser request. A monitor credential grants `/v1/telemetry` only. An inference credential cannot install, calibrate or run commands. Partner hosts such as Unsloth own their registered Strata runtime lifecycle through the separate host adapter contract.
+
+## 3. Easy-to-edit operational commands
+
+### User experience
+
+An owner should be able to choose a saved serving profile, edit its model/device/parallel/batch parameters, preview the effect, then run the same action from UI or CLI. Save profile revisions so a successful configuration can be restored. Surface the exact effective engine arguments, component versions and resolved paths in the preview with secrets redacted.
+
+**Proposed public grammar (target, not all implemented):**
+
+```text
+strata profile list
+strata profile create four-gpu --from-config CONFIG.json
+strata profile show four-gpu --effective --output json
+strata profile edit four-gpu
+strata profile set four-gpu parallel=8 max_queue=32 queue_timeout=15 batch_telemetry=true
+strata profile set four-gpu parallel=8 --plan
+strata profile use-config four-gpu --from-config /absolute/path/next-model.json --plan
+strata profile use-config four-gpu --from-config /absolute/path/next-model.json --if-revision PROFILE_REVISION
+strata profile validate four-gpu
+strata profile history four-gpu
+strata profile rollback four-gpu --to REVISION
+```
+
+Read-only monitor connections are separate from serving profiles. They store a server root, an optional proxy prefix and a credential environment-variable **name**, never its value:
+
+```text
+strata connection create work --url https://HOST --prefix /strata --credential-env STRATA_TELEMETRY_KEY
+strata connection set work prefix=/new-strata --plan
+strata connection set work prefix=/new-strata --if-revision CONNECTION_REVISION
+strata config show --effective --connection work --output json
+strata status --connection work --output json
+strata monitor --connection work
+strata logs --connection work --source runtime --follow --output jsonl
+```
+
+Runtime and calibration:
+
+```text
+strata runtime start --profile four-gpu --plan
+strata runtime start --profile four-gpu
+strata runtime restart --profile four-gpu --plan
+strata runtime restart --profile four-gpu --startup-wait 300
+strata runtime restart --profile four-gpu --allow-source-switch --plan
+strata runtime restart --profile four-gpu --allow-source-switch --if-profile-revision NEW_PROFILE_REVISION --if-source-sha256 CANDIDATE_SOURCE_SHA256 --if-owner-id CURRENT_OWNER_ID --if-instance-id CURRENT_INSTANCE_ID
+strata runtime restart --profile four-gpu --allow-source-migration --plan
+strata runtime restart --profile four-gpu --allow-source-migration --if-profile-revision PROFILE_REVISION --if-source-sha256 CANDIDATE_SOURCE_SHA256 --if-owner-id CURRENT_OWNER_ID --if-instance-id CURRENT_INSTANCE_ID
+strata runtime status --profile four-gpu --output json
+strata runtime verify --profile four-gpu --wait 300 --output json
+strata runtime verify --profile four-gpu --load --wait 300 --output json
+strata runtime stop --profile four-gpu --plan
+strata runtime stop --profile four-gpu --if-owner-id OWNER_ID --if-instance-id INSTANCE_ID
+strata runtime stop --profile four-gpu
+
+strata engine calibrate --profile four-gpu --plan
+strata engine calibrate --profile four-gpu --measure --exclusive --out CALIBRATION_REPORT
+strata engine calibrate --profile four-gpu --review-result CALIBRATION_REPORT
+strata engine calibrate --profile four-gpu --apply-result CALIBRATION_REPORT --exclusive
+strata engine calibrate --profile four-gpu --review-rollback CALIBRATION_REPORT
+strata engine calibrate --profile four-gpu --rollback-result CALIBRATION_REPORT --exclusive
+strata doctor --profile four-gpu --components --output json
+strata doctor --profile four-gpu --live --output json
+strata components verify --profile four-gpu
+strata models list --installed --output json
+strata models inspect MODEL_ID --output json
+strata models list --served --connection work --output json
+strata models import /absolute/path/to/GGUF-directory --plan --output json
+strata bench run --profile four-gpu --require-managed-match --suite serving-smoke --concurrency 8 --out RESULTS
+strata bench run --profile four-gpu --suite parallel-overload-v1 --concurrency 48 --out OVERLOAD_RESULTS
+strata bench run --profile four-gpu --suite parallel-cancel-v1 --concurrency 8 --out CANCEL_RESULTS
+strata bench run --profile four-gpu --suite parallel-prefill-cancel-v1 --concurrency 8 --out PREFILL_CANCEL_RESULTS
+strata bench report RESULTS --output json
+strata bench compare BASELINE_RESULTS MONITORED_RESULTS --output json
+strata bench report RESULTS --output markdown --out NEW_REPORT.md
+strata bench compare BASELINE_RESULTS MONITORED_RESULTS --output markdown --out NEW_COMPARISON.md
+```
+
+Operation recipes:
+
+```text
+strata ops init --profile four-gpu
+strata ops list --profile four-gpu
+strata ops show restart --profile four-gpu
+strata ops edit restart --profile four-gpu
+strata ops set restart --profile four-gpu startup_wait_s=45
+strata ops plan restart --profile four-gpu
+strata ops run restart --profile four-gpu \
+ --if-revision RECIPE_REV --if-profile-revision PROFILE_REV \
+ --if-owner-id CURRENT_OWNER_ID --if-instance-id CURRENT_INSTANCE_ID \
+ --if-source-sha256 CANDIDATE_SOURCE_SHA256
+strata ops run check --profile four-gpu
+strata ops set check --profile four-gpu live=true
+strata ops plan check --profile four-gpu
+strata ops run check --profile four-gpu
+strata ops set calibrate --profile four-gpu report_dir=/private/path/reports
+strata ops plan calibrate --profile four-gpu
+strata ops run calibrate --profile four-gpu --exclusive
+strata ops runs --profile four-gpu --limit 20 --output json
+strata ops result OPERATION_ID --profile four-gpu --output json
+```
+
+**Implemented now (source run):** `serve`, `status`, `monitor`, `logs` (bounded redacted request activity), saved `profile` edits/revisions/rollback, typed `ops` recipes with a bounded local recipe/direct-operation journal, `doctor`, `components verify`, local setup-config `models list --installed` and `models inspect MODEL_ID`, read-only `models list --served` and `models import PATH --plan`, calibration plan/measure/review/apply/rollback, `bench run`/`bench report`/`bench compare`, and POSIX `runtime` start/status/verify/restart/stop. The model commands read only top-level `strata-*.json` configs, include malformed candidates, and return local component presence separately from unverified engine compatibility. The served list reports only the current instance from telemetry. The import preview checks shard names, presence, bounded GGUF v3 architecture/tokenizer metadata, tensor-directory payload extents/overlaps and observed routed-expert encodings, then matches names to supported setup selections without adopting or copying files. A candidate selection still does not prove whole-file integrity, provenance, model-pack suitability or an engine load; actual adoption remains to be implemented. Serve previews settings. Optional `doctor --live` and `components verify --live` query a bounded NVIDIA host inventory and flag selected card indices that are absent. The typed `components.verify` recipe can save `live=true` for the same check. Card inventory and driver strings do not prove engine/backend compatibility, physical topology or model hashes; HIP and other live probes remain unqualified. The optional `max_queue` cap and `queue_timeout` deadline bound admitted calls and their wait for the first engine turn; the monitor shows the cap, rejections, deadline, timeout count, oldest wait and observed client-disconnect cancellations. The deadline requires a queue cap. Nonstreaming timeouts return HTTP 429; streams receive API-specific error events after headers. A disconnected serial request now leaves the bounded FIFO wait promptly. Calibration measures decode speed, then smoke-tests and saves the prior config and setup settings before apply. A separate rollback review checks exact applied-state hashes; rollback smoke-tests the previous config and restores both stores when they are unchanged. `--exclusive` remains an owner assertion. On POSIX, managed owner hosts and foreground `strata serve` hold a shared local activity lease; calibration measure, apply and rollback take its exclusive lease, scan owner records including uncertain state, and check the configured port. This prevents overlap among those new launch paths even on different ports. Direct legacy server launches, unrelated GPU processes and Windows control remain outside this lease. A calibration recipe only creates a new measurement report; review/apply/rollback remain separate explicit commands. The native Desktop Benchmarks screen now reviews an exact suite, concurrency, repeats, timeout, condition and new output directory against a loaded managed instance. A single-use review pins profile revision, source digest, owner and telemetry instance; execution rechecks them before calling the shared `bench.run` implementation. The screen polls a host job and opens the saved report, including failed and incomplete phase evidence. Reports retain the planned phase sequence; an interrupted or short run cannot claim success or enter a successful comparison. A malformed postflight telemetry response also leaves a failed report instead of a stale running record. A private phase progress record and the final report persist across a Desktop host restart. The browser session retains their path and can read them through the shared management bridge; the exact-run saved-profile lease check distinguishes a process still holding that output path from one that released it. Stale progress alone does not establish liveness or work advancing. Saved-profile CLI and Desktop benchmark runs share that local lease to refuse overlapping workloads. Exact-run operator cancellation and durable Desktop benchmark receipts are implemented locally; Windows recovery needs target qualification. The serving benchmark can export a local Markdown summary and a workload-checked comparison with explicit measurement limits; these exports omit the server address, credentials, prompts and answers and never publish automatically. The serving benchmark records client latency/TTFT, a short operator condition label, and sampled slots, groups, queues and devices without prompt/answer content. Read-only `bench compare` pairs saved runs only when suite, model, request fingerprints, concurrency, source digest and available reported environment agree. Its median phase deltas remain provisional. An opt-in `bench run --require-managed-match` checks the local POSIX owner host, saved profile/source revision, launch attestation, API endpoint and telemetry instance before and after the workload. A preflight mismatch refuses the workload; a postflight mismatch leaves a failed report. A successful managed report is labelled `managed_launch_checked`, while ordinary foreground/remote runs remain `unverified`. The checkpoint match is not continuous attestation, and monitor attachment, driver, engine and model hashes remain unverified. An explicit overload suite synchronizes up to 64 clients, separates expected rejections/timeouts from unexpected failures and checks recovery. The active/queued cancellation suite closes an active stream after first content and a queued stream behind occupied slots. A separate prefill cancellation suite closes a target only after correlated batch-slot telemetry shows partial prompt reading, while a companion decodes. Both check disconnect observation, companion completion, settled resources and recovery. The active/queued suite passed with mock and fake batched engines; the prefill suite passed with the fake batched engine. These source-run checks are not sustained four-card qualification. The POSIX host controls only its own child and restores the prior launch arguments after failed activation. After a hard host kill, its server receives an inherited-pipe parent-loss signal; a subsequent start verifies the host's lease is gone and the recorded child has exited before reclaiming stale private state. A missing/ambiguous ownership record or active socket still needs inspection. An owner can now point a saved profile to a separate run-config file with `profile use-config`, preview the source switch and restart with `--allow-source-switch` plus the candidate SHA-256. For an ordinary file switch, the old regular source must remain byte-for-byte unchanged for rollback. An in-place edit needs `--allow-source-migration` and the previewed candidate SHA-256: before drain the POSIX owner stores the running config bytes in its private directory, and failed activation relaunches from that snapshot without overwriting the edited file. A successful activation retires the snapshot. A hard-linked source remains disallowed; a changed candidate digest is rejected before drain. Start and restart verify the ready-file identity through authenticated local telemetry and a generation request with at least one completion token before reporting a loaded model ready; a deliberately lazy model is reported as unloaded without forcing a load. `runtime verify` rechecks an owned instance, and `--load` explicitly tests an unloaded model. These checks use a local API key in memory and put no generated text in the operation journal; the optional API monitor can capture the fixed probe request. A one-token smoke check does not establish answer quality or sustained throughput. The managed POSIX host now compares a private server-reported MAC of the config bytes and launch arguments with the launch it requested before reporting ready. This binds the running server to that launch, but does not prove model-file hashes, GPU topology or post-start external changes. **Still target:** Windows owner IPC/ACL, journal coverage for remaining direct management commands and the shared Desktop service, sustained hardware overload qualification and signed cross-platform release packaging. No real-model or four-card result exists.
+
+`profile edit` and `ops edit` use the configured editor on temporary JSON copies; validation and atomic replacement protect saved revisions. Invalid drafts remain available for repair. `profile set` and `ops set` supply typed edits and no-write previews. Recipe history and rollback are implemented locally. The developer must connect Desktop to the same schema and authority. Effective previews must show provenance, executable/argv and effects. The current preview covers local serving and recipe operations. The local journal records recipe runs and saved-profile direct runtime start/verify/restart/stop and calibration measure/apply/rollback with typed intent, start/end events and compact results; unfinished records have unverified completion. Explicit run-config path calibration and Desktop still need the shared lifecycle authority and journal.
+
+The source-run TUI opens on a YASD-inspired one-screen Overview. The narrow left column stacks serving state, side-by-side prompt/answer speed and batching/parallel work; the wider right column keeps per-card history, requests and recent activity together. At taller terminals, the left column also shows reported lifetime session totals and bounded model/engine facts. The 110 x 30 and 80 x 24 captures preserve the navigation footer and all four selected cards. Number keys open the detail views. The reference is Antani Technologies' MIT-licensed `yasd` repository (https://github.com/AntaniTechnologies/yasd). This implementation draws only from the versioned Strata telemetry contract; it does not synthesize YASD metrics such as KV quantization or expert-cache occupancy that Strata cannot yet report. The source-run TUI can show live request detail with slot, group, queue wait, prompt count, newly read prompt tokens and generated output. Requests scrolls through live and recent rows; Enter shows bounded detail for either kind without prompt bodies. Selected requests, devices and slots remain attached to their reported IDs across polls. A live request follows into recent history; if a selected row leaves retention, detail closes with an explicit notice; an instance restart clears selection even if an ID is reused. Serving tabs select Devices, Requests or Groups even at wide and compact widths; Enter opens bounded read-only device/slot detail, and Page Up/Down plus Home/End navigate rows.
+
+Compact layouts retain the selected row through a 40 x 12 resize. The selected pane precedes optional metrics, and the footer fits the terminal. It uses the snapshot time for queue age, so freeze holds that number steady. Live and recent server first-engine-token timing is now reported from engine queue entry; it includes queue and prefill. The Engine view and device detail show engine-reported inclusive layer ranges only when a current startup log supplies a valid plan; physical-card mapping needs an unambiguous visibility order. This is allocation, not measured stage occupancy. Opt-in `batch_telemetry=true` yields low-rate engine samples of processed verifier rows and active request slots per batch window, with a sample age; the default and older engines keep those values unavailable. This native path remains unbuilt and unqualified on CUDA, HIP and SYCL. Grouped-pipeline stage in-flight fractions now come from opt-in engine host spans; they include poll delay and are not GPU kernel occupancy. Client-observed TTFT, GPU kernel occupancy, non-grouped stage timing and a complete request lifecycle remain unavailable in the monitor and must stay labelled as such until instrumented.
+
+The Overview shows prompt-reading progress only when a request reports both a read count and prompt length. It summarizes reading, decoding and idle slot phases only when the effective slot report is complete and unambiguous. Exact pipeline group occupancy additionally requires a valid group on every effective slot; a partial or ambiguous report shows unavailable instead of a numeric fraction. The normalizer and bounded client also leave occupied slots unavailable when the source slot list is truncated or ambiguous; the client derives the number from validated slots instead of trusting a conflicting field. A bounded output-throughput trend shows the range over the displayed polling samples; it resets on an instance change and disappears with stale or missing rates. At wide sizes, separate recent-poll trends show processed batch rows/window and pre-admission queue count; replica mode shows each child batch series separately, never a cross-replica average. These trends have bounded sample counts and visible min/max ranges, reset on an instance change, and disappear when their newest source value is missing, its batch sample is more than five seconds old, or the connection is stale. The Overview hides batch and host-span numbers from engine samples older than five seconds; detail views retain the last value with its age. They are display histories, not extra engine measurements. After any failed collection, the first healthy snapshot establishes a new rate baseline while activity sequence tracking remains intact; the next consecutive healthy sample can report aggregate throughput. It marks a reachable unloaded model `SLEEPING` and suppresses stale speed readings. On initial attach, disconnect, rejected credentials or incompatible telemetry, a dedicated connection panel replaces cached request and GPU values in all six views, including compact 40-column layouts. Disconnects retry automatically; credential and schema failures require manual refresh after correction. Automatic glyph selection uses Unicode block history graphs when the output encoding supports them and ASCII on limited streams. `--glyphs braille` offers denser cells on terminals with a supporting font; `--glyphs ascii` forces a plain fallback.
+
+A portable `strata-monitor.pyz` can be built from `packaging/monitor_bundle.py`. It contains only the read-only client, renderer, one-screen dashboard, optional TUI module, shared status/monitor/logs grammar and Strata MIT notice; no engine or model files. `status`, `monitor --once` and `logs` work with standard-library Python, while interactive mode requires an explicit Textual install. The version-3 manifest checks SHA-256, bundle members, Python 3.10 minimum, telemetry schema 1 and the license notice; version-1 and version-2 source bundles remain verifiable for update/rollback. Eight focused bundle tests passed on the current Python 3.11 worktree; the version-3 artifact was built and verified with Python 3.10, and its standard-library connection command ran there without site packages. The earlier version-2 build passed the same tests on Python 3.10 and 3.11 on macOS. The manifest is unsigned. A local `install` command verifies the bundle, requires the candidate SHA-256 from its preview, copies it into a new directory and verifies the copy. A hash-pinned `update` retains one previous client; `rollback` exchanges the two verified copies, and `commit` removes the previous copy. `uninstall` requires the active SHA-256 from its preview and refuses a directory with unexpected files or an uncommitted previous copy. None of these commands installs Textual or changes the server. Treat this as a source-run transfer artifact; signed optional components and clean Windows/Linux install and update qualification remain release gates.
+
+### Editable recipe format
+
+The source-run CLI stores one versioned recipe file per operation under the owner-only profile directory. Its current schema uses `schema_version`, `profile`, `id`, `kind` and typed `params`. The three supported kinds are `runtime.restart` with `startup_wait_s`, `engine.calibrate.measure` with an absolute `report_dir`, and `components.verify` with optional boolean `live` (false by default). The calibration suite is still the fixed decode sweep. Recipes are not shell scripts and cannot embed arbitrary command text. The developer must connect UI forms and CLI edits to one validated schema and operation service. The example below is a **future target schema**, not a current Strata config file:
+
+```json
+{
+ "schema_version": 1,
+ "profile": "four-gpu",
+ "model_ref": "installed-model-id",
+ "devices": [0, 1, 2, 3],
+ "parallel": 8,
+ "batch_groups": "auto",
+ "max_queue": 32,
+ "queue_timeout": 15,
+ "operations": {
+ "restart": { "kind": "runtime.restart", "drain_timeout_s": 30 },
+ "calibrate": { "kind": "engine.calibrate", "suite": "throughput-and-latency", "trials": 3 },
+ "check": { "kind": "components.verify", "scope": ["engine", "backend", "model", "tokenizer", "api"] }
+ }
+}
+```
+
+Keep canonical model profiles, user overrides and temporary command flags separate. The effective preview shows which layer supplied each value; the active runtime records a snapshot of what actually launched. Changes to the file do not silently restart a running model. A profile and recipe have stable IDs and a schema version. Validate ranges, model/backend capabilities and incompatible sampling or batch modes before GPU allocation. Use argument arrays and typed values when invoking owned processes. Do not splice raw command text into a shell.
+
+For expert developers who truly need a custom local tool, a separate **local-owner-only** `exec` recipe may accept an absolute executable path, an argv array, a fixed working directory and named environment references. It is opt-in, never served through inference or telemetry APIs, never constructed from model output, and displays the exact command and effects before execution. First-class restart, calibration, doctor and benchmark flows should use typed operations instead of this escape hatch.
+
+### Operation semantics
+
+| Operation | Preview / checks | Execution and result |
+| --- | --- | --- |
+| Restart or rerun model | Resolve installed model, backend binary, devices, pack/schema, context, requested slots/groups and effective args. Check port and available resources. | Stop new admissions, drain/cancel within deadline, start the owned instance from a saved profile revision, wait for generation readiness, and report actual slots/groups. On failed activation, restore the previous working profile/runtime selection where safe. Never kill unrelated GPU processes. |
+| Calibrate engine | Show scope, expected duration, exact hardware/model key, parameters and benchmark suite. `--plan` performs no mutation or network access. | `--measure` obtains exclusive access or an explicitly drained instance, runs repeated trials and saves a signed or hash-bound report containing baseline, raw trials, candidate and hardware/model identity; it does not change the active config. `--apply-result` checks report freshness and identity, saves the prior config, applies the candidate, then verifies a smoke generation. On failure restore previous settings. Report latency and throughput rather than only fastest tok/s. |
+| Doctor / component check | Read installed component manifests and inspect engine binary/version/protocol, backend and driver, selected GPUs, model shards and hashes, tokenizer/template, optional vision, TUI and harness compatibility. Label unverified checks. | Read-only report with stable issue codes, severity and repair suggestions. A separate explicit repair plan may download or replace artifacts; doctor never repairs by itself. |
+| Benchmark | Resolve a named, versioned workload and output directory; show model/config/hardware identity. | Run only on explicit request, record JSON evidence and environment, include four-GPU mixed long/short prompts, cancels and overload, and compare with a pinned baseline. No benchmark runs when opening Monitor. |
+
+The operator surfaces must show command state (`planned`, `waiting`, `running`, `cancelling`, `succeeded`, `failed`), timestamps, log location, resulting instance ID and whether any change applied. CLI `--output json`/`jsonl` must remain machine-clean. Secrets are referenced by owner-controlled storage, not embedded in recipes, shell histories, ready files or operation logs.
+
+### Four-GPU serving visibility
+
+A 4 x RTX 6000 operator should see one aggregate line and four card rows in the selected-device order, updated from measured telemetry. A missing or duplicate card sensor leaves that selected row visible with unavailable readings and no stale utilization graph instead of substituting another host GPU. Client device history is capped at the currently selected card indices. Keep **running requests**, **occupied decode/prefill slots**, **engine waiting**, **pre-admission queue**, **rejections and timeouts**, **batch groups**, **batch size/window**, **throughput**, **TTFT** and **per-card memory/utilization** as distinct fields. A missing backend signal is `unavailable`, not zero or a guessed mapping. Group membership must identify the engine’s actual slot groups; stage placement is a separate engine-reported mapping, and time-series views should reveal whether batching improves throughput while harming tail latency. Provide terminal widths around 110 and 80 columns plus a compact 60-column view; preserve a clean JSON snapshot for scripts. Validate all labels against the engine scheduler before using the TUI as a performance dashboard.
+
+One acceptance scenario should run mixed short and long requests at a recorded parallel setting, increase arrival rate until queue admission is exercised, cancel an in-flight request, then drain and restart the model. Save synchronized CLI JSON, TUI capture, backend counters and benchmark output. The expected invariant is that aggregate and per-card counts reconcile with the scheduler and that no request disappears between admitted, waiting, active, cancelled, completed and rejected states. Record the exact RTX 6000 generation and memory size with the driver, topology and model; the card name alone is insufficient.
+
+## 4. UI, CLI and TUI mapping
+
+| Surface | Connect to shared operation | Display rule |
+| --- | --- | --- |
+| Desktop Overview / Models | Start, stop, restart, model selection and readiness | Show saved versus running revision and exact failure/rollback state. |
+| Desktop Tuning | Edit profile and operation recipes; validate; preview calibration; apply and restart | Preserve the supplied UI's visual language. Explain duration and exclusivity. Clearly mark predictions versus measurements. |
+| Desktop Settings / Components | `doctor`, component versions, check and explicit repair plan | Show installed, missing, incompatible and optional components separately. |
+| Desktop Serving / Monitor | Same versioned telemetry used by terminal; API connection details | Show batch group occupancy, in-flight/occupied/waiting/queued counts and four per-card readings without invented stage mappings. |
+| CLI | Scriptable typed operations above | Same validation and results as UI, with stable exit codes and clean JSON/JSONL. |
+| TUI monitor | Read-only telemetry, request/group/device panes | Show operation status from telemetry if exposed, but never execute a restart/calibration from a monitor key. Offer copyable CLI guidance when useful. |
+| `strata code` | Shared harness session and approval service | Local workspace/tool authority is separate from remote inference credentials. |
+
+Terminal styling should match the supplied UI's restrained green/neutral hierarchy and terminology. The terminal font is user-controlled; no font installation is required. The current wide, four-stage, sampled-batching, 80-column serving, recent-detail and slot-detail previews under `Strata-TUI-CLI/docs/terminal-previews/`, plus the six-view screenshots in `output/terminal-screenshots/`, use fixture values and are not hardware results. The six-view captures use the dark theme with color enabled; the actual monitor still honors `NO_COLOR` when set by an operator.
+
+<!-- pagebreak -->
+
+## 5. Developer implementation order
+
+1. **Intake and reconcile.** Record hashes, source revisions, rights, UI/TUI/harness behavior and the chosen current Strata base. Compare this terminal milestone against that base; port it without replacing newer engine changes. Return a screen/action/contract matrix and supported model/backend matrix.
+2. **Shared runtime and profile contract.** Extract pure validate/start from `setup.py` and `serve/server.py`; define profile schema and effective-value resolver. Preserve legacy launchers and APIs. Add owner-only management access, operation journal and ready/instance identity.
+3. **Operator operations.** Implement profile edit/validate, restart, calibration plan/apply, doctor/components and benchmark hooks as typed operations. Split `setup.py` calibration measurement from its current update/config-write/start side effects. Add atomic config revisions and rollback.
+4. **Front-end wiring.** Connect the supplied UI's Tuning, Overview, Models and Serving screens to the same operation and telemetry contracts. Connect the milestone CLI to management and package the TUI independently. Integrate the supplied TUI only after comparing behavior and dependencies; do not ship two terminal frameworks.
+5. **Harness and release.** Wire the supplied DeepSeek-derived harness to Desktop and `strata code` with shared sessions/approvals. Build verified Desktop and lean Server distributions and optional components. Keep host-native runtime work in its own adapter milestone.
+6. **Qualification.** Run clean Windows/Linux installs, offline starts, management permissions, interruption/rollback and hardware tests. On the intended 4 x RTX 6000 host, record exact card generation, driver, model and topology; compare a defined mixed workload with and without the monitor attached.
+
+### Required developer PR evidence
+
+- Before/after contract and migration notes; exact source and asset revisions.
+- Tests for preview versus apply, config edit conflicts, active requests during restart, failed calibration rollback, stale ready file, component corruption, lost GPU and cancelled operation.
+- UI and CLI parity for the same profile/action, with both success and failure screenshots or machine outputs.
+- Server without Desktop, harness, Textual or build-tool dependencies; TUI installed and removed independently.
+- Four-GPU telemetry where occupied slots, engine waiting, pre-admission queue, group mapping, aggregate throughput and device sensors have distinct measured meanings. Batch-window rows and grouped-pipeline stage in-flight spans require the opt-in engine protocol and native-backend qualification; GPU kernel occupancy remains unavailable. Startup layer allocation is labelled as reported topology.
+- Benchmark raw results, hardware/software identity, repeated trials and overhead evidence. Do not describe fixture screenshots as RTX 6000 measurements.
+
+## 6. Transfer checklist
+
+Use the [terminal telemetry field matrix](TERMINAL_TELEMETRY_FIELDS.md) when wiring the supplied UI to `/v1/telemetry`: it records units, source, request sensitivity, sample age and legacy fallbacks. A missing signal stays unavailable rather than becoming a zero or a four-card estimate.
+
+The [qualification matrix](TERMINAL_QUALIFICATION.md) separates existing mock/fake-engine evidence from hardware, cross-platform, shared Desktop and harness gates. Carry its raw evidence requirements into the integration PRs.
+
+Deliver the three plan documents, this handoff, the supplied asset originals with hashes, the selected GitHub base revision and the terminal milestone commit or patch. The milestone was developed in a **separate local checkout**, not merged into the user's current Strata GitHub repository. The developer should identify a current integration base, review the patch, then merge/cherry-pick in reviewable pieces. Do not treat the UI prototype's demo model or restart stub as production engine integration.
+
+At first review, the developer should return: (1) a file/action map, (2) exact command schemas and profile/recipe storage location, (3) a migration plan for the current setup/calibration behavior, (4) dependency and license inventory, (5) acceptance environment including the exact RTX 6000 variant, and (6) an ordered PR schedule with remaining owner decisions.
+
+**Current compact monitor check.** All 215 terminal tests pass, including a live 40x12 disconnect screen and all six views at 40/60/80 columns. Synthetic 30.31-second and 30.34-second UI runs passed on the compact and display revisions, respectively; see their raw reports. The 1,800.31-second UI soak on monitor revision `ba138f6` passed 360 resizes, two outages, a restart, bounded four-card histories, one in-flight read and detach; raw JSON and late-run RSS are in the packet. Target-host and real-model qualification remain open.
diff --git a/docs/MANAGEMENT_PROTOCOL.md b/docs/MANAGEMENT_PROTOCOL.md
new file mode 100644
index 000000000..4d3940e22
--- /dev/null
+++ b/docs/MANAGEMENT_PROTOCOL.md
@@ -0,0 +1,59 @@
+# Owner-local management bridge, version 1
+
+The Strata CLI and a local Desktop host use the same saved-profile store and `strata_control.management.runtime_action()` for runtime operations. A trusted Desktop host can invoke the one-shot `python -m strata_control.management` process for runtime actions, component/model inspection, reviewed benchmark runs and saved evidence, reviewed calibration and profile edits. Send one UTF-8 JSON object on stdin, close stdin, and read one JSON object on stdout. The command exits with the response's `exit_code` on failure; ordinary success exits 0. Diagnostics go to stderr. The input limit is 64 KiB.
+
+This is **owner-local process IPC**. It has no HTTP listener and does not accept an inference or monitor API key. The imported Node host has limited, opt-in loopback HTTP seams for one host-configured saved profile: `/api/native/runtime` for Serving, `/api/native/telemetry` for Monitor, `/api/native/components` for component inspection, `/api/native/models` for installed run configs, `/api/native/models/inspect?id=MODEL_ID` for details, `/api/native/models/import-plan` for an explicit read-only GGUF preflight, `/api/native/profile` for saved settings, `/api/native/bench/review`, `/execute` and `/job?id=JOB_ID` for reviewed benchmark launch, `/api/native/bench/report` and `/compare` for saved evidence, plus `/api/native/calibration/review`, `/execute`, `/job?id=JOB_ID` and `/cancel` for reviewed calibration, bounded progress and exact active-measurement stop requests. Serving, Profile, Benchmarks and Calibration use short-lived, single-use server-side reviews before mutations. The Node routes check local Host/Origin and a custom JSON action header for action POSTs; Python rechecks reviewed preconditions. This local preview is not audited Desktop authentication or a general browser management API. The other UI screens still use prototype data; native mode refuses prototype mutations and `/v1` inference. The shared Desktop journal and full operation API remain integration work.
+
+## Request and response
+
+```json
+{"schema_version":1,"action":"runtime.start.plan","profile":"four-gpu","params":{"shutdown_timeout_s":30}}
+```
+
+`schema_version` must be the integer `1`. `action` and `params` must match one row below exactly. `profile` is a saved lowercase profile ID. Unknown fields, duplicate JSON keys, nonfinite numbers, booleans in numeric fields and unexpected actions are rejected before an operation starts. Runtime errors return `{"schema_version":1,"ok":false,"error":"...","exit_code":N}`. Successful results include `schema_version:1` and the owner runtime's result. Journaled actions also return an `operation_id` that both UI and CLI can inspect with `strata ops result`.
+
+| Action | Exact `params` keys | Effect |
+| --- | --- | --- |
+| `bench.run.plan` | `path`, `suite`, `concurrency`, `repeat`, `request_timeout`, `condition` | Check a new absolute output directory, bounded workload, loaded model and matching managed profile/owner/telemetry instance. Return the planned request count, phase list and pinned identities. No inference request or output directory is created. |
+| `bench.job.create` | `job_id` plus all `bench.run` review and identity keys | Create an owner-only journal receipt for a reviewed Desktop job before launching its worker. The 32-character job ID is generated by the host. A receipt without an active lease or final report does not prove that the worker started. |
+| `bench.job` | `job_id` | Read the durable receipt, exact-run lease, private progress and matching report. A saved final report can finish a receipt left running by a crash after report write. An unfinished receipt without an active lease becomes `completion_unknown` after a short launch window. |
+| `bench.run` | all `bench.run.plan` keys plus `if_profile_revision`, `if_source_sha256`, `if_owner_id`, `if_instance_id`; Desktop also sends `job_id` | Recheck the reviewed source, owner and instance, then use the CLI benchmark runner with managed matching before and after. Create a private `results.json` when measured phases fail. With a job ID, the worker verifies the receipt matches the reviewed request and finishes it with a bounded outcome. |
+| `bench.progress` | `path` | Read the owner-only `progress.json` in an absolute output directory (or next to its `results.json`). It reports completed phases and the current phase without prompts, answers or credentials. For saved-profile runs, the response also checks the exact output path against the owner-local lease: `active`, `ended`, `other_active` or `untracked`. A `running` record alone does not prove process liveness. |
+| `bench.cancel` | `path` | Request a stop for the exact active saved-profile run. The owner-local lease and private output directory are checked before writing an owner-only `cancel.request` marker. Returns `cancel_requested` until the runner writes final evidence; it does not claim that the engine has already stopped. CLI: `strata bench cancel --profile NAME --path /absolute/run/results.json`. |
+| `bench.report` | `path` | Read an absolute local `bench run` output directory or `results.json`, summarize its phases and produce a privacy-safe Markdown export. No workload, mutation or journal entry. |
+| `bench.compare` | `baseline`, `candidate` | Read two absolute local saved reports, apply the CLI's workload and available-environment match checks, and produce a provisional comparison and privacy-safe Markdown export. No workload, mutation or journal entry. |
+| `calibration.plan` | none | Read-only decode-sweep preflight, including saved-profile revision, source digest, selected devices and component status. No engine launch or journal entry. |
+| `calibration.job.create` | `job_id`, `action`, `path`, `exclusive_ack`, `if_profile_revision`, `if_source_sha256`, `if_report_sha256` | Create an owner-only receipt for a reviewed Desktop measure/apply/rollback action before launching its worker. `if_report_sha256` is `null` for measure. The receipt alone does not prove the worker started. |
+| `calibration.job` | `job_id` | Read a bounded receipt after a Desktop host restart. A measurement report bearing the exact job ID and reviewed profile/source identity can finish a receipt left running after report write. An exact worker lease proves active work; without it or a final journal result or matching report, the receipt becomes `completion_unknown` after a short launch window. The response also carries bounded stage progress and stop-request state. |
+| `calibration.cancel` | `job_id` | Request a stop only for the exact active measurement worker. The owner-only marker is polled by that worker and passed into engine generation; the request acknowledges intent, while the final receipt says whether cancellation occurred. Apply and rollback cannot be cancelled in flight. |
+| `calibration.measure` | `path`, `exclusive_ack`, `if_profile_revision`, `if_source_sha256`; Desktop also sends `job_id` | Require explicit exclusive-access acknowledgement, reject a stale saved profile or source, then measure into a new absolute local report path and journal the result. Recheck source under the calibration lock. With a job ID, every preflight and execution failure finishes the matching receipt. |
+| `calibration.apply.plan` | `path` | Review one saved report for freshness and applicability, pin report body digest, profile revision and source digest. No write or journal entry. |
+| `calibration.apply` | `path`, `exclusive_ack`, `if_profile_revision`, `if_source_sha256`, `if_report_sha256`; Desktop also sends `job_id` | Recheck reviewed profile, source and report, then smoke-test and apply the candidate with private rollback evidence; journal the outcome. |
+| `calibration.rollback.plan` | `path` | Review the exact applied state and saved backups for rollback; pin report, profile and current source. No write or journal entry. |
+| `calibration.rollback` | `path`, `exclusive_ack`, `if_profile_revision`, `if_source_sha256`, `if_report_sha256`; Desktop also sends `job_id` | Recheck the reviewed state, smoke-test the previous config and restore config/settings; journal the outcome. |
+| `components.inspect` | `live` | Read the saved profile's installed component report. `live: true` also runs the bounded host GPU probe. An inspection can succeed (`ok: true`) while `report.ok` is false because required files or selected cards are missing. No operation journal entry is created. |
+| `models.installed` | none | List at most 128 setup-written local run configs for model selection; presence and execution compatibility remain separate. Requires the configured saved profile to exist. |
+| `models.inspect` | `model_id` | Inspect one installed run config and its component report. Model-file integrity and engine compatibility remain unverified. No journal entry. |
+| `models.import.plan` | `path` | Check an absolute local GGUF file or shard folder using the CLI's bounded preflight. It never copies, adopts or loads a model. No journal entry. |
+| `profile.inspect` | none | Read the saved profile, revision, source digest and effective serving values. No mutation or journal entry. |
+| `profile.change.plan` | `overrides`, `source_config`, `if_revision` | Validate typed overrides and an absolute run config against the revision loaded in the editor; show before/after, effective values, current profile revision and proposed source digest. No file write or restart. |
+| `profile.change` | `overrides`, `source_config`, `if_revision`, `if_source_sha256` | Save the reviewed candidate through the same versioned profile store as CLI. Reject changed profile revision or source digest. The running instance is unchanged; the operator reviews Restart separately. Profile history records the old revision, but this save is not a runtime journal operation. |
+| `runtime.status` | none | Read the owner's current instance state. |
+| `runtime.start.plan` | `shutdown_timeout_s` | Validate the saved profile and show effective launch arguments, `launch.profile_revision` and `source_sha256`; no launch or journal entry. |
+| `runtime.start` | `wait_s`, `shutdown_timeout_s`, `if_profile_revision`, `if_source_sha256` | Start through the owner host with both reviewed preconditions and journal the outcome. Both preconditions are required by the Desktop bridge. |
+| `runtime.restart.plan` | `allow_source_switch`, `allow_source_migration` | Compare the current owned launch with the saved profile and report source, owner and instance preconditions. |
+| `runtime.restart` | `wait_s`, `startup_wait_s`, `if_profile_revision`, `if_owner_id`, `if_instance_id`, `allow_source_switch`, `allow_source_migration`, `if_source_sha256` | Drain and restart through the owner host, with reviewed profile, source, owner and instance preconditions and a journal record. All four preconditions are required by the Desktop bridge. |
+| `runtime.verify.plan` | `load` | Read the ready owner and instance IDs, model load state and whether this check would load the model. It performs no probe and creates no journal entry. |
+| `runtime.verify` | `wait_s`, `load`, `if_owner_id`, `if_instance_id` | Recheck the reviewed owner and instance inside the owner host before checking API identity, launch attestation and generation when loaded. It may explicitly load a model and is journaled. Both IDs are required by the Desktop bridge; direct CLI verification may omit them. |
+| `runtime.stop.plan` | none | Read the current owner ID and, when available, engine instance ID; no drain or journal entry. |
+| `runtime.stop` | `wait_s`, `if_owner_id`, `if_instance_id` | Drain and stop only the reviewed owner and instance; journal the outcome. `if_owner_id` is required by the Desktop bridge. |
+
+Desktop benchmark review bounds the total phase count and per-request timeout against its 1,900-second bridge deadline; longer workloads remain available through `strata bench run`. Saved-profile CLI runs and Desktop runs share a local per-profile benchmark lease that refuses overlapping launches; a raw `--url` run has no saved-profile lease. `STRATA_API_KEY` and optional `STRATA_TELEMETRY_KEY` are read only by the host process. Desktop now creates a private journal receipt before launch and recovers a job by ID after a host restart. The phase progress file and final report persist in the private output directory. Reports retain the planned and completed phase counts; success requires every planned phase to pass. A caught phase exception saves partial evidence and is labelled incomplete in the Desktop and Markdown export; an abrupt process kill can leave only the last progress record. Operator cancellation closes active benchmark-owned response streams and saves `cancelled: true`, `successful: false`, and a `cancelled` final progress state. It can take up to the configured request timeout if a connection has not received response headers yet. The request marker is an acknowledgement, not the final outcome. A malformed postflight telemetry response is saved as failed evidence with unavailable after-state. The exact-run lease check distinguishes a process still holding that path from one that released it. `other_active` and `untracked` do not prove that the saved run is alive. A held lease does not prove that inference is making progress. A crash before the benchmark creates an output directory can leave only the receipt; after the launch window it is labelled `completion_unknown`. Windows lease and receipt recovery still need target qualification.
+
+Times are seconds. `if_profile_revision` is a 16-character lowercase profile revision; `if_source_sha256` is a 64-character lowercase digest. For start, take them from `runtime.start.plan` as `plan.launch.profile_revision` and `plan.source_sha256`. For restart, take `candidate_profile_revision`, `candidate_source_sha256`, `current_owner_id` and `current_instance_id` from `runtime.restart.plan`. For stop, take `plan.owner_id` and `plan.instance_id` from `runtime.stop.plan`; the instance ID may be `null` while the engine is starting or has failed. Owner and instance IDs are 32-character lowercase values when present. Restart plans require a ready instance, so both identities are present. The bridge rejects stale restart and stop reviews before journaling; the owner host checks again before draining. A stale start plan is rejected before the journal begins when possible; the owner host checks the same preconditions again immediately before launching the engine. A plan does not reserve the profile, source file or instance. An interrupted or timed-out mutating call may have an uncertain outcome. Inspect the operation journal and runtime status before retrying; never assume the process exit reversed a side effect.
+
+## Desktop adapter requirements
+
+The Desktop host now maps one configured profile's Start, Stop, Restart and Verify controls to these typed actions and displays the returned operation ID and owner state. A changed source config causes the first Restart review to refuse the action and show an explicit source-change review; the second plan sets only the operator-selected source-switch/migration allowances and displays the candidate path, digest and rollback requirement before drain. Its Components screen reads the same `doctor.inspect` report as the CLI; the optional live card probe runs only after the operator requests it. Profile presents typed override fields and installed model config choices, stores a reviewed candidate server-side for 90 seconds and saves through the shared profile store. Models lists the same setup-written run configs as CLI, inspects one config and its component report on request, and offers an explicit read-only GGUF file or folder preflight. Benchmarks reads saved local results through the shared CLI parser, shows selected bounded phase fields and compares only workload-compatible runs; its Markdown download omits addresses, credentials, prompts and answers. It launches reviewed managed workloads and can request cancellation for the exact active run. Calibration reviews a decode sweep and saved apply/rollback candidates through the same Python calibration module as CLI. The browser receives only bounded selected settings and findings; argv and raw measurement reports stay on the host. One host job can run at a time. The browser polls an owner-journal job ID for launching, running, succeeded, failed, cancelled or uncertain status, while the Python action writes bounded progress and the final shared operation record. Benchmark jobs are queryable by the same ID after a Desktop host restart through the owner journal and saved evidence. Calibration jobs have owner-only journal receipts recoverable by ID after a Desktop host restart. An exact saved measurement report can reconcile a receipt left running after report write. Measurement writes bounded stage/sample progress; a live exact worker lease distinguishes active work from an orphaned receipt. An operator can request cancellation for an active measurement, and its engine generation receives the stop event. The final receipt records `cancelled` only after the worker exits; inspect `strata ops runs` and the report path before retrying an uncertain operation. The browser receives only selected, bounded inspection fields; a plausible model file set still needs engine, model-pack, integrity and hardware checks. The host filters and bounds every report before sending it to the browser. Verify uses a single-use 90-second review and pins owner and instance IDs; an explicit Load + Verify choice is shown when the model is unloaded. A successful one-token probe does not establish answer quality or sustained throughput. It must preserve the plan/execute review step, keep only one lifecycle authority for a profile, and never build shell command strings from browser content. The harness screen still needs its shared typed mapping. Calibration progress, exact-worker liveness and measurement cancellation are implemented locally; long-run GPU behavior, cleanup after abrupt worker death, and unmanaged/Windows engine exclusion need target qualification. The current one-shot bridge does not provide a general write lease, streaming progress or recovery for an ambiguous start/stop/restart result.
+
+Before production use, qualify this bridge and its owner transport on Windows/Linux, test an actual engine launch, and run UI/CLI parity scenarios against the same profile and journal. The source-run macOS fake-engine test checks that a bridge-started instance is visible and stoppable from CLI, that stale start, stop and restart reviews do not affect a different launch, and that malformed requests create no journal entry.
diff --git a/docs/TERMINAL.md b/docs/TERMINAL.md
new file mode 100644
index 000000000..86d9631c3
--- /dev/null
+++ b/docs/TERMINAL.md
@@ -0,0 +1,272 @@
+# Strata terminal commands (implementation in progress)
+
+For the shortest path through the source-checkout commands, use the [terminal quick start](TERMINAL_QUICKSTART.md).
+
+This checkout adds a source-run terminal entry point beside the existing server:
+
+```sh
+python strata.py status --url http://127.0.0.1:8095
+python strata.py status --url http://127.0.0.1:8095 --json
+python strata.py monitor --url http://127.0.0.1:8095 --once
+python strata.py serve --profile path/to/strata-model.json --port 8095
+```
+
+Discover setup-written model run configs in an installation without loading the engine:
+
+```sh
+python strata.py models list --installed --output json
+python strata.py models inspect MODEL_ID --output json
+python strata.py models list --installed --install-dir /absolute/Strata/install --output json
+python strata.py models list --served --connection work --output json
+python strata.py models import /absolute/path/to/GGUF-directory --plan --output json
+```
+
+Installed discovery scans only top-level `strata-*.json` files in the checkout containing `strata.py`, or in the existing absolute directory chosen by `--install-dir`/`STRATA_INSTALL_DIR`. It checks the local engine, tokenizer and referenced pack files using the same read-only component inventory as `doctor`. Invalid config candidates stay visible with an error. `models inspect` returns the component report and source-config SHA-256. `component_status: present` means required files exist, while `execution_compatibility: unverified` means model/backend support and real loading have not been proven.
+
+`models list --served` uses the saved read-only connection and reports the **current server instance's** model ID and loaded state from telemetry. It is not a catalog of every installed or available model. `models import PATH --plan` inspects a local GGUF file or directory for bounded shard names, presence, regular files and GGUF v3 metadata. It checks for the expected `qwen4exp` architecture and `gpt2` tokenizer fields, and compares shard names with this checkout's known supported setup selections. It parses each bounded tensor directory, rejects payload extents past the end of a shard, and reports observed routed-expert encodings against the known variant's allowed encodings. An optional `mmproj` GGUF in the folder is listed as auxiliary and left untouched. A matching name produces a `setup_args_hint`, not a compatibility verdict: the preview does not read tensor payloads, hash entire files, verify provenance or test an engine load. Full artifact, model-pack, engine-version and hardware checks remain before actual adoption. No import, copy, download, repair or engine launch occurs in these inventory and preview commands.
+
+Save a monitor endpoint separately from the model's serving profile. A connection stores the server root, an optional reverse-proxy prefix and the **name** of a credential environment variable; it never stores the secret:
+
+```sh
+python strata.py connection create work --url https://inference.example --prefix /strata --credential-env STRATA_TELEMETRY_KEY
+python strata.py connection list --output json
+python strata.py connection show work --output json
+python strata.py connection set work prefix=/new-strata --plan --output json
+python strata.py connection set work prefix=/new-strata --if-revision CONNECTION_REVISION
+python strata.py config show --effective --connection work --output json
+python strata.py status --connection work --json
+python strata.py monitor --connection work
+python strata.py logs --connection work --source runtime --follow --output jsonl
+```
+
+`config show` reports the source of each effective setting and whether the referenced credential is present, without printing its value or connecting to the server. An explicit `--url` or `--connection` wins over `STRATA_CONNECTION`, then `STRATA_URL`, then the local default. `--credential-env` overrides the selected reference. Direct URL use retains the legacy `STRATA_API_KEY` default; new saved connections default to `STRATA_TELEMETRY_KEY` so a read-only key can be used. Remote roots require HTTPS, and a saved proxy prefix accepts only simple path segments. The source CLI and portable monitor bundle use the same owner-private connection files in `${XDG_CONFIG_HOME:-~/.config}/strata/connections` or `%APPDATA%/Strata/connections`; `STRATA_CONNECTION_DIR` can select an absolute directory. On POSIX, the directory and records must be owner-only. Windows ACL qualification remains open.
+
+Operator profiles are separate from setup's run config. Save one from an installed config, preview edits, and use its name for serving:
+
+```sh
+python strata.py profile create four-gpu --from-config path/to/strata-model.json
+python strata.py profile set four-gpu parallel=8 batch_groups=auto max_queue=32 queue_timeout=15 batch_telemetry=true --plan
+python strata.py profile set four-gpu parallel=8 batch_groups=auto max_queue=32 queue_timeout=15 batch_telemetry=true
+python strata.py profile show four-gpu --effective --output json
+python strata.py serve --profile four-gpu --plan --output json
+python strata.py serve --profile four-gpu --output jsonl
+python strata.py doctor --profile four-gpu --components --output json
+python strata.py doctor --profile four-gpu --live --output json
+python strata.py engine calibrate --profile four-gpu --plan --output json
+python strata.py serve --profile four-gpu --ready-file /absolute/path/strata-ready.json
+```
+
+For a saved profile on POSIX, an owner-only local host can keep the server running and provide repeatable rerun commands:
+
+```sh
+python strata.py runtime start --profile four-gpu --plan --output json
+python strata.py runtime start --profile four-gpu --shutdown-timeout 30
+python strata.py runtime status --profile four-gpu --output json
+python strata.py runtime verify --profile four-gpu --wait 300 --output json
+python strata.py runtime verify --profile four-gpu --load --wait 300 --output json
+python strata.py profile set four-gpu parallel=8 batch_groups=auto --plan
+python strata.py profile set four-gpu parallel=8 batch_groups=auto
+python strata.py runtime restart --profile four-gpu --plan --output json
+python strata.py runtime restart --profile four-gpu --startup-wait 300
+python strata.py runtime stop --profile four-gpu
+```
+
+To switch a managed model to a separate run config file, select the file in the saved profile, preview the owned restart, then pass its candidate digest when restarting:
+
+```sh
+python strata.py profile use-config four-gpu --from-config /absolute/path/next-model.json --plan --output json
+python strata.py profile use-config four-gpu --from-config /absolute/path/next-model.json --if-revision PROFILE_REVISION --output json
+python strata.py runtime restart --profile four-gpu --allow-source-switch --plan --output json
+python strata.py runtime restart --profile four-gpu --allow-source-switch --if-profile-revision NEW_PROFILE_REVISION --if-source-sha256 CANDIDATE_SOURCE_SHA256
+```
+
+If an operator edits the **same run config file** while its managed server is running, use the separate migration preview and pin the edited bytes before restart:
+
+```sh
+python strata.py runtime restart --profile four-gpu --allow-source-migration --plan --output json
+python strata.py runtime restart --profile four-gpu --allow-source-migration --if-profile-revision PROFILE_REVISION --if-source-sha256 CANDIDATE_SOURCE_SHA256
+```
+
+The local host owns its server child and uses a private Unix control socket and token file; the CLI never signals a PID read from a ready file. Restart drains the current instance, applies the saved profile revision, waits for the new ready file, and launches the previous arguments again if activation fails. Switching the saved profile to a **distinct, regular source file** is explicit and requires the preview's source digest. The old source file must still contain its launch bytes for ordinary rollback. An in-place edit requires `--allow-source-migration`; before drain the host copies the running config bytes to a mode-0600 file in its private runtime directory. If the old file was edited **and** the saved profile now points to a new file, preview and run with both source flags. A failed activation restarts from the snapshot, leaving the operator's edited file untouched. The rollback status reports the snapshot path; after the operator fixes the candidate file, retry it as a distinct source with `--allow-source-switch`. A successful activation removes the unneeded snapshot. A hard link to the old file or a source change after preview is rejected before draining; a source change during activation fails attestation and attempts rollback. The host stores private logs and state under `${XDG_STATE_HOME:-~/.local/state}/strata/runtime` or `STRATA_RUNTIME_DIR` (which must be an absolute, owner-only directory). `runtime start` and `runtime restart` verify the ready-file instance ID against authenticated local telemetry, compare a private MAC of the config bytes and launch arguments actually read by the server, and run a one-token generation before reporting generation readiness. A launch mismatch fails before generation. The MAC is scoped to the owner-managed process; it is not a publisher signature or a model-file hash. An intentionally lazy model remains `unloaded` with `generation_ready=false`; `runtime verify --load` opts into loading and generating. `runtime status` reports the last successful startup or explicit verification, not continuous engine liveness; use `runtime verify` to recheck. The probe validates the bound endpoint and model ID, requires at least one completion token, uses a configured API key only in memory, and puts neither generated text nor credentials in the operation journal. If the optional API monitor is enabled, it can capture the fixed probe request like other inference calls. This one-token smoke check does not establish sustained throughput, answer quality or four-card stability. On POSIX, an inherited pipe makes the server stop its dedicated process group when the owner host dies, including after a hard kill. `runtime status` then reports `stale`; a new `runtime start` waits for the recorded child to exit, verifies the host's file lease is gone and the child has exited, and reclaims private state and any orphaned rollback snapshots without signaling a saved PID. If the child is still present, its ownership record is missing, or the socket has an active listener, recovery refuses and requires inspection. This mechanism has been tested with a fake engine on macOS, not qualified on real multi-GPU workloads or Linux. Windows needs a qualified owner-only control transport and ACL tests before these commands can manage it. The shared Desktop operation journal and full model/device editing contract are still pending.
+
+Owner-editable operation recipes save typed actions next to profiles. Initialize three examples, preview the exact action and its effects, then run it explicitly:
+
+```sh
+python strata.py ops init --profile four-gpu
+python strata.py ops list --profile four-gpu
+python strata.py ops set restart --profile four-gpu startup_wait_s=45 --plan
+python strata.py ops set restart --profile four-gpu startup_wait_s=45
+python strata.py ops edit restart --profile four-gpu
+python strata.py ops plan restart --profile four-gpu --output json
+python strata.py ops run restart --profile four-gpu --if-revision RECIPE_REVISION --if-profile-revision PROFILE_REVISION
+python strata.py ops run check --profile four-gpu --output json
+python strata.py ops set check --profile four-gpu live=true --plan
+python strata.py ops set check --profile four-gpu live=true
+python strata.py ops plan check --profile four-gpu --output json
+python strata.py ops run check --profile four-gpu --output json
+python strata.py ops set calibrate --profile four-gpu report_dir=/private/path/reports
+python strata.py ops plan calibrate --profile four-gpu --output json
+python strata.py ops run calibrate --profile four-gpu --exclusive --output json
+python strata.py ops runs --profile four-gpu --limit 20 --output json
+python strata.py ops result OPERATION_ID --profile four-gpu --output json
+python strata.py ops history restart --profile four-gpu
+python strata.py ops rollback restart --profile four-gpu --to REVISION
+```
+
+`ops create NAME --profile four-gpu --kind runtime.restart|engine.calibrate.measure|components.verify` adds another typed recipe. `ops edit` opens a temporary JSON copy in `VISUAL` or `EDITOR`; invalid drafts are kept for repair. Recipe revisions are saved atomically with history. `--if-revision` and `--if-profile-revision` prevent an edited recipe or profile from running after a preview; the runtime host checks the profile revision again before draining. `ops plan` is read-only and distinguishes preview effects from the effects of a subsequent run. The calibration recipe runs the existing decode-speed sweep, creates a new report filename under its saved absolute `report_dir`, and requires a fresh `--exclusive` assertion every time. Review and apply that report with the separate `engine calibrate --review-result` and `--apply-result` commands above; a recipe run never applies tuning automatically. The component recipe reads installed files; its optional typed `live=true` setting also queries the host's GPU inventory during both preview and run. Recipes contain known kinds and typed values, never arbitrary shell command text.
+
+Each accepted `ops run` creates a local operation record with recipe/profile revisions, typed intent, start/end events and a compact outcome. `ops runs` and `ops result` read these records; they never execute anything. The store retains at most 500 records per profile by pruning the oldest completed records, and refuses new work if unfinished records alone fill the cap. An unfinished record after a caller crash is labelled `completion_unverified`; it does not prove the operation is still running or safely stopped. The journal does not store credentials, prompts, full calibration reports or raw server traces. Its files use mode 0600 and directories mode 0700 on POSIX; Windows ACL behavior still needs release qualification. Saved-profile direct `runtime start|restart|stop` and `engine calibrate --measure|--apply-result|--rollback-result` commands now write version 2 records to the same run list; read-only plans, reviews and status do not. An explicit run-config path retains its legacy, unjournaled calibration behavior. This local journal is not yet the shared Desktop operation service.
+
+To tune an installed engine, stop all instances using its devices, then measure and review a separate report before applying it:
+
+```sh
+python strata.py engine calibrate --profile four-gpu --measure --exclusive --out calibration.json
+python strata.py engine calibrate --profile four-gpu --review-result calibration.json --output json
+python strata.py engine calibrate --profile four-gpu --apply-result calibration.json --exclusive
+python strata.py engine calibrate --profile four-gpu --review-rollback calibration.json --output json
+python strata.py engine calibrate --profile four-gpu --rollback-result calibration.json --exclusive
+```
+
+To measure the **running** server after selecting the intended model and batching profile, run an explicit serving workload and keep its local evidence:
+
+```sh
+python strata.py bench run --profile four-gpu --suite serving-smoke --concurrency 8 --out ./bench-smoke-01
+python strata.py bench report ./bench-smoke-01 --output json
+python strata.py bench run --url http://127.0.0.1:8095 --suite parallel-mixed-v1 --concurrency 8 --repeat 3 --out ./bench-mixed-01
+python strata.py bench run --profile four-gpu --suite parallel-overload-v1 --concurrency 48 --out ./bench-overload-01
+python strata.py bench run --profile four-gpu --suite parallel-cancel-v1 --concurrency 8 --out ./bench-cancel-01
+python strata.py bench run --profile four-gpu --suite parallel-prefill-cancel-v1 --concurrency 8 --out ./bench-prefill-cancel-01
+python strata.py runtime start --profile four-gpu
+python strata.py bench run --profile four-gpu --require-managed-match --suite parallel-mixed-v1 --concurrency 8 --repeat 3 --condition baseline --out ./bench-baseline
+# Attach the read-only monitor in a separate terminal, then repeat the same workload.
+# python strata.py monitor --url http://127.0.0.1:8095 --interval 2
+python strata.py bench run --profile four-gpu --require-managed-match --suite parallel-mixed-v1 --concurrency 8 --repeat 3 --condition monitor-default --out ./bench-monitored
+python strata.py bench compare ./bench-baseline ./bench-monitored --output json
+```
+
+`bench run` requires a loaded instance and versioned telemetry. It sends one warmup request, a two-request serial phase and a mixed short/long streaming phase; `parallel-mixed-v1` repeats the mixed phase twice per trial. `parallel-overload-v1` instead sends one warmup, a synchronized short/long burst and a recovery request. It requires configured `max_queue` and `queue_timeout`, and `--concurrency` must exceed the reported admission limit; use up to 64 workers for this explicit suite, or up to 16 for the others. The example of 48 workers only fits a server whose reported admission limit is below 48. Expected `admission_full` and `queue_wait_timeout` responses are counted separately from unexpected errors; the suite passes only if some calls run, some are refused or time out, and recovery works. `parallel-cancel-v1` closes one active stream after its first content, then fills the effective slots and closes a queued stream, followed by a recovery request. It requires at least one queue place, a queue timeout of at least two seconds, disconnect telemetry and `--concurrency` at least the effective slot count. It checks that the target was visible, the server observed a client disconnect, companions completed and admission and slots settled. `parallel-prefill-cancel-v1` separately closes a target while the engine reports partial prompt reading in a batch slot, with one companion decoding; it requires at least two effective slots, concurrency at least two and disconnect telemetry. Both cancellation suites verify companion completion, settled resources and recovery. Run them without unrelated client traffic because the disconnect counter is server-wide. `--concurrency` is a client-worker count, not the engine's effective slot count. Supply an inference key through `STRATA_API_KEY`; if monitoring has a separate key, add `--telemetry-credential-env STRATA_TELEMETRY_KEY`. The new output directory contains `results.json`, with request latency, first-token time, output token counts when the API provides them, and sampled active/queued/occupied slots, groups and per-card readings. Prompts, answer text and credentials are excluded. The report records null when a backend signal is unavailable and labels the limits of client-observed timing. `bench run --profile NAME --require-managed-match` is an opt-in gate for a server launched by the POSIX owner host. It rejects a changed profile, changed source config, unverified owner launch, wrong telemetry instance or endpoint before creating benchmark output. It checks again after the workload and retains a failed report if the match was lost. Reports label the result `managed_launch_checked`; default, foreground and remote runs label it `unverified`. This is a beginning/end check of the owner's startup attestation, not continuous verification of running files. These source-run suites do not verify model artifact hashes or driver versions or establish four-GPU throughput on the target host.
+
+`bench run --condition NAME` records a short operator label, such as `baseline`, `monitor-default` or `monitor-fast`; it does not verify that a monitor was attached. `bench compare BASELINE CANDIDATE` reads two saved reports without contacting the server or writing files. It rejects failed runs, different suites/models, changed request fingerprints or concurrency, changed source-config digests and conflicting reported device/settings identity. It pairs phases and reports client-observed p95 TTFT, p95 latency and output throughput, plus admission/queue deltas. Missing values remain unavailable. The comparison is **provisional** even when both runs have `managed_launch_checked`: the owner match is checked only at the beginning and end, and exact driver/engine/model hashes, monitor attachment, host CPU/RSS and telemetry traffic are not attested. For the four-card overhead gate, keep at least three repeated measured phases, save `doctor --live` card/driver evidence, record PCIe and layer topology separately, measure host and monitor CPU/RSS and HTTP calls/bytes separately, and investigate changes against trial variability. A pair of reports alone is not release qualification.
+
+`profile edit NAME` opens a temporary JSON copy in `VISUAL` or `EDITOR` and validates it before saving. `profile history NAME` lists revisions; `profile rollback NAME --to REVISION` restores one. `profile set NAME KEY=VALUE` supports `host`, `port`, `parallel`, `batch_groups`, `max_queue`, `queue_timeout`, `offline` and `batch_telemetry`. The store is `%APPDATA%/Strata/profiles` on Windows or `${XDG_CONFIG_HOME:-~/.config}/strata/profiles` on Unix; `STRATA_PROFILE_DIR` overrides it for managed installations. Revisions and previous copies are saved atomically. Editing a saved profile does not change the setup-generated run config or restart an active server. Explicit CLI flags take precedence over saved overrides, which take precedence over run-config values. `profile show --effective` and `serve --plan` display that provenance and the resolved engine arguments with known credential arguments redacted.
+
+`doctor` and `components verify` inspect local engine, tokenizer, pack, model-shard and optional vision paths without starting the engine. Missing required files return exit 5. Their optional `--live` flag queries `nvidia-smi` once, with a five-second timeout, and compares selected NVIDIA device indices with the visible card inventory. The JSON report lists each card's name, UUID, memory and driver version. A live check requires `--profile`. Missing selected cards, an unavailable probe for an explicitly selected NVIDIA profile, or a HIP/other backend without a qualified live probe return exit 5. With no selected device, a successful card inventory is labelled `selection_unverified`; an unavailable probe is a warning when the backend is also unknown. The default command does not run external tools. This read-only inventory does not launch the engine or establish CUDA/HIP compatibility, PCIe topology, four-card throughput or model-file integrity. Artifact integrity still needs trusted signed manifests. `doctor` makes no repairs or downloads.
+
+`engine calibrate --plan` is a read-only preflight that names the source config digest, selected model/devices, measured settings, expected duration and component results. `--measure` runs the existing **decode-speed** sweep and writes a report with raw trials, selected settings, source/engine/tool digests and a local hardware key; it does not change the run config. `--review-result` shows the candidate and refuses a changed profile, config, engine, required model file metadata, hardware key or report contents. `--apply-result` starts a short candidate smoke generation first, saves the previous run config and setup settings with an owner-only application record, then writes calibrated args and setup's remembered calibration. A failed smoke test or settings write leaves or restores the previous config. `--review-rollback` checks that the applied config and setup settings still match that record; `--rollback-result` smoke-tests the previous config and restores both stores only when they are unchanged since application. An application made before this record existed needs manual recovery from its backup. Each action that starts the engine requires `--exclusive`; this remains the owner's assertion that other processes using those devices have stopped. On POSIX, the managed runtime host and foreground `strata serve` hold a shared local activity lease, while calibration measure, apply and rollback take its exclusive lease for the full engine action. Calibration also refuses stale or uncertain managed owner records. This blocks Strata instances launched through these paths even on a different port. The configured port is checked too, including for rollback. Direct legacy server launches, unrelated GPU processes and Windows control are not covered by this lease and still need operator verification. Report integrity is a checksum and local identity binding, not a publisher signature; full model-file hash verification is still pending. This suite does not measure multi-request throughput, TTFT or four-GPU tail latency.
+
+The basic CLI and status command use Python's standard library. The interactive monitor is an optional component:
+
+```sh
+python -m pip install -r requirements-monitor.txt
+python strata.py monitor --url http://127.0.0.1:8095
+```
+
+Use the same Python environment that runs Strata. Strata's runtime dependencies are listed separately in `requirements.txt`; the monitor dependency is not needed for `serve` or `status`.
+`strata doctor --output json` reports the optional monitor as missing, present at the pinned Textual version, or
+unverified when its version differs or package metadata is absent. This is a package-version check, not a terminal
+rendering test; an unverified monitor never blocks serving.
+
+In replica mode, the Overview labels each configured card R0, R1 and so on and keeps pipeline groups distinct across children. With opt-in batch telemetry, `p/a` shows processed/active rows per window for each replica; the 80-column view shows processed rows, while Serving and Engine show both values and sample age. Each replica has its own sample window, so the monitor does not report a server-wide batch average. The Engine and Hardware views show a child’s reported layer ranges when its startup log and launch visibility map to that replica’s configured cards; they do not present that plan as live utilization. Missing child samples display `--`. These values are engine work counters, not GPU utilization.
+
+At 128 columns by 36 rows or larger, Overview switches to a visual serving dashboard inspired by [llm-visuals](https://github.com/DingoOz/llm-visuals). It has an aggregate output-rate headline and history, engine-reported prompt/prefill and answer rates, four selected GPU meters with utilization history and VRAM, a per-slot context-capacity meter, batch rows, a group/slot state map, active slot context and token rates, and a table of multiple queued/reading/decoding requests. The Serving, Requests, Engine, Hardware and Logs pages use the same visual panels at that size. Serving shows admission pressure, concurrent requests, slot context and GPU meters; Requests keeps live, completed and selected request data visible; Engine separates batch rows and host-stage spans from GPU sensors; Hardware shows each card and its bounded history; Logs shows the redacted recent activity ring and continuity. Tab still changes the Serving selection pane, Up/Down still selects rows, Enter opens detail, and `/` filters identities and states. At smaller sizes the existing compact pages remain in use. `1ST ENGINE` is time from engine queue entry to first generated token, not network-observed TTFT. A request's `SLOT t/s` appears only when the complete slot map correlates the same pseudonymous request ID to that slot. The context bar is the largest **active** slot's reported held tokens divided by model context capacity; it is not a sum across requests. Empty or stale measurements remain `--`. No expert-routing or MTP heatmap is drawn because schema v1 does not report those measurements. These pages add no dependency beyond the optional Textual monitor package and copy no code from llm-visuals.
+
+For a read-only client on another machine, build a small portable bundle from this checkout:
+
+```sh
+python packaging/monitor_bundle.py build dist/strata-monitor.pyz
+python packaging/monitor_bundle.py verify dist/strata-monitor.pyz
+python dist/strata-monitor.pyz status --url https://HOST --json
+python dist/strata-monitor.pyz monitor --url https://HOST --once --json
+python dist/strata-monitor.pyz logs --url https://HOST --output json
+```
+
+The `.pyz` contains only the bounded telemetry client, connection store, renderers for the Overview and five detail pages, optional TUI module, the same status/monitor/logs command implementation used by `python strata.py`, and Strata's MIT license notice. It has no server, engine, model, setup code or bundled framework. One-shot status, request activity and saved connections work with Python's standard library alone; interactive mode needs an explicit `python -m pip install textual==8.2.8` in that Python environment. The adjacent version-4 `.manifest.json` records a SHA-256 checksum, exact bundle members, Python 3.10 minimum and telemetry schema 1 compatibility. The verifier still accepts older version-1 through version-3 source bundles so a local update can retain and roll back to one. The manifest has no publisher signature, so it is a source-run artifact, not a signed release component. A remote URL still requires HTTPS or a local SSH tunnel; credentials come from an environment variable through `--credential-env` or a saved reference.
+
+Before distributing a candidate to an operator, run its standard-library smoke on each target Python and OS:
+
+```sh
+python tools/portable_monitor_smoke.py --bundle /absolute/path/to/strata-monitor.pyz --report /absolute/path/to/new-smoke-report.json
+```
+
+It uses isolated `-I -S` child processes, a loopback telemetry fixture and a temporary owner directory to verify one-shot status, a digest-pinned local install and uninstall, read-only GET requests, and one structured error from deeply nested JSON. Add `--interactive` with Textual installed to check the packaged screen separately. The current r31 bundle passed both standard-library smokes on macOS with Python 3.10 and 3.11 and the optional headless interactive smoke on 3.11; real engines, GPU sensors, remote TLS, physical terminals, Windows and Linux remain open.
+
+For the source CLI, run `python tools/minimal_cli_smoke.py --report /absolute/path/to/new-report.json`. Its `-S` child processes check that help, one-shot status and monitor, missing-config serve and the missing-harness error work without Rich or Textual. It uses only a loopback telemetry fixture and does not establish that an installed inference server or engine runs without its own required dependencies.
+
+To check source serving without the optional terminal framework, create a fresh virtual environment, install only `requirements.txt`, then run `python tools/minimal_server_smoke.py --report /absolute/path/to/new-report.json` with that environment's Python. This exercises foreground and POSIX managed serving against a fake engine. It does not install model weights or prove hardware or release-package behavior.
+
+To place that client in a separate local directory without changing the server, first create its parent directory, then preview and run the offline copy:
+
+```sh
+python packaging/monitor_bundle.py install dist/strata-monitor.pyz --target /absolute/path/to/new-monitor --plan
+python packaging/monitor_bundle.py install dist/strata-monitor.pyz --target /absolute/path/to/new-monitor --if-candidate-sha256 CANDIDATE_SHA256
+python /absolute/path/to/new-monitor/strata-monitor.pyz status --url https://HOST --json
+python packaging/monitor_bundle.py update dist/next-monitor.pyz --target /absolute/path/to/new-monitor --plan
+python packaging/monitor_bundle.py update dist/next-monitor.pyz --target /absolute/path/to/new-monitor --if-current-sha256 CURRENT_SHA256 --if-candidate-sha256 CANDIDATE_SHA256
+python packaging/monitor_bundle.py rollback --target /absolute/path/to/new-monitor --plan
+python packaging/monitor_bundle.py rollback --target /absolute/path/to/new-monitor --if-active-sha256 ACTIVE_SHA256 --if-rollback-sha256 PREVIOUS_SHA256
+python packaging/monitor_bundle.py commit --target /absolute/path/to/new-monitor --plan
+python packaging/monitor_bundle.py commit --target /absolute/path/to/new-monitor --if-active-sha256 ACTIVE_SHA256 --if-previous-sha256 PREVIOUS_SHA256
+python packaging/monitor_bundle.py uninstall --target /absolute/path/to/new-monitor --plan
+python packaging/monitor_bundle.py uninstall --target /absolute/path/to/new-monitor --if-active-sha256 ACTIVE_SHA256
+```
+
+Install verifies the bundle and manifest, requires the candidate SHA-256 returned by its preview, copies only those two files into a new directory and verifies the copy. A changed or missing candidate digest is refused before creating the target. Verification caps the zipapp at 1 MiB, the manifest at 64 KiB and each member at 256 KiB. The target parent must already exist and, on POSIX, belong to the caller without group/world write permission. Update requires the current and candidate hashes from its preview, promotes a verified copy and retains the old directory as `.previous`. Rollback requires its preview hashes and exchanges the two verified directories, so the replaced copy remains available. Commit removes the verified `.previous` copy after its own hash-pinned preview; perform it before another update or uninstall. Uninstall checks the active files, requires the active SHA-256 from its preview and refuses a directory with any extra content. These operations are local and do not install Textual, change `PATH`, touch the server or download anything. They do not establish publisher authenticity or qualify a Windows/Linux release installer.
+
+`serve` runs the existing API and engine in the foreground. The profile must already be prepared. Startup does not invoke setup, download model files or open a browser. `--parallel N`, `--batch-groups auto|N`, `--max-queue N` and `--queue-timeout SECONDS` apply to this run and do not rewrite the profile. `max_queue` (0–4096) and `queue_timeout` (0.1–600 seconds) may also be set in the JSON profile. The engine may reduce the requested slot count; compare `slots_requested` with `slots_effective` in telemetry. A non-loopback bind requires a configured API key. There is no automatic tunnel or remote management. This source-run entry point opts into a 30-second graceful drain on stop (`--shutdown-timeout 0..300`); a deadline cancels requests owned by that server and returns exit 8. The legacy direct server entry point keeps its prior shutdown behavior unless given that flag.
+
+`serve --output jsonl` writes one schema-versioned lifecycle event per stdout line: `starting`, `ready`, `stopping`, `draining` and `stopped`, or `failed` if startup does not reach readiness. The ready event reports the actual bound address/port, instance ID, process ID and model state, without keys or prompt content. Human server diagnostics go to stderr in this mode. `SIGTERM` with a completed drain exits 0; Ctrl-C exits 130; a drain deadline exits 8. `serve --plan --output json` remains a single read-only preview; `--plan --output jsonl` is rejected. The direct `python -m serve.server` entry point retains its legacy human output.
+
+`--json` is a shortcut for `--output json` on one-shot commands, including profile, doctor, components, models, calibration, runtime, ops, bench, saved connection and effective config commands. `serve --json` requires `--plan`; foreground serving uses `--output jsonl`. `monitor --json` requires `--once`, and `logs --json` is one-shot; follow mode uses `--output jsonl`. The standalone monitor bundle accepts the same shortcut for its saved connection and effective config commands.
+
+`--quiet` suppresses successful human informational output on one-shot commands and the human foreground server banner, while failures still report on stderr. JSON and JSONL records are never suppressed. For `logs`, quiet hides the heading and reconnect progress but keeps the requested redacted activity rows, sequence gaps and instance changes. The interactive Monitor remains visible; `--quiet` affects only its one-shot form.
+
+Every JSONL record has `schema_version: 1`, `event` and `at` (wall-clock seconds). `starting` identifies the selected profile/model and PID; `ready` adds the instance ID, bound host/port, API URL, and model/API state. `stopping` names `sigint` or `sigterm`; `draining` reports the pending request count and deadline; `stopped` reports whether the drain finished, how many owned requests were cancelled, and the exit code. A preflight failure may be the only `failed` record. Startup failures after `starting` include `phase` and `exit_code`, with diagnostics on stderr. Consumers should use `ready.instance_id` together with live telemetry before treating a stale ready record as a running instance.
+
+`serve --ready-file ABSOLUTE_PATH` creates a JSON record after the API is bound. It contains the actual port, process and instance IDs, and distinct API/model states; a lazy server reports `model_state: unloaded`. The file contains no credentials and is removed on a handled stop. It uses mode 0600 on POSIX; on Windows choose a private parent directory because its ACL is inherited. A hard kill can leave a stale file: a host must compare the recorded instance ID with live `/v1/telemetry` before trusting it, and remove a verified stale file before reusing its path. `serve --plan` validates the requested path without writing it. The option is opt-in so existing launchers keep their old behavior.
+
+When `--max-queue` is set, at most **effective slots + max queue** HTTP inference calls are reserved at once. The cap applies to OpenAI chat completions, Anthropic messages and OpenAI Responses, including streaming calls; excess calls get HTTP 429 with code `admission_full` and `Retry-After: 1` before any SSE headers. The reservation includes model loading, prompt preparation and any server-side MCP rounds, so it is a conservative pressure bound, not an exact count of engine-queued requests. `--queue-timeout` requires the cap and limits the wait for the first engine turn after prompt preparation. A timed-out nonstreaming call gets HTTP 429 with code `queue_wait_timeout` and `Retry-After: 1`; a streaming call gets a format-specific error event because its SSE headers are already sent. The deadline stops when the engine accepts the first prompt and does not interrupt generation. Telemetry reports the configured deadline, total timeouts and oldest waiting request. Omitting these options retains the upstream admission and wait behavior.
+
+`serve --offline` refuses profiles with MCP servers or `before_load` commands and rejects remote image URLs in requests. It does not disable local API access; the bind address still controls which clients can connect.
+
+`status --json` and `monitor --once --json` return one versioned JSON object. Remote monitor URLs require verified HTTPS; a local SSH tunnel can use `http://127.0.0.1`. For a read-only monitor key, set `STRATA_TELEMETRY_KEY` on the server and pass the same secret to the client through `--credential-env STRATA_TELEMETRY_KEY` (or another client environment variable). Use a distinct inference API key: the server rejects duplicate keys. The telemetry key authorizes `/v1/telemetry` only; it cannot call inference or management endpoints. The existing `STRATA_API_KEY` also works and has its broader legacy permissions. Keys are never put in URLs or command arguments. The client refuses redirects and responses over 2 MiB. Excessively nested JSON is reported as a malformed telemetry response with the same one-record error contract, rather than a Python traceback.
+
+The interactive monitor has Overview, Serving, Requests, Engine, Hardware and Logs views. Use keys `1`–`6` or Left/Right to switch views, Tab in Serving to cycle Devices / Requests / Groups at wide and compact widths, `/` to filter requests, Up/Down and Page Up/Down to move the selected row, Home/End to jump to the first/last row, Enter to show or hide read-only request, device or slot detail, Space to freeze the display, `r` to refresh, `t` to cycle theme, `?` or F1 for help, and `q` to detach. Filter input is limited to 80 characters and cleaned of terminal controls and bidi formatters as text arrives; `q` remains ordinary text while the filter has focus. Recent detail contains bounded token and timing summaries, never prompt bodies. A selected request, device or slot stays attached to its reported ID across polls, including when a request moves from live to recent history; detail closes and the TUI says “No longer retained” if that ID disappears. An instance restart clears selection even when a new request reuses the same ID. The 60- and 40-column layouts keep the selected request visible. It never starts or stops the server. `NO_COLOR` or `--color never` uses terminal defaults. `--glyphs ascii` avoids special glyphs. The selected terminal font is controlled by the terminal, not Strata.
+
+Remote model, device and request labels are stripped of terminal controls and bidi formatters before display. The stdlib renderer clips by terminal display cells and pads fixed columns by the same measure; local cases cover combining marks, CJK names, regional-indicator flags and joined emoji at 110, 80, 60 and 40 columns. Terminal implementations can differ on ambiguous-width characters, so the renderer uses the terminal's narrow default for them.
+
+Interactive Monitor opens immediately in `CONNECTING` and fetches in the background. It labels a failed poll `STALE` while retaining the last snapshot, then `DISCONNECTED` after repeated transport failures; snapshot age remains visible and answer, prompt and aggregate output rates show `--` until a fresh sample arrives. Authorization and telemetry-schema failures show `AUTH REQUIRED` or `INCOMPATIBLE` and stop automatic retry; correct the connection or server and press `r`. Other failures retry with bounded exponential backoff and jitter. If an older server has no `/v1/telemetry` or `/metrics` but still answers `/v1/status`, the client displays `NO TELEMETRY` and the available model/status fields without inventing live work or rates. `status` and `monitor --once` still fetch once and return an error code when even status is unavailable.
+
+Logs shows recent **redacted request transitions** from the versioned telemetry snapshot: queued, admitted, prompt reading, first engine token and final outcome. Each row has an instance-scoped sequence number, time and pseudonymous request ID; it contains no prompt, answer, tool content or credential. The server retains at most 128 transitions in memory and sends only the newest 32 in a snapshot, so older events can disappear during a burst or while the monitor is detached. This is a sampled activity view, not a durable audit log or a raw runtime log. Older servers show “Request activity unavailable”; an empty supported feed says no transitions are retained. The same read-only telemetry key protects the feed, and `/` filters its visible rows. `strata logs --source runtime` reads that same bounded activity: one shot uses `--output human|json` (`--json` is an alias), and `--follow` polls every two seconds by default with `--output human|jsonl`. Follow prints explicit sequence gaps when transitions are absent from consecutive bounded snapshots and resets its cursor on a serving instance change. It stops after three consecutive connection failures; Ctrl+C detaches with exit 0. `--source harness` reports the missing shared local harness component. A separate authorized raw runtime log and push event stream remain future work.
+
+The [wide four-GPU Serving preview](terminal-previews/serving-110-color.png), [80-column parallel-request preview](terminal-previews/serving-80-light.png), [80-column recent-request detail preview](terminal-previews/requests-80-detail.png), [80-column slot detail preview](terminal-previews/serving-80-slot-detail.png) and [wide four-stage mapping preview](terminal-previews/serving-110-stages.png) and [wide sampled batching preview](terminal-previews/serving-110-batch-sample.png) are **layout fixtures**, with illustrative values. They are not hardware runs or benchmark results.
+
+## Reading the Serving view
+
+The [schema v1 telemetry field matrix](TERMINAL_TELEMETRY_FIELDS.md) gives each displayed value's source, unit, scope, sensitivity and missing-data rule. Use it when connecting another UI or consuming `status --json`.
+
+The [qualification matrix](TERMINAL_QUALIFICATION.md) lists source-run checks and the remaining target-host gates for the developer.
+
+For a repeatable client stability check, run `tools/monitor_soak.py` with an absolute new report path. `--exercise-ui` resizes the live Textual monitor across 110 x 30, 80 x 24, 60 x 16 and 40 x 12 while a synthetic server rotates an unrelated host GPU row and intermittently omits or duplicates a selected card sensor. It checks selected-card history bounds alongside reconnect, restart and read-only detach. Use `--seconds 1800 --interval 0.5 --exercise-ui` for the long soak. Its JSON is synthetic client evidence; it does not measure engine, model or GPU performance.
+
+For a portable client installation check, run `python3 tools/portable_monitor_smoke.py --bundle /absolute/path/to/strata-monitor.pyz --report /absolute/path/to/new-report.json`. It verifies the bundle and digest-pinned local install/removal, then reads only loopback fake telemetry with isolated `-I -S` Python. Add `--interactive` when Textual and Rich are installed in that Python environment to load the packaged one-screen Overview in a headless 110 x 30 terminal, check all six panels and detach. The interactive check uses isolated `-I` Python with site packages enabled for Textual. Both modes require a new absolute report path. Run them on each release OS; a passing fake-server check does not qualify real hardware or a physical terminal.
+
+On POSIX with Textual installed, run `python3 tools/portable_monitor_pty_smoke.py --bundle /absolute/path/to/strata-monitor.pyz --report /absolute/path/to/new-pty-report.json` to check live terminal cleanup. It opens a 110 x 30 pseudo-terminal, waits for the packaged dashboard and telemetry, detaches once with `q` and once with Ctrl-C, and compares terminal settings before, during and after each session. It also checks that the fake server remains readable. The Mac result is in the transfer packet; repeat it on Linux and still check a physical terminal/SSH session separately.
+
+- **Requested/effective slots:** the profile or command's requested concurrency versus the engine's reported actual slot count. A lower actual count can result from resource limits.
+- **In flight, occupied slots, engine waiting and pre-admission queued:** distinct reported fields; do not add them together as disjoint work. In flight includes requests waiting for an engine slot. Occupied slots counts non-idle slot states, so 12 in flight with 8/8 slots occupied and 4 engine-waiting is possible. Requests may be in transition during a poll. Admission reserved/limit includes all accepted HTTP inference calls; rejected is a server-lifetime count.
+- **Group:** the engine's resolved slot-to-pipeline-group map when a batch engine is active. Every request moves through the pipeline stages; a group is not a GPU assignment.
+- **GPU row:** a card's own sensor readings when available. Missing readings display `--`. A configured card with no readable sensor still has a row. An aggregate reading is never copied into four rows.
+- **VRAM trend:** the wide Overview shows a separate recent-poll memory-use percentage history for each selected card beside its current used/total GiB reading. Missing, duplicate, invalid or out-of-range card memory sensors add an unavailable gap; an outage adds a gap, and a new instance clears the history. Only selected cards are retained, with at most 32 samples per card. The 80-column view keeps current memory readings without these graphs. This is reported VRAM allocation, not GPU kernel occupancy or throughput.
+- **Request ID:** a pseudonymous server-lifetime correlation ID. Prompts, answer text, client identities and tool arguments are not included in terminal telemetry.
+- **Total output:** the interactive monitor computes the difference in server output-token counters over one common poll interval. The first sample and the first after a restart show `--`.
+- **Prompt read:** a live batch slot reports newly read prompt tokens while it is reading. The request row shows `read N new`; the total prompt-token count can include cached tokens and is therefore displayed separately. Queue wait is measured from the same server snapshot, so freezing the display freezes the wait value.
+- **First engine token:** the server measures elapsed monotonic time from entering its engine queue until that request's first generated engine token, including queue, model load and prompt reading. The live request detail and Overview's last-completed summary show this value when observed. It is **not client-observed TTFT**: HTTP ingress, tokenization before queue entry, streaming/rendering and network time are excluded. Client TTFT is measured separately by `bench run`; `--` means this server has not reported the engine value.
+- **Layer ranges and card mapping:** when an installed run records the engine startup log, Strata reads at most 2 MiB from this engine start and accepts the final contiguous `strata serve: layer split: layers ...` line. The inclusive layer ranges come from the engine after automatic split resolution. Engine GPU ordinals map to physical card indices only when the child process has an unambiguous numeric visibility list. Otherwise the ranges are shown without a claimed card mapping. An unloaded model has no current resolved stage plan. This reports allocation, not live occupancy.
+- **Batch rows/window:** opt in with `strata serve --batch-telemetry` or `profile set NAME batch_telemetry=true` before starting the server. A supporting engine emits one bounded `BSTAT` sample about once per second while batch windows complete, plus a final partial sample at idle; its counters reset after each emission. The monitor shows average **processed verifier rows/window** and **active request slots/window** over that sample, its window count, elapsed span from the first included window start to the last completion, and age. Overlapping pipeline windows can share that span; it is not a sum of window times. Pipelined groups may process idle padding rows, and batch MTP may process two rows for one active slot, so the averages can differ. A single request on the solo path has no batch sample. The Overview and wide visual detail pages show `--` for a retained sample older than five seconds and omit it from the trend; compact Serving and Engine keep the last sample with its age. Older engines and the default-disabled path show `--`. This source-run implementation has not yet been built or qualified on CUDA, HIP or SYCL hardware.
+- **Pipeline stage in-flight time:** the same opt-in engine mode emits bounded `PSTAT` host spans for grouped pipeline execution. About once per second and at idle, each stage reports how much of the sample interval elapsed between its window launch and completed poll. The wide Engine page shows that in-flight fraction per stage only for a recent sample; an older retained sample becomes `--`. Compact Serving and Engine retain the last value with its reported age. It includes host polling delay and is **not GPU kernel utilization or hardware occupancy**. Non-grouped batch mode, older engines and the default-disabled path show `--`. Without a usable startup log, exact layer ranges and card mapping stay unavailable; a stage number alone does not prove physical placement. This source path still needs native-backend and four-card qualification.
+
+For a four-card run, record the exact GPU model/VRAM, driver, selected device IDs, layer split, model revision, context, requested/effective slots and groups before comparing throughput or latency. The UI is not a benchmark. Use the current `docs/BATCHING.md` and `docs/MULTI_GPU.md` for supported engine modes and limitations.
+
+## Current limits
+
+The `strata code` command returns a missing-component error because the shared Desktop harness source and its session/approval contract have not been integrated. No separate coding-agent loop is bundled here. The source-run checkout now has a POSIX owner bridge, recoverable benchmark and calibration journal receipts, a redacted request-activity feed and a portable read-only monitor bundle. Windows runtime ownership and locking, remaining Desktop authority mappings, complete management journal coverage, signed whole-runtime distribution and qualified native batch/stage samples are pending. Calibration and serving benchmarks have not been run on a real model in this checkout. This implementation does not establish a macOS inference-engine port or four-RTX-6000 performance.
diff --git a/docs/TERMINAL_IMPLEMENTATION_STATUS.md b/docs/TERMINAL_IMPLEMENTATION_STATUS.md
new file mode 100644
index 000000000..565ee99a4
--- /dev/null
+++ b/docs/TERMINAL_IMPLEMENTATION_STATUS.md
@@ -0,0 +1,51 @@
+# Terminal work against the 10 October 2026 implementation plan
+
+Source baseline for the original milestone: `Niko1221/Strata` at `fb58e0dbc8399662c0e47c76578c6e878b14f6cf`. Branch `feat/terminal-cli-monitor-current` merges the public `main` fetched on 11 October 2026 at `61b3fb5dd3f1e8ec09cf7e4e05208bc6d3c46406`. The plan lives at `../output/strata-terminal-implementation-plan.md` in the parent design workspace. This is a working implementation, not a qualified release.
+
+Current-main integration checks on macOS: 706 server tests passed with 11 skipped, all 218 terminal tests passed, and the C++20 batch/stage sampler compiled with warnings as errors and passed. The imported editable Desktop app passed TypeScript checking, a production build and 116 Node tests. The broad setup suite ran 465 tests with two failures and four errors; representative CUDA build and prebuilt-download failures reproduce on a clean public-main checkout, while HIP errors need a ROCm environment absent here. Fake-engine two-replica request/slot correlation and configured card assignment are covered; native GPU builds, native per-replica batch/stage qualification, Windows/Linux install, full Desktop authority and coding harness remain open. The Desktop native shell now supports an opt-in, owner-backed single-profile Serving Start/Stop/Restart/Verify preview, a read-only six-panel Monitor, a read-only Components screen with manual host GPU probe, a reviewed Profile editor for source run config and typed serving overrides, a read-only Models screen with per-config detail and GGUF preflight, a Benchmarks screen for reviewed managed runs, saved reports, workload-checked comparisons and private Markdown export, and a native Calibration screen for reviewed measure/apply/rollback through a pollable host job and shared journal; prototype mutations and its demo monitor sampler are disabled.
+
+Desktop calibration now saves owner-only stage/sample progress, checks an exact worker lease across fresh host processes, and accepts an operator stop request only for the active measurement job. The request is passed into engine generation and the final receipt distinguishes cancellation from success or uncertain completion. The worker does not emit raw prompts or measurements to the browser. Apply and rollback are not cancellable in flight; abrupt worker death, real engine stop latency and Windows locking remain qualification gates.
+
+The source-run Overview now follows YASD's asymmetric two-column composition: serving, prompt/answer speed and batch pressure on the left; four selected GPUs, live requests and activity on the right. The 80 x 24 view keeps its footer; the 110 x 30 view keeps the four card rows, request queue and pipeline groups; a taller view adds reported session totals and model/engine facts. Wide views show separate bounded load and VRAM histories for each selected card, plus batch and pre-admission histories with visible ranges; replica mode keeps child batch trends separate. VRAM history uses each card's reported used/total memory, records gaps for missing or ambiguous sensors and resets with the server instance. The 80-column view keeps current memory readings without VRAM graphs. Missing newest values and batch samples older than five seconds hide their trends. The Overview also hides current batch and host-span numbers when their engine samples are older than five seconds; the detail views retain the last reading with its age. The illustrative captures were regenerated from the current renderer. These layout checks do not establish real four-card measurements.
+
+The replica-specific follow-up maps child slots and pipeline groups into distinct global IDs, attaches replica IDs to active requests, and labels configured GPU groups in the Overview and adds a local stage label to each card only when one engine-reported stage maps there. It shows each live child engine's validated BSTAT processed/active rows per window separately, with sample age in the Serving view. Child startup logs can also report per-replica stage/layer ranges and physical cards when the child's launch visibility order matches its configured card group. Each child now also reports its validated PSTAT host-stage sample, with local stage percentages and age in the Engine view and separate R0/R1 lines in the wide Overview. Server-wide rows/window and stage timing remain unavailable in replica mode because the children have independent sample windows. These host spans include polling delay and are not GPU utilization. Illustrative 110- and 80-column four-card replica screenshots are in the transfer packet; their values are fixtures, not hardware results.
+
+| Plan phase | Current state | Remaining gate |
+| --- | --- | --- |
+| T0 references | Upstream, YASD and current UI tokens recorded in the plan | Receive/audit supplied TUI zip and DeepSeek harness repo; freeze UI revision and rights |
+| T1 CLI/serve | `strata.py` grammar; foreground server wrapper; named owner profiles with typed overrides, plan/edit/history/rollback, explicit use-config source selection and effective-value origins; separate saved monitor connections with editable URL/prefix/credential reference and `config show --effective`; typed local operation recipes with edit/plan/run/history/rollback and a bounded recipe-run journal; ephemeral concurrency and queue-cap overrides; offline request checks; non-loopback key preflight; opt-in ready file with actual port and instance/model state; opt-in graceful drain; POSIX owner host with start/status/restart/stop and a shared serving activity lease, prior-argv rollback, guarded hard-kill recovery, private launch attestation of config bytes and server arguments, previewed distinct-file source switching and in-place config migration with rollback, reviewed owner/instance restart preconditions checked before journaling and again inside the owner, authenticated generation readiness and explicit `runtime verify` with an optional reviewed owner/instance plan; one-shot JSON with `monitor --once` required for JSON output | Windows owner IPC/ACL, shared journal and Desktop integration, real engine stop/restart qualification, Linux package tests |
+| T2 telemetry | Versioned `/v1/telemetry`; bounded read client with occupancy derived only from complete slot reports; 4-GPU per-card rows; engine slot groups and pseudonymous request correlation; read-only telemetry key; admission pressure, queue deadline and rejection counters; server first-engine-token timing; bounded engine-start-log layer ranges and stage/card mapping when visibility order is unambiguous; opt-in engine BSTAT rows/window, separate per-replica BSTAT rows/window and PSTAT stage host spans, plus grouped-pipeline PSTAT stage host spans (source integration, not hardware-qualified); bounded redacted request transitions in the snapshot, with client-observed sequence gaps | GPU kernel occupancy, non-grouped stage timing, client-observed TTFT/cache and native-backend qualification; log-free topology source, key rotation/packaging, push event stream |
+| T3 monitor | Six-view optional Textual shell; YASD-inspired one-screen Overview with separate Serving, Performance plus bounded output trend, Batching/Parallel, selected-GPU histories with bounded current-card retention, missing-sensor placeholders without stale graphs, Requests and Activity panels at 80+ columns; matching visual Serving, Requests, Engine, Hardware and Logs pages at 128 × 36 and larger; compact text fallback at 60/40 columns with selected-row priority and same-event resize rendering; bounded local device history; freeze, filter, theme, refresh and detach; aggregate throughput restarts from a healthy post-outage baseline and unexpected collection failures show a redacted stale/disconnected state; scrollable live/recent request selection with bounded detail; read-only device/slot drilldowns; stable row identity and explicit retention loss across polls and instance restarts; Serving pane selection and page/home/end keyboard navigation at wide and compact widths; reported stage ranges and sampled pipeline stage in-flight fractions shown in Serving/Engine; Logs shows recent redacted request transitions, observed retention gaps and instance resets; slot phases and group occupancy require a complete, unambiguous slot report | GPU kernel occupancy, visual QA and reconnect/resize soak on real Windows/Linux terminals, real single/four-GPU workloads and overhead qualification |
+| T4 code | Missing-component exit 5 avoids a second agent loop | Integrate supplied shared harness/session API; Desktop parity, approvals, leases, scripted JSONL and policy exit 7 |
+| T5 components/release | Optional `requirements-monitor.txt`, source-run documentation, standard-library saved monitor connections in the portable client, read-only `doctor`/`components verify` inventory, setup-config `models list --installed` and `models inspect MODEL_ID`, telemetry-backed `models list --served`, and read-only `models import PATH --plan` with bounded GGUF v3 metadata/tensor-directory and payload-extent and overlap checks, routed-expert encoding signals and known setup-selection hints, opt-in bounded NVIDIA host-card/driver probe that verifies selected indices | Actual model adoption, signed component manifests, engine/backend compatibility, qualified HIP/other live probes, installer/update/rollback, cross-platform qualification, notices and measured performance budget |
+| T6 operator integration | Handoff contract documented in `docs/DEVELOPER_INTEGRATION_HANDOFF.md`; versioned owner-local runtime operation bridge in `strata_control.management`, called by CLI and by a single-profile Desktop Serving screen through an opt-in loopback route with review/execute Start/Stop/Restart/Verify and owner/instance preconditions for verification; a read-only native Monitor route and six-panel UI that check owner/telemetry instance identity, bound fields, keep the telemetry key on the host and omit the prototype monitor ticker; a read-only native Components route and screen using the same CLI inspection path with an explicit opt-in live GPU probe; a native Profile screen that previews and saves source config and typed serving overrides through the same revisioned store as CLI, with a 90-second server-side review and source digest check; a native Models screen that lists setup-written run configs, inspects one config and previews a GGUF file set through the CLI's bounded read-only paths; a native Benchmarks screen that reviews a bounded workload against the managed owner and loaded instance, launches the shared benchmark runner through a pollable host job with private phase progress and an exact-output saved-profile lease check, active/ended lease status and a durable journal receipt recoverable by job ID after host restart, overlap refusal, accepts exact-run operator cancellation from CLI or Desktop, saves a distinct cancelled outcome, reads saved reports, distinguishes incomplete suites, shows phase metrics, compares compatible workloads and downloads private Markdown; a native Calibration screen that reviews decode measurement, apply and exact rollback, requires exclusive-access acknowledgement, pins source/report digests and polls a host job with an owner-only receipt, exact worker lease, bounded decode-sweep progress and exact active measurement cancellation; saved reports reconcile finished measurements after host restart; native Restart separately reviews selected source switches and in-place config migrations before drain; prototype mutations disabled in that mode; local profile and recipe schemas, editors, typed `set`, revision/rollback, read-only component inventory, calibration measure/review/apply, explicit serving benchmark reports with read-only, workload-checked comparison, private Markdown export and optional pre/post owner-launch matching; a POSIX owner runtime host with macOS fake-engine hard-kill recovery, generation probe and previewed in-place config migration | Full Desktop operation authority, model adoption, calibration abrupt-worker cleanup, real-engine stop latency and target-host recovery qualification; Windows control transport; ambiguous-state/manual recovery, real-GPU drain/restart, unmanaged/Windows calibration exclusivity and full recipe capability/UX audit |
+
+Tests are under `tests/terminal/` and the existing server tests under `serve/`. No RTX 6000 hardware or model pack is present in this design checkout, so hardware acceptance must be run on the intended machine with the exact card generation and driver recorded. Telemetry marks missing values with null/`--`.
+
+Latest local checks on macOS with Python 3.11 and a mock/fake engine: `tests/terminal/` ran 218 tests with the optional Textual dependency installed (all passed), including the one-screen overview at 110x30 and 80x24 and bounded, cleaned filter paste with keyboard focus; the merged public-main `serve/` suite ran 706 tests (11 skipped, all others passed). A live mock HTTP request produced a bounded redacted activity sequence visible through the read-only telemetry key, and the client kept malformed, untrusted event fields out of the Logs view. The source-run `status --json` and `bench run --output json` commands reached live mock servers on OS-assigned ports. Saved read-only connection profiles resolved a proxy prefix and environment credential reference in both the source CLI and a standard-library-only portable bundle; effective output omitted the secret. The managed runtime was exercised with a fake engine through start, read-only restart preview, an edited recipe restart, edited-profile restart, failed-activation rollback, stop, hard-killed host recovery, authenticated one-token generation verification, private config/argv launch attestation, a rejected config-read race and an explicit lazy-model load. POSIX managed and foreground serving leases excluded calibration from overlapping engine actions, including a different-port owned host; rollback gained the configured-port preflight. A profile source switch to a distinct config was previewed, digest-pinned and generation-verified against a fake engine; failed activation restored the prior owned launch. An edited run config was previewed and digest-pinned, then restarted with a private original-bytes snapshot; a failed activation restored the prior launch from that snapshot without overwriting the edited file. A managed benchmark matched the owned launch before and after a fake-engine workload; mismatches were refused before output or retained as failed evidence after the workload. An owner-local benchmark lease probe identified one exact output path as active, then ended after its separate holder process was killed; another path stayed untracked. An active mock HTTP stream was stopped through the owner-local cancel action and saved a distinct cancelled report and progress record. A new owner-bridge process read the same journal job ID, and a saved report reconciled a receipt left running by an interrupted worker. The standalone C++ batch/stage sampler compiled and passed with clang++ C++20 warnings as errors; a fake batched engine carried PSTAT through the server without contaminating replies. An earlier 60.29-second synthetic Monitor soak also passed two outages, one restart, bounded 32-sample output-rate history, single in-flight polling and detach without stopping the fake telemetry server; see `monitor-soak-60s-current-2026-10-11.json`. It remains client stability evidence. These checks do not establish CUDA/HIP/SYCL engine builds, Windows/Linux package behavior, four-card performance or Desktop harness parity.
+
+A 30.31-second synthetic Textual soak on the compact-renderer revision exercised repeated 110x30, 80x24, 60x16 and 40x12 resizes, four selected GPU cards, missing and duplicate card sensors, two disconnects and one restart. It passed bounded device/output histories, one in-flight read and detach; see `monitor-soak-30s-ui-fixed-2026-10-11.json`. The compact and detail views now replace cached model, request and GPU work with a connection panel during initial attach, disconnect, credential rejection and incompatible telemetry. A later 30.34-second run passed on the palette/host-span display revision `e885bf8`; see `monitor-soak-30s-ui-current-2026-10-11.json`.
+
+A later 30.32-second synthetic Textual soak on the batch/queue trend revision passed the same four resize sizes, two outages, one restart, one in-flight read and detach. Batch and pre-admission histories stayed below the 32-sample limit, including gap markers; see `monitor-soak-30s-work-trends-2026-10-11.json`. These are client stability checks with fixture telemetry, not GPU performance results.
+
+A new 30-second synthetic Textual soak on the VRAM-trend revision passed the same resize, outage, restart and detach scenarios. Both selected-card load and VRAM series remained within four cards and 32 samples each and retained unavailable gaps for missing or ambiguous sensors; see `monitor-soak-30s-vram-final-2026-10-11.json`. The percentages are derived from fixture memory readings, not measured GPU occupancy or throughput.
+
+The current r31 portable monitor bundle passed an isolated standard-library HTTP and digest-pinned local install/status/uninstall smoke with Python 3.10.20 and 3.11.15 on macOS ARM64. Each run made three telemetry GETs, including one malformed-response probe, and no other HTTP methods; the raw reports are `portable-monitor-stdlib-smoke-py310-r31-2026-10-11.json` and `portable-monitor-stdlib-smoke-py311-r31-2026-10-11.json`. Eight focused bundle lifecycle tests also passed under Python 3.10. This does not establish Linux/Windows installation.
+
+The same r31 bundle passed an optional packaged Textual 8.2.8 headless check on Python 3.11.15: it imported the interactive Monitor from the `.pyz`, connected to loopback telemetry, rendered all six one-screen Overview panels at 110 x 30 and detached with `q`. The full check made four telemetry GETs and no other methods; see `portable-monitor-interactive-smoke-py311-r31-2026-10-11.json`. It is not a physical terminal, target OS or real-engine qualification.
+
+A separate macOS POSIX pseudo-terminal smoke launched packaged r31 at 110 x 30, saw live telemetry and raw/no-echo mode, then detached with `q` and Ctrl-C in separate sessions. Both exited 0, restored the exact prior terminal settings, and left the fake telemetry server readable; see `portable-monitor-pty-smoke-py311-r31-2026-10-11.json`. The Ubuntu/Python 3.11 CI workflow includes this check but has not run; physical Linux/Windows terminal qualification remains open.
+
+A deep-JSON loopback regression now checks that source and isolated portable status commands return a single redacted exit-3 error for a malformed nested response; the client no longer exposes a Python recursion traceback.
+
+A Linux/Windows GitHub Actions matrix now defines bundle-build and standard-library smoke jobs on Python 3.10 and 3.11, plus optional packaged Textual Overview checks on 3.11. The matrix has not run in this local checkout; target-platform evidence remains open.
+
+The same matrix now includes a source CLI `-S` smoke before optional terminal dependencies are installed. Local Python 3.10 and 3.11 runs passed help, one-shot status and monitor, offline serve's missing-config exit 5 and coding CLI's missing-harness exit 5, with exactly two loopback GETs and no other methods; see `minimal-cli-no-site-py310-2026-10-11.json` and `minimal-cli-no-site-py311-2026-10-11.json`. This proves those dispatch paths do not require Rich/Textual; actual engine startup and clean minimal release installation remain open.
+
+A fresh Python 3.11 virtual environment with only `requirements.txt` and no Rich/Textual passed all 32 owned-runtime integration tests on macOS, including foreground JSONL ready/stop and POSIX owner start/restart/stop. See `minimal-server-runtime-module-macos-py311-2026-10-11.json`. A new Linux CI job provisions the same runtime-only environment, but it has not run. This proves source-checkout serving without the optional terminal framework in those tests; real-model, GPU, Windows and packaged installer gates remain open.
+
+The full `serve/` suite passed in that same runtime-only environment: 706 tests ran in 270.073 seconds, 11 skipped and no failures; see `minimal-server-serve-suite-macos-py311-2026-10-11.json`. The Linux CI job now runs both the owned-runtime and server suites; it remains unrun. This is fake-engine/source-checkout evidence, not a clean target installer or actual GPU result.
+
+The sample-age Overview revision passed 215 terminal tests and a 30.35-second synthetic Textual soak with 20 resizes across the four sizes, two outages, one restart, at most 26 retained batch/queue samples, one read in flight and detach while the server remained readable; see `monitor-soak-30s-current-work-age-2026-10-11.json`. Focused renderer checks show stale single-engine and replica BSTAT/PSTAT samples as unavailable in Overview. Native engine timing remains unqualified.
+
+The 30-minute synthetic UI stress run launched on monitor revision `ba138f6` passed in 1,800.31 seconds, with 360 resizes across all four sizes, two outages, one instance restart, four selected-card histories, missing/duplicate sensor gaps, no more than 32 samples per history, one HTTP read in flight and detach without stopping the synthetic server. It handled 3,581 GETs, four expected HTTP failures and no non-GET methods; final traced-memory growth was 597,327 bytes from its post-start baseline. Its 26 RSS samples cover the final 25 minutes, from 44,880 to 45,904 KiB, with a 480 KiB first-to-last change. See `monitor-soak-30m-ui-2026-10-11.json` and `monitor-soak-30m-ui-rss-2026-10-11.csv`. Later palette and label changes do not alter the collection path; the shorter run covers their display revision. These are synthetic client checks, not target-terminal or inference-overhead qualification.
diff --git a/docs/TERMINAL_QUALIFICATION.md b/docs/TERMINAL_QUALIFICATION.md
new file mode 100644
index 000000000..741ef583a
--- /dev/null
+++ b/docs/TERMINAL_QUALIFICATION.md
@@ -0,0 +1,80 @@
+# Terminal qualification matrix
+
+This matrix separates checks already run in this source checkout from release gates that need the supplied UI/harness/TUI assets or a target host. A passed synthetic client test does not establish engine performance or platform support. Record exact commands, source commit, artifacts and environment for every final gate.
+
+| Gate | Evidence in this checkout | Remaining acceptance work |
+| --- | --- | --- |
+| Telemetry contract and privacy | Versioned `/v1/telemetry`, bounded client sanitization, read-only key, mock/fake-engine terminal and server tests. Field meanings: [telemetry matrix](TERMINAL_TELEMETRY_FIELDS.md). | Review the actual UI data binding and run a redaction audit with real workloads. |
+| Serving, batching and four-card display | YASD-inspired one-screen Overview at 110 and 80 columns, including bounded aggregate-output, batch-row and pre-admission queue trends and selected-card histories with unavailable rows for missing sensors, with compact detail views at 60 and 40; fake batched engine tests for slot/group/queue and BSTAT/PSTAT transport; occupied slots and read/decode/idle phases require a complete, unique slot report; exact group occupancy additionally requires a valid group on every slot. Display-cell clipping tests cover CJK device/request labels, combining marks, flags and joined emoji. The Overview suppresses retained BSTAT/PSTAT samples older than five seconds while detail keeps their reported age. Screenshots are illustrative. | Native CUDA/HIP/SYCL build and tests; measured four-card sensors, stage visibility, requested/effective slots, batch rows/window, group mapping and per-request progress on the exact target hardware. Repeat Unicode layout checks on supported Windows/Linux terminals. |
+| Two-replica monitor contract | A fake-engine HTTP test correlates the second replica's live request with global slot 5 and global group 1, checks configured [[0,1],[2,3]] GPU assignment, keeps each child's BSTAT rows/window and PSTAT host-stage spans separate, and reports each child's startup stage/layer ranges only when its launch visibility order maps into the configured card group. Terminal tests sanitize bounded replica IDs, samples and stage plans, reject mismatched device assignments, and render R0/R1 and uniquely mapped local stage labels at 110 and 80 columns. The 110- and 80-column screenshots are synthetic. | Qualify the mapping, per-child sample age, startup log and request progress with the intended four-card hardware; qualify per-replica PSTAT host spans on native hardware; GPU kernel occupancy remains unavailable. |
+| Parallel and cancellation behavior | Mock and fake-engine overload, active/queued disconnect and partial-prompt disconnect suites; server tests. Ten fresh fake-engine active/queued cancellation cycles passed; each recovered, exited its child and closed its listener. | Sustained multi-client load on the real model, ten load/generate/cancel/unload cycles, no orphan workers or cross-request content, and recorded recovery latency. |
+| Read-only monitor stability | Unit and integration tests for v1/legacy and status-only fallback, reconnect, freeze, resizing, bounded rows and detach. Explicit connecting, stale, disconnected, auth-required, incompatible and telemetry-unavailable states mask cached rates; all six views replace cached request/GPU values with a connection panel for connecting, disconnected and blocked states. Headless tests cover automatic and manual recovery, plus a 110-to-40-to-110 terminal resize with selected request detail retained and the tiny footer visible. Headless tests also verify that the live Overview and Logs expose observed sequence gaps after a frozen display resumes and reset that notice on a server instance change. An outage now clears the aggregate-rate baseline and an unexpected collector exception becomes a redacted stale/disconnected state; the first recovered sample does not claim a cross-outage rate. A native Desktop browser smoke checked the same rate reset while retaining the observed activity gap. The 30-minute synthetic 0.5-second headless soak passed with two outages, one instance restart, bounded request/activity rows, one in-flight HTTP collection and a readable server after detach. Raw JSON and late-run RSS series are in the transfer packet. | Repeat on target Linux/Windows terminals and with the real server. Measure server and client CPU/RSS separately in the hardware run. |
+| Command and lifecycle safety | POSIX owned fake-engine start/verify/restart/rollback/stop, digest-pinned source migration, calibration review/apply/rollback, typed recipes and bounded journal tests. A one-shot owner-local JSON bridge shares runtime actions and journal records with CLI; malformed requests and stale start reviews are rejected before engine launch. Stale stop reviews are rejected before drain, including at the owner host. The owner host repeats the start revision/digest check after process handoff. Foreground `serve --output jsonl` emits typed ready/drain/stop records with JSON-only stdout in fake-engine SIGTERM and Ctrl-C subprocess tests. The `--json` shortcut covers all 43 human/JSON parser leaves, including portable connection/config commands; streaming modes reject incompatible combinations. Quiet-mode tests cover human success/error handling, requested log rows, portable one-shot output and JSONL serving through a generated response. Source and portable clients reject JSON monitor output without `--once` before opening a connection. | Connect Desktop to one lifecycle authority and operation journal; qualify Windows ownership and ACL; test real model, corrupted components, lost GPU and long-running cancellation. |
+| Optional installation | Portable monitor zipapp verified by adjacent SHA-256/member manifest; version 3 includes the one-screen dashboard, records telemetry/Python compatibility and bundles the MIT notice while verification still accepts versions 1 and 2 for update/rollback. Offline local digest-pinned install/update/rollback/commit/remove tests; eight focused bundle tests passed on Python 3.10 and 3.11 on macOS. The current r31 bundle passed isolated `-I -S` one-shot HTTP, verified install, installed status and digest-pinned uninstall smokes on both interpreters against a loopback fixture; each made three telemetry GETs, including one deeply nested JSON error probe. A separate `-I` headless packaged Textual check on Python 3.11 imported the Monitor from the bundle, connected, rendered six Overview panels and detached; it made four telemetry GETs total with the lifecycle and malformed-response checks. The default setup dependency list now excludes CMake/Ninja; the local compile path installs only missing build helpers from a separate pinned file. `doctor` now distinguishes absent, pinned and unverified Textual versions without importing the optional TUI into serving. | Signed release artifacts, publisher trust, clean Windows/Linux installation, optional Textual dependency and rollback qualification. Verify a fresh ready-made-engine setup has no CMake/Ninja in its private environment, then qualify local compilation on each target backend. |
+| Harness and native host runtime | `strata code` reports missing component; host-adapter contract is in the architecture plan. The imported Desktop has an opt-in, loopback, single-profile owner-backed Serving status and reviewed Start/Stop/Restart path. Its native Monitor now reads bounded v1 telemetry through the host, verifies the owner instance ID, retains the read-only key on the host, shows six live panels and leaves missing sensors unavailable; native mode does not start the prototype monitor sampler. A read-only Components screen uses the same Python inspection report as the CLI, with a manual live GPU probe and bounded browser fields. A native Profile screen reviews a source run config and typed serving overrides, pins revision and digest for save, and leaves the running instance unchanged; installed model choices come from the same Python inventory as CLI. Native Restart requires a second explicit review for source switching or in-place migration and passes those allowances to the owner. The shared management bridge and owner now reject a stale Restart owner/instance review before drain; editable restart recipes accept the same reviewed identities and config digest. It passed Node host route tests for runtime, components, profile save and saved benchmark report/compare with the real Python bridge. Native Calibration now reviews the same Python decode-sweep plan, apply and rollback as CLI, requires a single-use review and exclusive-access acknowledgement, and exposes a pollable host job while journaling the underlying action. Fake-engine Python tests cover stale digests, measure, smoke apply and exact rollback; a real browser fixture checked review and responsive layout, not a real engine action. Calibration and benchmark host jobs save owner-only progress and journal receipts; a restarted host can query the same job ID and reconcile a finished report. Exact-run leases distinguish an active worker from a released path, and both workflows accept cancellation. Abrupt worker death, real-engine stop latency and Windows locking still need qualification. Chat, Tuning and the browser profile store remain prototype. | Supplied DeepSeek harness and TUI source audit, common session/approval behavior, coding CLI parity, remaining Desktop mappings, abrupt-worker and real-engine lifecycle tests, Windows locking, and LM Studio/Unsloth host integration tests. |
+| Performance overhead | Bench tool records privacy-safe latency/TTFT and compare metadata; no real GPU result exists. | Fix budgets from M0 baseline. Run no-client, default Monitor, 0.5-second Monitor and Monitor-plus-code-client on identical workload, at least three retained trials after warmup. Record tokens/s, client TTFT, queue wait, cancellation latency, server/client CPU/RSS and HTTP calls/bytes/s with raw reports. |
+
+## Evidence record for the developer
+
+Use the transfer packet's commit/patch and the exact baseline described in `DEVELOPER_INTEGRATION_HANDOFF.md`. The 11 October checkout passed 218 terminal tests, including a headless filter paste/focus check, 706 server tests (11 skipped), and 116 Desktop Node tests with TypeScript checking and a production build; the replica HTTP and rendering tests use fake engines and illustrative fixture values. `monitor-soak-synthetic-2026-10-10.json` records a passing 1,800.28-second synthetic client run: four expected HTTP failure responses across two disconnects, recovery after a server instance change, 32 activity and 50 request rows retained, one maximum in-flight collection, zero non-GET methods and a readable server after detach. It recorded 3,577 GETs, 27,487,739 response bytes, 89.734 seconds of combined process CPU and 17,338 bytes of final traced-memory growth from its post-start baseline. `monitor-soak-rss-samples-2026-10-10.csv` contains 45 combined-process RSS samples over the final 1,320.7 seconds, ranging from 32,992 to 42,912 KiB; it did not cover the first eight minutes. The synthetic sampler's 20 MiB growth limit is a regression threshold, not a release performance budget. None of these results proves native RTX 6000 throughput. The available machine is macOS ARM64 and has no NVIDIA host/container runtime. A local UI handover ZIP exists in the parent workspace; the final TUI ZIP and DeepSeek harness repository have not been supplied to this checkout.
+
+`portable-monitor-stdlib-smoke-py310-r31-2026-10-11.json` and `portable-monitor-stdlib-smoke-py311-r31-2026-10-11.json` record the current r31 portable bundle on macOS ARM64 with Python 3.10.20 and 3.11.15. Both used `-I -S`, verified the bundle, read one versioned loopback telemetry snapshot, installed into a new temporary owner directory with its SHA-256 pinned, read status from that installed copy and removed it with its digest pinned. Each used exactly three GETs, including one deeply nested JSON error probe, no other HTTP methods and no site packages. `tools/portable_monitor_smoke.py` repeats the check on a target host. This is client and local packaging evidence, not Linux/Windows distribution or Textual rendering qualification.
+
+A local loopback server returning a syntactically valid but excessively nested JSON response produced one redacted `ClientError` in both source and isolated portable status clients, with exit 3 and no traceback. The full 218-test terminal suite passed after the parser boundary fix.
+
+`portable-monitor-interactive-smoke-py311-r31-2026-10-11.json` records the same r31 bundle on macOS ARM64 with Python 3.11.15 and locally installed Textual 8.2.8. The optional `--interactive` mode ran the lifecycle check, then imported `strata_cli.monitor` from the `.pyz` in an isolated `-I` process, connected to loopback v1 telemetry, rendered all six one-screen Overview panels at 110 x 30 and detached with `q`. It made four GETs total and no other HTTP methods. This is packaged headless rendering evidence; target OS terminals and actual engine telemetry remain unqualified.
+
+`portable-monitor-pty-smoke-py311-r31-2026-10-11.json` records the packaged r31 Monitor in a real POSIX pseudo-terminal on macOS ARM64. Both `q` and Ctrl-C sessions entered raw/no-echo mode, exited 0, restored the exact prior terminal settings and left the loopback telemetry server readable. Each session fetched one telemetry snapshot; the final server-alive check made one more GET, with no non-GET methods. `.github/workflows/terminal-portable-monitor.yml` now schedules the same PTY check on Ubuntu/Python 3.11 after installing Textual, but that CI job has not run. This does not qualify Windows Terminal or a physical Linux terminal/SSH session.
+
+`minimal-cli-no-site-py310-2026-10-11.json` and `minimal-cli-no-site-py311-2026-10-11.json` record source CLI checks on macOS with Python `-S`, which hides site packages including Rich and Textual. Help, JSON status, JSON one-shot monitor, missing-config offline serve and missing-harness coding error returned their expected schemas and exit codes. The loopback server saw two GETs and no other methods. The Windows/Linux CI matrix now includes this check but has not run. This proves lazy source dispatch for these paths; it does not prove a real engine serves in a clean minimal installation.
+
+`minimal-server-runtime-module-macos-py311-2026-10-11.json` records a separate, newly created Python 3.11 virtual environment containing only the pinned `requirements.txt` runtime packages. Rich and Textual were absent. All 32 owned-runtime integration tests passed, including foreground machine JSONL ready/stop, managed start/restart/stop, source migration, rollback and fake-engine generation checks. `.github/workflows/terminal-minimal-server.yml` now repeats this module in a fresh Ubuntu virtual environment, but has not run. The report establishes source-checkout serving with a fake engine and excludes actual model, GPU, Windows, release-package and one-click installer qualification.
+
+The full `serve/` suite also passed in that same environment: 706 tests ran, 11 skipped, all others passed in 270.073 seconds; see `minimal-server-serve-suite-macos-py311-2026-10-11.json`. Its SHA-256 links to the retained local raw log. The Linux CI job includes this full suite but has not run. These tests use fake engines and do not qualify actual model loading, GPU drivers or target-host installation.
+
+`.github/workflows/terminal-portable-monitor.yml` defines a small Linux/Windows matrix for Python 3.10 and 3.11. It builds the bundle from source and runs the same standard-library smoke; the Python 3.11 jobs additionally install the optional Textual dependency and exercise the packaged Overview. The workflow has not run in this local checkout. Retain its run URLs and reports after the integration branch is published; passing CI still does not replace a physical terminal, full installer or real-engine qualification.
+
+`monitor-soak-60s-status-2026-10-10.json` records a separate 60.31-second synthetic run on an earlier Monitor lifecycle revision. It exercised the interactive connecting path, saw stale state during two outages, recovered after one synthetic instance restart, retained 32 activity and 50 request rows, kept at most one in-flight collection, and left the test server readable after detach. It made 100 GETs, received four expected HTTP failures and used no other HTTP methods. The shorter run checks those lifecycle changes; it does not replace the earlier 30-minute memory-stability evidence or target-hardware qualification.
+
+`monitor-soak-60s-trend-2026-10-11.json` records an earlier 60.29-second synthetic 0.5-second run with the bounded output trend enabled. Two deliberate outages and one instance restart ended in a recovered monitor; the final history held 32 valid samples, never exceeded 32, and was attached to the final instance. The server handled 99 GETs including four expected HTTP failures, no other methods and at most one collection in flight, and remained readable after detach. The report observed 32 activity and 50 request rows retained. This is client stability evidence, not real-model or GPU performance evidence.
+
+`monitor-soak-60s-current-2026-10-11.json` is an earlier 60.29-second run on the selected-card monitor revision after the selected-card history and resize fixes. It passed two synthetic outages, one instance restart, a bounded 32-sample output history attached to the final instance, one maximum in-flight collection, and a readable server after detach. The server handled 98 GETs, including four expected HTTP failures and no non-GET methods; the final snapshot retained 32 activity and 50 request rows. This is client stability evidence only. The live resize path is covered separately by the headless 110-to-40-to-110 selection test.
+
+`parallel-cancel-ten-cycle-synthetic-2026-10-10.json` records ten fresh runs of `serve.test_parallel.ParallelService.test_benchmark_cancel_suite_releases_batch_queue_and_slots`. The repeated fake batched engine suite generates, cancels active and queued streams, checks recovery and returns admission to zero; a wrapper also checked that each engine process exited after unload and each HTTP listener closed. All ten passed in 33.836 seconds. This does not test a real model or driver unload.
+
+For each target-hardware run, record source SHA, engine/backend version, exact RTX 6000 generation and VRAM, driver and OS, model/revision and hashes, selected device indices and topology, effective slot/group counts, context and request mix, warmup, repeats, failure counts and raw outputs. Compare each rate only over a defined interval. Store fixture screenshots separately from measured results.
+
+## Target-host run order
+
+1. Install the exact reviewed build in a clean Windows or Linux environment; record installer/component hashes, versions, rights/notices and rollback result. Confirm the pure server starts with Desktop, harness and Textual absent. Install and remove the optional Monitor separately.
+2. Create a saved four-card profile, run `profile show --effective`, `doctor --components --live`, `components verify --live`, `runtime start` and `runtime verify`. Save the effective argv, owned instance ID, configured and resolved device order, model identity and actual slot/group counts. A successful one-token verify is only a smoke check.
+3. Use `status --json` and the Serving, Requests, Engine, Hardware and Logs views at 110, 80, 60 and 40 columns. Verify each displayed count against the v1 response and the [field matrix](TERMINAL_TELEMETRY_FIELDS.md). Record unavailable fields explicitly. For opt-in BSTAT/PSTAT samples, retain raw engine lines, sample windows/age and native-backend build identity. A reported layer range must not be labelled live GPU occupancy.
+4. Run the same fixed serving workload with no monitor, default Monitor, 0.5-second Monitor and Monitor plus the coding client. Warm up, then retain at least three repeated trials per condition. Save `bench run` directories and `bench compare` results only when workload fingerprints and available environment match. Measure server and terminal CPU/RSS separately, HTTP calls/bytes/s, tokens/s, client TTFT, queue wait, cancellation latency and every slow or failed request. Declare pass budgets from the M0 baseline before looking at the trial deltas.
+5. Run mixed parallel, overload, active/queued cancellation and partial-prompt cancellation suites with the monitor both attached and detached. Choose concurrency from reported effective slots and admission limit; the overload suite must exceed the limit. Exercise at least ten load/generate/cancel/unload cycles and verify no orphan workers, stale topology, leaked request content or changed engine state after monitor detach.
+6. Restart the server during a 30-minute real Monitor soak, add two deliberate network interruptions, and check bounded memory/rows, one in-flight poll, reconnect, selection reset and clean detach. Repeat terminal key, resize, freeze, theme, color and ASCII glyph checks on each supported OS/terminal. Capture actual terminal screenshots separately from illustrative fixtures.
+
+The synthetic `tools/monitor_soak.py` report is a useful client regression check before step 6. It runs a local fake telemetry server and cannot supply the real server CPU/RSS, inference performance, native GPU sample accuracy or operating-system qualification required above.
+
+## Work-order mapping (M0–M8)
+
+This is the status of the **separate terminal milestone**, not a claim that the full product work order is complete. Use the original development work plan for each milestone's complete acceptance criteria.
+
+| Milestone | Terminal milestone contribution | Still required for the product gate |
+| --- | --- | --- |
+| M0 intake | Current baseline, command grammar, fixture screenshots and v1 field source map recorded; the UI handover ZIP is available locally. | Audit the available UI handover; receive and audit the TUI and harness assets; pin licenses/revisions and real-model baseline; agree target OS/hardware and MVP parity. |
+| M1 pure start | Opt-in foreground `strata serve`, explicit profile resolution, offline flag, ready file, loopback/key checks and drain handling. | Qualify all legacy start paths, blocked-egress/offline behavior and Windows/Linux process trees on supported models. |
+| M2 shared runtime contract | v1 read-only telemetry, admission controls, POSIX owned host, typed profiles/recipes, authenticated generation readiness and a versioned Desktop owner bridge with recoverable benchmark/calibration journal receipts. | Complete remaining Desktop mappings and host-worker protocol, schema migrations, security boundary and real-model cancellation/unload acceptance. |
+| M3 verified distribution | Thin offline Monitor zipapp with unsigned SHA-256 manifest and local update/rollback test. | Signed release packages and trust/rotation design, whole-runtime install/update/rollback, target dependency locks and clean-room offline acceptance. |
+| M4 Desktop UI | The imported native shell has owner-backed Serving, read-only Monitor/Components/Models, reviewed Profiles, Benchmarks and Calibration. | Finish Chat/Tuning and browser-store authority mapping; pass Desktop/API/CLI parity on a clean install. |
+| M5 coding harness | `strata code` marks the missing shared component explicitly. | Review supplied DeepSeek harness, implement shared sessions/permissions and CLI mode, then pass real-model parity scenarios. |
+| M6 TUI | Six-view read-only Textual monitor with a YASD-inspired one-screen Overview, separate batch/queue/replica trends, fixtures, keyboard/resize tests and bounded telemetry client. | Reconcile supplied TUI design, real four-card and supported Windows/Linux terminal runs, attached-client overhead budget. |
+| M7 cleanup and benchmarks | Privacy-safe serving benchmark suites, comparison checks, command docs and qualification matrix. The separate integration branch now merges public `main` at `61b3fb5d`. | Review and land the integrated changes in small PRs, remove superseded paths after migration, run full hardware suites and signed candidate release checks. |
+| M8 native host runtimes | Host-adapter requirements are recorded in the plans; no native runtime package is claimed. | Build and qualify Strata as a native runtime in the chosen LM Studio/Unsloth host paths with signed packages and lifecycle tests. |
+
+`monitor-soak-30s-work-trends-2026-10-11.json` records a later 30.32-second synthetic pass on the batch/queue-trend revision: 20 resizes across four terminal sizes, two outages, one restart, at most 29 batch and pre-admission samples, one in-flight read and a readable server after detach. The trend values are fixtures, not measured GPU batching. `monitor-soak-30s-current-work-age-2026-10-11.json` records a further 30.35-second pass on the sample-age Overview revision with the same resize/outage/restart/detach scenarios, at most 26 batch and queue history samples and one read in flight. Focused renderer tests check that a BSTAT/PSTAT sample older than five seconds is unavailable in Overview; the synthetic soak is not a native engine timing measurement.
+
+`monitor-soak-30s-ui-fixed-2026-10-11.json` records a 30.31-second synthetic UI stress pass on the compact-renderer revision. It rotated four terminal sizes from 110x30 to 40x12, retained only four selected GPU histories despite unrelated, missing and duplicate sensor records, observed two outages and one restart, kept a single read in flight, and detached while the test server remained readable. A separate headless regression renders connection failures at 40, 60 and 80 columns in all six views and hides cached work values. `monitor-soak-30s-ui-current-2026-10-11.json` repeats this path on display revision `e885bf8` after the light-palette and host-span label corrections.
+
+`monitor-soak-30s-vram-final-2026-10-11.json` exercises the later per-card VRAM history through the same four terminal sizes, selected-card sensor churn, two outages, one restart and detach. The report bounds both load and VRAM series to four selected cards and 32 samples each, observes unavailable gaps in each, and checks one in-flight read and server survival. The values are fixture memory readings, not target GPU measurements.
+
+`monitor-soak-30m-ui-2026-10-11.json` records the passing 1,800.31-second synthetic UI stress run started on monitor revision `ba138f6`: 360 terminal resizes across 110x30, 80x24, 60x16 and 40x12; two deliberate outages; one instance restart; selected-card sensor gaps and duplicates; at most four card histories and 32 samples per history; 3,581 GETs including four expected failures, no non-GET requests and one maximum in-flight collection; and a readable test server after detach. Final traced-memory growth was 597,327 bytes from the post-start baseline. `monitor-soak-30m-ui-rss-2026-10-11.csv` holds 26 combined-process RSS samples spanning the final 1,500.4 seconds: 44,880–45,904 KiB, first-to-last +480 KiB. The sampler missed the first five minutes. The UI and server in this test were synthetic and headless; no real model, GPU or physical Windows/Linux terminal was measured.
diff --git a/docs/TERMINAL_QUICKSTART.md b/docs/TERMINAL_QUICKSTART.md
new file mode 100644
index 000000000..3ddd23d19
--- /dev/null
+++ b/docs/TERMINAL_QUICKSTART.md
@@ -0,0 +1,96 @@
+# Terminal quick start (source checkout)
+
+These commands describe the current `Strata-TUI-CLI` development branch. Run them from the repository root with the Python environment used for Strata. Substitute `python3` on systems without a `python` command. They do not install a model or change the existing one-click setup path. The complete options, permissions and limits are in [TERMINAL.md](TERMINAL.md).
+
+## Read a running server
+
+With Strata already serving locally, get one machine-readable snapshot:
+
+```sh
+python strata.py status --url http://127.0.0.1:8080 --json
+```
+
+The interactive monitor is optional. Install its pinned dependency in that same Python environment, then open the one-screen Overview:
+
+```sh
+python -m pip install -r requirements-monitor.txt
+python strata.py monitor --url http://127.0.0.1:8080
+```
+
+The Overview puts serving state, prompt and answer speed, batch/queue pressure, four selected GPU rows, requests and activity on one screen. Press `1`–`6` for detail, `Space` to freeze the display, `r` to refresh, and `q` to detach. Detach leaves the server running. On a machine without a terminal, use `status --json` or `monitor --once --json`.
+
+For a remote server, use HTTPS or a local SSH tunnel. A saved connection stores only the credential environment variable's **name**:
+
+```sh
+python strata.py connection create work --url https://example.invalid --credential-env STRATA_TELEMETRY_KEY
+python strata.py monitor --connection work
+```
+
+Set `STRATA_TELEMETRY_KEY` in the environment before connecting. Replace `example.invalid` with your own server root. The monitor client never needs a management credential.
+
+## Prepare and rerun a local model
+
+Use the run config written by setup. Start by reviewing its components and effective launch; neither command starts an engine:
+
+```sh
+python strata.py doctor --profile /absolute/path/to/strata-model.json --components --output json
+python strata.py serve --profile /absolute/path/to/strata-model.json --plan --output json
+```
+
+For repeatable local management on POSIX, create a named profile from that config. Review changes before saving them:
+
+```sh
+python strata.py profile create four-gpu --from-config /absolute/path/to/strata-model.json
+python strata.py profile set four-gpu parallel=8 batch_groups=auto max_queue=32 queue_timeout=15 batch_telemetry=true --plan
+python strata.py profile set four-gpu parallel=8 batch_groups=auto max_queue=32 queue_timeout=15 batch_telemetry=true
+python strata.py profile show four-gpu --effective --output json
+python strata.py runtime start --profile four-gpu --plan --output json
+python strata.py runtime start --profile four-gpu
+python strata.py runtime verify --profile four-gpu --output json
+```
+
+Choose slot and queue settings for the actual model and card memory. A requested `parallel=8` does not prove the engine loaded eight effective slots. Check the reported values after start. To change a running profile, save the edit, review the restart, then execute it:
+
+```sh
+python strata.py profile set four-gpu parallel=4 --plan
+python strata.py profile set four-gpu parallel=4
+python strata.py runtime restart --profile four-gpu --plan --output json
+python strata.py runtime restart --profile four-gpu
+```
+
+The restart is an explicit operation. `profile set` alone does not restart or retune a running model. `runtime stop --profile four-gpu` stops only the owned instance; `q` in Monitor does not. The POSIX runtime host and rollback path have fake-engine tests, but real GPU and Windows ownership qualification remains open.
+
+## Check cards, calibrate and benchmark
+
+Read installed components without launching the engine. The `--live` forms also probe host GPUs:
+
+```sh
+python strata.py components verify --profile four-gpu --output json
+python strata.py doctor --profile four-gpu --live --output json
+```
+
+Calibration is separate from serving. Review the plan and measure a decode sweep only when the selected devices are available for exclusive use. Measuring writes a report but does not apply settings:
+
+```sh
+python strata.py engine calibrate --profile four-gpu --plan --output json
+python strata.py engine calibrate --profile four-gpu --measure --exclusive --out /absolute/path/to/calibration.json
+python strata.py engine calibrate --profile four-gpu --review-result /absolute/path/to/calibration.json --output json
+```
+
+After reviewing the report, applying and rolling back remain separate explicit actions. Both require exclusive device access:
+
+```sh
+python strata.py engine calibrate --profile four-gpu --apply-result /absolute/path/to/calibration.json --exclusive
+python strata.py engine calibrate --profile four-gpu --review-rollback /absolute/path/to/calibration.json --output json
+python strata.py engine calibrate --profile four-gpu --rollback-result /absolute/path/to/calibration.json --exclusive
+```
+
+Check the candidate report and owner state before either action. The full preconditions and rollback behavior are in [TERMINAL.md](TERMINAL.md).
+
+After the model is loaded, save an explicit serving benchmark report:
+
+```sh
+python strata.py bench run --profile four-gpu --suite serving-smoke --concurrency 4 --out /absolute/path/to/new-bench-report
+```
+
+The benchmark writes into a new output directory and does not publish its result. Synthetic screenshots and local fake-engine tests do not establish performance on a four-card host. Capture the exact GPU generation, model, driver and workload before comparing real runs.
diff --git a/docs/TERMINAL_TELEMETRY_FIELDS.md b/docs/TERMINAL_TELEMETRY_FIELDS.md
new file mode 100644
index 000000000..728ea7ba9
--- /dev/null
+++ b/docs/TERMINAL_TELEMETRY_FIELDS.md
@@ -0,0 +1,49 @@
+# Terminal telemetry field contract (schema v1)
+
+This is the source map for the current `strata status`, `strata monitor`, and `strata logs` surfaces. The authoritative read-only response is `GET /v1/telemetry`; `strata_cli/client.py` validates and bounds it before display. The server builds v1 in `serve/server.py` from its current metrics, status, scheduler, engine samples and GPU sampler. A snapshot is a momentary observation, not a transaction across all subsystems. `sampled_at` is server wall-clock seconds for telemetry snapshots; the status-only fallback uses local receipt time because that older endpoint supplies no current sample clock. Age and rate labels must be tied to the relevant interval.
+
+`--` or JSON `null` means unavailable. Zero is used only when a source reports zero. The client accepts at most 2 MiB of JSON, 16 devices, 64 slots, 50 active and 50 recent requests, 32 activity events and 16 stages. Text is shortened and stripped of control characters. An instance change resets client-derived rates, selected-row identity and display histories. Monitor history retains at most 32 samples for each of at most 16 current selected cards, server output, processed batch rows, pre-admission queue count and each of at most 16 configured replica batch series. Absent or duplicate current sensors and failed collection append a gap instead of connecting unrelated samples. A missing newest value hides its output or work trend. The Overview also treats an engine batch or stage sample older than five seconds as unavailable; Serving and Engine detail retain its last value with the reported age.
+
+| Display / JSON field | Server source | Unit and scope | Sensitivity / freshness | Missing or older-server behavior |
+| --- | --- | --- | --- | --- |
+| Model and loaded state (`model.id`, `model.loaded`) | `/v1/status` as normalized into v1 | Model identifier and Boolean for this server instance | Identifier can reveal the served model; current snapshot | `--` / `null`; never infer load from a config file |
+| Context (`model.context`) | Status cache limit | Tokens, current model | Operational metadata; current snapshot | `--` / `null` |
+| Instance ID/state (`instance.id`, `instance.state`) | Server-assigned boot identity and drain state | One running server; `ready` or `draining` | ID is operational metadata; current snapshot | Legacy has boot time but no reliable restart identity; client-derived rate stays unavailable |
+| Requested/effective slots (`work.slots_requested`, `slots_effective`) | Requested serving configuration; actual engine/status concurrency | Slot counts for this instance | Operational; after load, may differ because engine reduced concurrency | Requested is unavailable in legacy; effective may be reported by status |
+| In flight, occupied, waiting, pre-admission (`work.active`, `occupied_slots`, `waiting`, `queued`) | Live engine/status counters and slot states | Request/slot counts at snapshot time | Operational; state transitions can race a poll; these sets overlap | The bounded client derives occupied slots from validated slot rows; it is `--` unless every effective slot has a unique index and known state; do not add counts as disjoint populations |
+| Admission (`admission_reserved`, `admission_limit`, `max_queue`) | Server admission state and configured cap | Accepted/reserved call count, total limit and queue cap for this instance | Operational; current snapshot | Legacy adapter leaves these unavailable |
+| Rejected, timeouts, disconnect cancellations (`admission_rejected`, `queue_timeouts`, `client_disconnect_cancels`) | Server counters | Calls since server start | Operational; reset on restart | Legacy unavailable; a reported zero is real zero |
+| Oldest queue wait and deadline (`oldest_queue_s`, `queue_timeout_s`) | Active queued/waiting rows and configured deadline | Seconds; oldest live wait and configured limit | Current snapshot; wait changes as requests move | Legacy unavailable; deadline absent unless configured |
+| Slot/group and request progress (`work.slots[]`) | Engine live slots plus engine `slot_group`/`slot_live` map | Slot index, pipeline group, state, held/prompt/read/generated tokens and per-slot tokens/s | Pseudonymous request ID; at most 64 rows; current snapshot | Group/slot values remain unavailable if engine does not report them; group is never a GPU assignment |
+| Wide Overview active context and slot rate | Complete `work.slots[]` joined with `model.context` and `work.requests[]` | Largest active slot's held tokens divided by per-slot model capacity; separate active-slot held/capacity rows; a request's slot tokens/s only when its slot and pseudonymous ID match | Display-only derivation from one snapshot; no summing independent contexts or treating idle retained cache as active | Incomplete slot report, missing held tokens/capacity or unmatched request ID yields `--`; no inferred expert or MTP activity |
+| Overview slot phases (read/decode/idle) | Count of `work.slots[]` states | Slot counts at one snapshot; these exclude queued/admitted requests outside slots | Derived only when every effective slot has a unique reported index and a known state | Hidden for partial, duplicate or unknown slot reports; never infer phase counts from active request totals |
+| Pipeline group occupancy (Gx busy/total) | Count of complete `work.slots[]` by reported group and non-idle state | Occupied/effective slots per pipeline group at one snapshot; not rows per batch window or a GPU lane | Exact counts require every effective slot to have a unique index, a known state and a valid group | Shows unavailable when the slot report is partial, duplicate or ambiguous; it never treats a partial group list as a total |
+| Replica and group identity (`work.slots[].replica`, `work.requests[].replica`) | The opt-in replica router and each child engine's slot map | Zero-based replica ID; group IDs are offset across replica engines so G0 in two engines is never collapsed into one chart | Instance-scoped, at most 64 slots and 50 live requests; a solo request may have a replica while its slot is null | No replica mode: null; a child slot without an ID retains null request correlation. Server-wide rows/window and stage timing remain unavailable in replica mode; separate child batch, placement and host-span samples are contracted; the first child is never presented as the whole server |
+| Replica card assignment (`topology.replica_devices[]`) | Validated configured GPU groups used to start each replica | Replica number and selected physical GPU indices; the Overview labels each selected card R0, R1 and so on | Configuration claim, not a measured routing trace; at most 16 replicas and 16 devices | Missing, duplicate or ambiguous assignment is omitted; card sensors remain independent of the configured mapping |
+| Replica layer placement (`topology.replica_stages[]`) | Each live child engine's bounded startup layer-split log plus that child's launch visibility order | Local stage number, contiguous layer range and physical card when it belongs to the configured replica group; the Overview labels a card Rn/Sm only when exactly one reported local stage maps to it | Engine-reported at startup, at most 16 replicas with 16 stages each; not a live utilization trace | Missing/oversized log leaves ranges unavailable; missing or mismatched visibility leaves card index `--`; stopped children do not retain a stale plan; server-wide `topology.stages` stays empty in replica mode |
+| Active requests (`work.requests[]`) | Server terminal-request registry enriched with live slots | At most 50 request states, queue/admit time, slot/group, prompt-read/generated counts | Pseudonymous instance-scoped ID; no prompt/answer/client address; `requests_omitted` counts overflow | Legacy has no correlated active request list; show unavailable, not synthetic IDs |
+| Recent completed requests (`recent[]`) | Existing `/metrics` recent-request ring | At most 50 outcome, token and timing summaries | No prompt/answer body; entries can disappear; current ring | Empty list or unavailable fields remain empty/`--` |
+| First engine token (`first_engine_token_s`) | Engine queue-entry to first generated token measurement | Seconds per request, includes queue/load/prefill after queue entry | Current live or recent request; missing until observed | `--`; this is not client-observed TTFT or HTTP ingress/network time |
+| Answer/prefill rates (`rates.answer_tok_s`, `prefill_tok_s`) | Existing engine metrics | Tokens/s over engine-reported windows or mean | Operational; `answer_window_s` identifies answer window | `--` if no engine sample; do not equate with aggregate multi-request output |
+| Wide Overview rate histories (client only) | Recent displayed prompt/prefill and answer rates | Relative eight-cell trends; the aggregate output history also includes its displayed range | At most 32 polls per series; reset on server instance change and append gaps on outage | Hidden when fewer than two valid samples or newest sample missing; not a benchmark or per-card throughput claim |
+| Aggregate output (`rates.output_tokens_server_counter` -> client `aggregate_output_tok_s`) | Completed server output tokens plus current in-flight generated tokens | Tokens/s for all requests over one common pair of polls | Derived by TUI; valid only for same instance, positive interval ≤30 s and monotonic counter | First poll, restart, invalid interval or counter reset: `--`; the Overview trend uses only recent valid display samples and labels their min/max; not a per-GPU rate |
+| Batch rows/window (`effective_rows_window`, `batch_active_rows_window`, `batch_sample_*`) | Opt-in engine `BSTAT` processed-row and active-slot counters | Average rows and active slots per batch window; count, elapsed span and age in seconds | Low-rate opt-in sample; age shown; rows can include padding or MTP work | Default and unsupported engines: `--`; slot occupancy is not batch rows/window |
+| Per-replica batch rows/window (`work.replica_batches[]`) | Each live child engine's opt-in `BSTAT`, kept in its own row | Processed/active rows per window and sample age for that replica only; R0 and R1 are never summed or averaged across asynchronous sample windows | At most 16 replica rows; missing or dead child has ID with no sample; bounded counts are revalidated in the terminal | `--` per replica without a valid sample; no server-wide rows/window claim in replica mode; native multi-GPU qualification remains open |
+| Overview work trends (client only) | Recent displayed `effective_rows_window`, `queued` and per-replica `effective_rows_window` values | Small relative graph with the visible min/max in rows/window or queued requests; independent polling samples, not another engine batch statistic | At most 32 samples per series; a server instance change resets the series; no cross-replica average and no addition of queue populations | Hidden when fewer than two valid samples exist, the newest sample is missing, the batch sample is more than five seconds old or the connection is stale; compact 80-column Overview keeps current values without these extra graphs |
+| Per-replica stage host span (`work.replica_stage_samples[]`) | Each live child engine's opt-in `PSTAT`, kept in its own row | Local stage in-flight percent, milliseconds, sample span and sample age for each replica; no cross-replica average | At most 16 child rows and 16 stages per child; stage count must match that child's reported plan when available; values include host polling delay | `--` per replica without a valid sample; server-wide `stage_in_flight[]` stays empty in replica mode; not GPU kernel occupancy or utilization; native multi-GPU qualification remains open |
+| Pipeline stage in-flight (`stage_in_flight[]`, `stage_sample_*`) | Opt-in engine `PSTAT` host spans | Percent of sample span and milliseconds per stage | Low-rate opt-in sample; includes host polling delay | `--` without sample; never label it GPU kernel occupancy/utilization |
+| Layer stages and device mapping (`topology.stages[]`) | Bounded current engine startup layer-split line, mapped through unambiguous numeric child visibility order | Inclusive layer ranges by stage and optionally physical device index | Reported allocation for loaded model, not measured runtime placement | No current log: unavailable; ambiguous visibility: retain ranges with no claimed card mapping |
+| GPU sensors (`devices[]`) | Per-device NVML/AMD sampler, selected device indices | Bytes VRAM used/total, utilization %, temperature °C, power W, per card | Host telemetry at sampler cadence; no inferred device values | Missing sensor fields `--`; Overview rows follow declared selected-device order and show a blank selected card if its sensor is absent or ambiguous; unrelated host cards stay in Hardware detail; legacy aggregate becomes one card only if sampler reports exactly one GPU |
+| Host RAM (`ram.used`, `ram.total`) | Existing hardware sampler | Bytes for host RAM | Operational; sampler cadence | `--` if not reported |
+| Redacted activity (`activity.events[]`) | Server in-memory terminal transition ring | Instance-scoped sequence, time, pseudonymous request ID, event/outcome | Server retains 128 and sends newest 32; gaps possible; no prompt, answer, tool text or credential | Legacy reports activity unavailable; empty supported feed says no transitions retained |
+| Lifetime totals (`totals.*`) | Server metrics totals | Requests and tokens since server start | Operational; reset with instance | `--` if omitted; do not use across restarts |
+
+The v1 `quality` object marks telemetry, request correlation, batch sample, stage host span and topology availability. `quality.replica_stage_in_flight=measured_host_span` means at least one child has a valid local PSTAT sample; it does not imply that every child has a sample. `quality.stage_in_flight` remains unavailable for the server as a whole in replica mode. A consumer should inspect it before drawing a chart or making a claim. `quality.telemetry=unavailable` means only `/v1/status` was reachable; live work, rates and sensors remain null or empty. `work.requests[]` and `activity.events[]` are monitoring data, not durable audit records. The monitor key authorizes `/v1/telemetry` only. An inference API key also works but grants broader legacy access; keep the keys distinct and pass them through environment references. Remote monitoring requires HTTPS or a local SSH tunnel; the client refuses redirects.
+
+For an older server, the client only falls back after a v1 **404**, reading `/metrics` and `/v1/status` and normalizing into the same bounded shape with `source=legacy-adapter`. If `/metrics` also returns 404 but `/v1/status` answers, it produces a `source=status-only` snapshot with model and reported effective concurrency, labels telemetry unavailable, and leaves live work and rates null. It never manufactures active request correlation, batch rows, stage spans, admission counters or four per-card readings. A schema mismatch or auth failure does not trigger fallback. Fixture screenshots are illustrative and cannot establish RTX 6000 throughput or native backend support.
+
+## Source and qualification map
+
+- Contract and sanitization: `strata_cli/client.py`; TUI aggregate rate and polling: `strata_cli/monitor.py`; labels and fallbacks: `strata_cli/render.py`.
+- Server response: `serve/server.py` `/v1/telemetry`; opt-in engine batch and pipeline samples are described in `docs/TERMINAL.md`.
+- Before a four-card release, capture server schema, source commit, engine/backend build, model hash/revision, exact RTX 6000 generation and VRAM, driver, selected device IDs, layer ranges and visibility order. Run the load/parallel/cancel and overhead matrix on that host. This file documents meanings; it is not hardware qualification evidence.
diff --git a/docs/terminal-previews/requests-80-detail.png b/docs/terminal-previews/requests-80-detail.png
new file mode 100644
index 000000000..82018c9ea
Binary files /dev/null and b/docs/terminal-previews/requests-80-detail.png differ
diff --git a/docs/terminal-previews/serving-110-batch-sample.png b/docs/terminal-previews/serving-110-batch-sample.png
new file mode 100644
index 000000000..d594d453b
Binary files /dev/null and b/docs/terminal-previews/serving-110-batch-sample.png differ
diff --git a/docs/terminal-previews/serving-110-color.png b/docs/terminal-previews/serving-110-color.png
new file mode 100644
index 000000000..dd8c3e879
Binary files /dev/null and b/docs/terminal-previews/serving-110-color.png differ
diff --git a/docs/terminal-previews/serving-110-stage-inflight.png b/docs/terminal-previews/serving-110-stage-inflight.png
new file mode 100644
index 000000000..d4d5f0d20
Binary files /dev/null and b/docs/terminal-previews/serving-110-stage-inflight.png differ
diff --git a/docs/terminal-previews/serving-110-stages.png b/docs/terminal-previews/serving-110-stages.png
new file mode 100644
index 000000000..7a736f0a4
Binary files /dev/null and b/docs/terminal-previews/serving-110-stages.png differ
diff --git a/docs/terminal-previews/serving-80-light.png b/docs/terminal-previews/serving-80-light.png
new file mode 100644
index 000000000..55f1b457b
Binary files /dev/null and b/docs/terminal-previews/serving-80-light.png differ
diff --git a/docs/terminal-previews/serving-80-slot-detail.png b/docs/terminal-previews/serving-80-slot-detail.png
new file mode 100644
index 000000000..a402e248f
Binary files /dev/null and b/docs/terminal-previews/serving-80-slot-detail.png differ
diff --git a/requirements-monitor.txt b/requirements-monitor.txt
new file mode 100644
index 000000000..4b3c20657
--- /dev/null
+++ b/requirements-monitor.txt
@@ -0,0 +1,2 @@
+# Optional terminal monitor only. The core server and `strata status` use stdlib.
+textual==8.2.8
diff --git a/strata.py b/strata.py
new file mode 100644
index 000000000..075982c52
--- /dev/null
+++ b/strata.py
@@ -0,0 +1,11 @@
+"""Strata's small, dependency-free terminal entry point.
+
+Run ``python strata.py --help`` from a source checkout. Optional terminal UI
+dependencies are imported only by ``monitor``.
+"""
+
+from strata_cli.cli import main
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/strata_cli/__init__.py b/strata_cli/__init__.py
new file mode 100644
index 000000000..79ca2335e
--- /dev/null
+++ b/strata_cli/__init__.py
@@ -0,0 +1,3 @@
+"""Terminal clients for the shared Strata server."""
+
+SCHEMA_VERSION = 1
diff --git a/strata_cli/bench.py b/strata_cli/bench.py
new file mode 100644
index 000000000..5d88dc53e
--- /dev/null
+++ b/strata_cli/bench.py
@@ -0,0 +1,1301 @@
+"""Explicit, local-file serving benchmark with privacy-safe evidence.
+
+This measures the API as a client sees it. Engine batching and GPU readings are
+sampled from telemetry; missing signals stay unknown. It does not tune a model.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import http.client
+import json
+import math
+import os
+import re
+import socket
+import stat
+import statistics
+import threading
+import time
+import urllib.error
+import urllib.request
+import uuid
+from contextlib import contextmanager, nullcontext
+from concurrent.futures import ThreadPoolExecutor, as_completed
+from datetime import datetime, timezone
+from pathlib import Path
+
+from strata_cli.client import ClientError, Endpoint, _NoRedirect
+from strata_control.profiles import ProfileError
+
+
+SCHEMA = 1
+MAX_EVENT_BYTES = 256 * 1024
+MAX_RESPONSE_BYTES = 8 * 1024 * 1024
+MAX_REPORT_BYTES = 4 * 1024 * 1024
+MAX_SAMPLES_PER_PHASE = 500
+SHORT_PROMPT = "Answer in one sentence: what does a GPU do during model inference?"
+LONG_PROMPT = ("Explain how a serving system handles simultaneous short and long requests, "
+ "including queue admission, prefill, decode slots, batching and cancellation. " * 12)
+CANCEL_PROMPT = ("Cancellation benchmark: write a detailed explanation of batching and parallel inference "
+ "with at least 200 words. Discuss admission, prompt reading, decoding and recovery.")
+SUITES = {"serving-smoke": ("warmup", "serial", "mixed"),
+ "parallel-mixed-v1": ("warmup", "serial", "mixed", "mixed"),
+ "parallel-overload-v1": ("warmup", "overload", "recovery"),
+ "parallel-cancel-v1": ("warmup", "cancel_active", "cancel_queued", "recovery"),
+ "parallel-prefill-cancel-v1": ("warmup", "cancel_prefill", "recovery")}
+
+
+class OperatorCancellation:
+ """Stop benchmark-owned streams after an owner-local cancel request appears."""
+
+ def __init__(self, directory: Path):
+ self.path = directory / "cancel.request"
+ self.event = threading.Event()
+ self._stop = threading.Event()
+ self._lock = threading.Lock()
+ self._sockets: set[socket.socket] = set()
+ self._watcher = threading.Thread(target=self._watch, daemon=True)
+
+ def _watch(self) -> None:
+ while not self._stop.wait(0.1):
+ if self.path.exists():
+ self.cancel()
+ return
+
+ def cancel(self) -> None:
+ with self._lock:
+ self.event.set()
+ sockets = tuple(self._sockets)
+ for owned in sockets:
+ try:
+ owned.shutdown(socket.SHUT_RDWR)
+ except OSError:
+ pass
+
+ @contextmanager
+ def track(self, response):
+ # urllib's HTTPResponse owns the socket while reading its buffered stream.
+ stream = getattr(response, "fp", None)
+ raw = getattr(stream, "raw", None)
+ owned = getattr(raw, "_sock", None)
+ if not isinstance(owned, socket.socket):
+ owned = None
+ if owned is not None:
+ with self._lock:
+ self._sockets.add(owned)
+ cancelled = self.event.is_set()
+ if cancelled:
+ try:
+ owned.shutdown(socket.SHUT_RDWR)
+ except OSError:
+ pass
+ try:
+ yield
+ finally:
+ if owned is not None:
+ with self._lock:
+ self._sockets.discard(owned)
+
+ def __enter__(self):
+ self._watcher.start()
+ return self
+
+ def __exit__(self, *_):
+ self._stop.set()
+ self._watcher.join(timeout=1)
+
+
+def _planned_phase_kinds(suite: str, repeat: int) -> list[str]:
+ single = {"warmup", "recovery", "cancel_active", "cancel_queued", "cancel_prefill"}
+ return [kind for kind in SUITES[suite]
+ for _ in range(1 if kind in single else repeat)]
+
+
+def _utc_now() -> str:
+ return datetime.now(timezone.utc).isoformat(timespec="seconds")
+
+
+def _percentile(values: list[float], fraction: float) -> float | None:
+ if not values:
+ return None
+ ordered = sorted(values)
+ return round(ordered[max(0, math.ceil(len(ordered) * fraction) - 1)], 4)
+
+
+def _sample(snapshot: dict) -> dict:
+ work = snapshot.get("work") or {}
+ rates = snapshot.get("rates") or {}
+ return {"at": time.time(), "instance_id": (snapshot.get("instance") or {}).get("id"),
+ "active": work.get("active"), "queued": work.get("queued"),
+ "waiting": work.get("waiting"), "occupied_slots": work.get("occupied_slots"),
+ "slots_effective": work.get("slots_effective"), "groups": work.get("groups"),
+ "admission_reserved": work.get("admission_reserved"),
+ "admission_rejected": work.get("admission_rejected"),
+ "admission_limit": work.get("admission_limit"), "max_queue": work.get("max_queue"),
+ "queue_timeout_s": work.get("queue_timeout_s"), "queue_timeouts": work.get("queue_timeouts"),
+ "client_disconnect_cancels": work.get("client_disconnect_cancels"),
+ "answer_tok_s": rates.get("answer_tok_s"),
+ "devices": [{"index": d.get("index"), "mem_used": d.get("mem_used"),
+ "mem_total": d.get("mem_total"), "util": d.get("util")}
+ for d in snapshot.get("devices", [])[:16]]}
+
+
+def _environment(snapshot: dict) -> dict:
+ """Bounded reported setup for comparisons, not a hardware attestation."""
+ work = snapshot.get("work") or {}
+ model = snapshot.get("model") or {}
+ topology = snapshot.get("topology") or {}
+ devices = []
+ for row in snapshot.get("devices", [])[:16]:
+ if not isinstance(row, dict):
+ continue
+ name = row.get("name")
+ devices.append({"index": row.get("index"),
+ "name": name[:120] if isinstance(name, str) and name.isprintable() else None,
+ "mem_total": row.get("mem_total")})
+ return {"model_context": model.get("context"),
+ "slots_effective": work.get("slots_effective"), "groups": work.get("groups"),
+ "max_queue": work.get("max_queue"), "queue_timeout_s": work.get("queue_timeout_s"),
+ "selected_devices": (topology.get("selected_devices") or [])[:16],
+ "stages": (topology.get("stages") or [])[:16], "devices": devices,
+ "source": "server_telemetry; driver, engine binary and model artifact hashes not attested"}
+
+
+def _managed_match(profile_identity: dict, endpoint_root: str, snapshot: dict) -> dict:
+ """Check a local owner host without persisting its control token or launch MAC."""
+ from strata_control import runtime
+
+ name, revision = profile_identity.get("profile"), profile_identity.get("revision")
+ if not isinstance(name, str) or not re.fullmatch(r"[a-z][a-z0-9_-]{0,63}", name) or \
+ not isinstance(revision, str) or not re.fullmatch(r"[0-9a-f]{16}", revision):
+ return {"matched": False, "reason": "saved_profile_required"}
+ try:
+ owner = runtime.status(name)
+ plan = runtime.plan_restart(name)
+ except (OSError, ProfileError, ValueError):
+ return {"matched": False, "reason": "owner_unavailable"}
+ instance = (snapshot.get("instance") or {}).get("id")
+ if (not owner.get("ok") or owner.get("state") != "ready" or
+ owner.get("launch_attested") is not True or owner.get("api_identity_verified") is not True or
+ owner.get("generation_ready") is not True):
+ return {"matched": False, "reason": "owner_not_verified"}
+ if (not plan.get("ok") or plan.get("changed") is not False):
+ return {"matched": False, "reason": "profile_or_source_changed"}
+ if (not isinstance(instance, str) or owner.get("instance_id") != instance or
+ plan.get("current_instance_id") != instance):
+ return {"matched": False, "reason": "instance_mismatch"}
+ if (owner.get("profile_revision") != revision or
+ plan.get("current_profile_revision") != revision or
+ plan.get("candidate_profile_revision") != revision):
+ return {"matched": False, "reason": "profile_revision_mismatch"}
+ if owner.get("api_url") != endpoint_root:
+ return {"matched": False, "reason": "endpoint_mismatch"}
+ return {"matched": True, "reason": "managed_launch_checked", "instance_id": instance,
+ "profile_revision": revision}
+
+
+def _event_result(event: dict, first_ns: int | None,
+ completion_tokens: int | None) -> tuple[int | None, int | None, str | None]:
+ if "error" in event:
+ error = event["error"]
+ code = (error.get("code") or error.get("type")) if isinstance(error, dict) else "stream_error"
+ return first_ns, completion_tokens, str(code)[:80]
+ choices = event.get("choices")
+ if isinstance(choices, list) and choices and isinstance(choices[0], dict):
+ delta = choices[0].get("delta")
+ if isinstance(delta, dict) and any(delta.get(key) for key in ("content", "reasoning_content", "tool_calls")):
+ first_ns = first_ns or time.monotonic_ns()
+ usage = event.get("usage")
+ if isinstance(usage, dict) and type(usage.get("completion_tokens")) is int:
+ completion_tokens = usage["completion_tokens"]
+ return first_ns, completion_tokens, None
+
+
+def _request(root: str, credential: str | None, prompt: str, max_tokens: int,
+ timeout: float, label: str, start_gate: threading.Event | None = None,
+ operator: OperatorCancellation | None = None) -> dict:
+ """Send one streamed request. Save measurements, never prompt or answer text."""
+ payload = {"messages": [{"role": "user", "content": prompt}],
+ "stream": True, "max_tokens": max_tokens, "temperature": 0}
+ headers = {"Content-Type": "application/json", "Accept": "text/event-stream",
+ "User-Agent": "Strata-Bench/0.1"}
+ if credential:
+ headers["Authorization"] = "Bearer " + credential
+ request = urllib.request.Request(root + "/v1/chat/completions",
+ data=json.dumps(payload).encode("utf-8"), headers=headers, method="POST")
+ if start_gate is not None:
+ start_gate.wait()
+ start_ns = time.monotonic_ns()
+ first_ns = None
+ tokens = None
+ received = 0
+ done = False
+ status = None
+ error = None
+ try:
+ if operator is not None and operator.event.is_set():
+ raise InterruptedError("operator cancelled")
+ with urllib.request.build_opener(_NoRedirect).open(request, timeout=timeout) as response:
+ with operator.track(response) if operator is not None else nullcontext():
+ status = response.status
+ if "text/event-stream" not in response.headers.get("Content-Type", ""):
+ raise ValueError("response was not an event stream")
+ while True:
+ line = response.readline(MAX_EVENT_BYTES + 1)
+ if not line:
+ break
+ received += len(line)
+ if len(line) > MAX_EVENT_BYTES or received > MAX_RESPONSE_BYTES:
+ raise ValueError("stream exceeded the benchmark size limit")
+ if not line.startswith(b"data: "):
+ continue
+ data = line[6:].strip()
+ if data == b"[DONE]":
+ done = True
+ break
+ event = json.loads(data)
+ if not isinstance(event, dict):
+ raise ValueError("stream event was not an object")
+ first_ns, tokens, error = _event_result(event, first_ns, tokens)
+ if error:
+ break
+ if not done and not error:
+ error = "stream_ended_without_done"
+ except urllib.error.HTTPError as exc:
+ status = exc.code
+ error = "authentication_failed" if status in (401, 403) else f"http_{status}"
+ if status == 429:
+ try:
+ raw = exc.read(4097)
+ if len(raw) <= 4096:
+ body = json.loads(raw)
+ code = (body.get("error") or {}).get("code")
+ if code in ("admission_full", "queue_wait_timeout"):
+ error = code
+ except (OSError, ValueError, AttributeError):
+ pass
+ exc.close()
+ except (urllib.error.URLError, TimeoutError, socket.timeout, OSError, http.client.HTTPException) as exc:
+ error = "connection_" + type(exc).__name__
+ except (UnicodeError, ValueError) as exc:
+ error = "invalid_stream_" + type(exc).__name__
+ if operator is not None and operator.event.is_set():
+ error = "operator_cancelled"
+ done = False
+ end_ns = time.monotonic_ns()
+ result = {"label": label, "prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(),
+ "prompt_characters": len(prompt), "max_tokens": max_tokens,
+ "status": status, "ok": status == 200 and done and error is None,
+ "error_code": error, "latency_s": round((end_ns - start_ns) / 1e9, 4),
+ "ttft_s": round((first_ns - start_ns) / 1e9, 4) if first_ns else None,
+ "completion_tokens": tokens}
+ if start_gate is not None:
+ result["_launch_ns"] = start_ns
+ return result
+
+
+def _cancellable_request(root: str, credential: str | None, prompt: str, timeout: float,
+ first_content: bool, opened: threading.Event,
+ ready_to_close: threading.Event, close_now: threading.Event,
+ result: dict, operator: OperatorCancellation | None = None) -> None:
+ """Hold one streamed client socket until the benchmark deliberately closes it."""
+ payload = {"messages": [{"role": "user", "content": prompt}],
+ "stream": True, "max_tokens": 512, "temperature": 0}
+ headers = {"Content-Type": "application/json", "Accept": "text/event-stream",
+ "User-Agent": "Strata-Bench/0.1"}
+ if credential:
+ headers["Authorization"] = "Bearer " + credential
+ request = urllib.request.Request(root + "/v1/chat/completions",
+ data=json.dumps(payload).encode("utf-8"), headers=headers, method="POST")
+ started = time.monotonic_ns()
+ result.update({"label": "cancel_target", "prompt_sha256": hashlib.sha256(prompt.encode()).hexdigest(),
+ "prompt_characters": len(prompt), "max_tokens": 512, "status": None,
+ "client_closed": False, "first_content_seen": False, "error_code": None})
+ try:
+ if operator is not None and operator.event.is_set():
+ raise InterruptedError("operator cancelled")
+ with urllib.request.build_opener(_NoRedirect).open(request, timeout=timeout) as response:
+ with operator.track(response) if operator is not None else nullcontext():
+ result["status"] = response.status
+ opened.set()
+ if "text/event-stream" not in response.headers.get("Content-Type", ""):
+ result["error_code"] = "not_event_stream"
+ return
+ if first_content:
+ received = 0
+ while received <= MAX_RESPONSE_BYTES:
+ line = response.readline(MAX_EVENT_BYTES + 1)
+ if not line:
+ result["error_code"] = "ended_before_cancel"
+ return
+ received += len(line)
+ if len(line) > MAX_EVENT_BYTES:
+ result["error_code"] = "stream_too_large"
+ return
+ if line.startswith(b"data: "):
+ data = line[6:].strip()
+ if data == b"[DONE]":
+ result["error_code"] = "ended_before_cancel"
+ return
+ event = json.loads(data)
+ first_ns, _, error = _event_result(event, None, None)
+ if error:
+ result["error_code"] = error
+ return
+ if first_ns is not None:
+ result["first_content_seen"] = True
+ break
+ if not result["first_content_seen"]:
+ result["error_code"] = "stream_too_large"
+ return
+ ready_to_close.set()
+ if not close_now.wait(timeout):
+ result["error_code"] = "client_close_signal_timeout"
+ return
+ result["client_closed"] = True
+ except urllib.error.HTTPError as error:
+ result["status"] = error.code
+ result["error_code"] = "authentication_failed" if error.code in (401, 403) else f"http_{error.code}"
+ error.close()
+ except (urllib.error.URLError, TimeoutError, socket.timeout, OSError,
+ http.client.HTTPException, UnicodeError, ValueError, TypeError, AttributeError) as error:
+ result["error_code"] = type(error).__name__[:80]
+ finally:
+ if operator is not None and operator.event.is_set():
+ result["error_code"] = "operator_cancelled"
+ opened.set()
+ ready_to_close.set()
+ result["latency_s"] = round((time.monotonic_ns() - started) / 1e9, 4)
+
+
+def _cancel_phase(endpoint: Endpoint, telemetry: Endpoint, *, kind: str,
+ slots: int, timeout: float,
+ operator: OperatorCancellation | None = None) -> dict:
+ samples: list[dict] = []
+ sample_errors = 0
+ samples_omitted = 0
+ peaks: dict[str, int | float] = {}
+ beginning = time.monotonic()
+
+ def capture() -> dict | None:
+ nonlocal sample_errors, samples_omitted
+ try:
+ snapshot = telemetry.snapshot()
+ except (ClientError, ValueError):
+ sample_errors += 1
+ return None
+ row = _sample(snapshot)
+ for key in ("active", "queued", "waiting", "occupied_slots", "groups"):
+ value = row.get(key)
+ if type(value) in (int, float):
+ peaks[key] = max(peaks.get(key, value), value)
+ if len(samples) < 120:
+ samples.append(row)
+ else:
+ samples_omitted += 1
+ return snapshot
+
+ def until(check, seconds: float) -> dict | None:
+ deadline = time.monotonic() + seconds
+ while time.monotonic() < deadline:
+ if operator is not None and operator.event.is_set():
+ return None
+ snapshot = capture()
+ if snapshot is not None and check(snapshot):
+ return snapshot
+ time.sleep(0.05)
+ return None
+
+ def wait_signal(signal: threading.Event, seconds: float) -> None:
+ deadline = time.monotonic() + seconds
+ while not signal.is_set() and time.monotonic() < deadline:
+ if operator is not None and operator.event.is_set():
+ return
+ signal.wait(min(0.2, max(0, deadline - time.monotonic())))
+
+ before = capture()
+ if before is None:
+ raise ProfileError("cancellation benchmark could not read telemetry", 5)
+ work_before = before.get("work") or {}
+ before_ids = {row.get("id") for row in work_before.get("requests") or []}
+ base_cancel = work_before.get("client_disconnect_cancels")
+ base_timeout = work_before.get("queue_timeouts")
+ if type(base_cancel) is not int or type(base_timeout) is not int:
+ raise ProfileError("cancellation benchmark lost required telemetry counters", 5)
+ opened, ready_to_close, close_now = threading.Event(), threading.Event(), threading.Event()
+ target: dict = {}
+ companion_rows: list[dict] = []
+ seen_state = False
+ observed_cancel = False
+ settled = False
+ target_id = None
+ companion_ok = True
+ worker = None
+ companions = None
+ companions_needed = slots if kind == "cancel_queued" else 1 if kind == "cancel_prefill" else 0
+ prompt_read_seen = False
+ try:
+ if companions_needed:
+ companions = ThreadPoolExecutor(max_workers=companions_needed)
+ futures = [companions.submit(_request, endpoint.root, endpoint.credential,
+ CANCEL_PROMPT, 512, timeout, "companion", None, operator)
+ for _ in range(companions_needed)]
+ running = until(lambda snap: sum(row.get("state") not in ("queued", "waiting")
+ for row in (snap.get("work") or {}).get("requests") or []
+ if row.get("id") not in before_ids) >= companions_needed,
+ min(timeout, 20))
+ if running is None:
+ target["error_code"] = "companion_slots_not_active"
+ else:
+ before_ids = {row.get("id") for row in (running.get("work") or {}).get("requests") or []}
+ if "error_code" not in target:
+ worker = threading.Thread(target=_cancellable_request,
+ args=(endpoint.root, endpoint.credential,
+ SHORT_PROMPT if kind == "cancel_queued" else
+ LONG_PROMPT if kind == "cancel_prefill" else CANCEL_PROMPT,
+ timeout, kind == "cancel_active",
+ opened, ready_to_close, close_now, target, operator), daemon=True)
+ worker.start()
+ wait_signal(opened, min(timeout, 20))
+ wait_signal(ready_to_close, min(timeout, 20))
+ desired = ({"queued", "waiting"} if kind == "cancel_queued" else
+ {"reading"} if kind == "cancel_prefill" else None)
+ found = until(lambda snap: any(row.get("id") not in before_ids and
+ (desired is None or row.get("state") in desired) and
+ (kind != "cancel_prefill" or
+ type(row.get("prompt_read")) is int and
+ type(row.get("prompt_tokens")) is int and
+ 0 < row["prompt_read"] < row["prompt_tokens"])
+ for row in (snap.get("work") or {}).get("requests") or []),
+ min(timeout, 5.0))
+ if found is not None:
+ row = next(row for row in (found.get("work") or {}).get("requests") or []
+ if row.get("id") not in before_ids and
+ (desired is None or row.get("state") in desired) and
+ (kind != "cancel_prefill" or
+ type(row.get("prompt_read")) is int and
+ type(row.get("prompt_tokens")) is int and
+ 0 < row["prompt_read"] < row["prompt_tokens"]))
+ target_id = row["id"]
+ target["request_id"] = target_id
+ seen_state = True
+ if kind == "cancel_prefill":
+ target["prompt_read_at_close"] = row["prompt_read"]
+ target["prompt_tokens_at_close"] = row["prompt_tokens"]
+ prompt_read_seen = True
+ close_now.set()
+ worker.join(timeout=min(timeout, 10))
+ observed = until(lambda snap: type((snap.get("work") or {}).get("client_disconnect_cancels")) is int
+ and (snap["work"]["client_disconnect_cancels"] >= base_cancel + 1)
+ and (target_id is None or all(row.get("id") != target_id
+ for row in snap["work"].get("requests") or [])), 10.0)
+ observed_cancel = observed is not None
+ if companions is not None:
+ for future in as_completed(futures):
+ companion_rows.append(future.result())
+ companion_ok = all(row["ok"] for row in companion_rows)
+ settled = until(lambda snap: (snap.get("work") or {}).get("admission_reserved") == 0 and
+ (snap.get("work") or {}).get("active") == 0 and
+ (snap.get("work") or {}).get("occupied_slots") in (0, None), 10.0) is not None
+ finally:
+ close_now.set()
+ if worker is not None:
+ worker.join(timeout=1)
+ if companions is not None:
+ companions.shutdown(wait=True)
+ after = capture() or {}
+ work_after = after.get("work") or {}
+ cancel_delta = (work_after.get("client_disconnect_cancels") - base_cancel
+ if type(work_after.get("client_disconnect_cancels")) is int and type(base_cancel) is int
+ else None)
+ timeout_delta = (work_after.get("queue_timeouts") - base_timeout
+ if type(work_after.get("queue_timeouts")) is int and type(base_timeout) is int else None)
+ passed = (seen_state and (kind != "cancel_prefill" or prompt_read_seen) and
+ target.get("client_closed") is True and observed_cancel and settled and
+ companion_ok and timeout_delta == 0 and target.get("error_code") is None and
+ (kind != "cancel_active" or target.get("first_content_seen")))
+ elapsed = time.monotonic() - beginning
+ return {"kind": kind, "requested": 1 + companions_needed,
+ "client_workers": 1 + companions_needed, "passed": passed,
+ "duration_s": round(elapsed, 4), "requests": [target, *companion_rows],
+ "telemetry_samples": samples, "telemetry_sample_errors": sample_errors,
+ "telemetry_samples_omitted": samples_omitted,
+ "summary": {"successful": sum(row["ok"] for row in companion_rows),
+ "failed": 0 if passed else 1, "expected_overload": 0,
+ "target_state_seen": seen_state, "client_closed": target.get("client_closed") is True,
+ "prompt_read_seen": prompt_read_seen,
+ "first_content_seen": target.get("first_content_seen") is True,
+ "client_disconnect_delta": cancel_delta, "queue_timeouts_delta": timeout_delta,
+ "companion_successful": sum(row["ok"] for row in companion_rows),
+ "settled": settled,
+ "p50_latency_s": _percentile([row["latency_s"] for row in companion_rows if row["ok"]], 0.5),
+ "p95_latency_s": _percentile([row["latency_s"] for row in companion_rows if row["ok"]], 0.95),
+ "p50_ttft_s": None, "p95_ttft_s": None, "output_tokens": None, "output_tok_s": None,
+ "peak_active": peaks.get("active"), "peak_queued": peaks.get("queued"),
+ "peak_waiting": peaks.get("waiting"),
+ "peak_occupied_slots": peaks.get("occupied_slots"), "peak_groups": peaks.get("groups"),
+ "peak_admission_rejected": None}}
+
+
+def _phase(endpoint: Endpoint, telemetry: Endpoint, *, kind: str, count: int,
+ concurrency: int, timeout: float,
+ operator: OperatorCancellation | None = None) -> dict:
+ samples = []
+ sample_errors = 0
+ samples_omitted = 0
+ sample_cap = min(MAX_SAMPLES_PER_PHASE, 120) if kind == "overload" else MAX_SAMPLES_PER_PHASE
+ peaks = {}
+ first_sample = None
+ last_sample = None
+ stop = threading.Event()
+
+ def record(snapshot):
+ nonlocal samples_omitted, first_sample, last_sample
+ sample = _sample(snapshot)
+ if first_sample is None:
+ first_sample = sample
+ last_sample = sample
+ for key in ("active", "queued", "waiting", "occupied_slots", "groups", "admission_rejected"):
+ value = sample.get(key)
+ if type(value) in (int, float):
+ peaks[key] = max(peaks.get(key, value), value)
+ if len(samples) < sample_cap:
+ samples.append(sample)
+ else:
+ samples_omitted += 1
+
+ def poll():
+ nonlocal sample_errors
+ while not stop.is_set() and (operator is None or not operator.event.is_set()):
+ try:
+ record(telemetry.snapshot())
+ except (ClientError, ValueError):
+ sample_errors += 1
+ stop.wait(0.15)
+
+ try:
+ record(telemetry.snapshot())
+ except (ClientError, ValueError):
+ sample_errors += 1
+ worker = threading.Thread(target=poll, daemon=True)
+ worker.start()
+ start = time.monotonic()
+ requests = []
+ try:
+ with ThreadPoolExecutor(max_workers=concurrency) as pool:
+ futures = []
+ start_gate = threading.Event() if kind == "overload" else None
+ try:
+ for index in range(count):
+ long = kind in ("mixed", "overload") and index % 2 == 1
+ prompt = LONG_PROMPT if long else SHORT_PROMPT
+ limit = 256 if kind == "overload" else 96 if long else 32
+ futures.append(pool.submit(_request, endpoint.root, endpoint.credential,
+ prompt, limit, timeout, "long" if long else "short",
+ start_gate, operator))
+ finally:
+ if start_gate is not None:
+ start_gate.set()
+ for future in as_completed(futures):
+ requests.append(future.result())
+ finally:
+ stop.set()
+ worker.join(timeout=min(telemetry.timeout + 1, 31))
+ elapsed = time.monotonic() - start
+ try:
+ record(telemetry.snapshot())
+ except (ClientError, ValueError):
+ sample_errors += 1
+ launches = [row["_launch_ns"] for row in requests if "_launch_ns" in row]
+ if launches:
+ for row in requests:
+ # The monotonic clock has meaning only inside this run; expose phase-relative offsets.
+ row["launch_offset_s"] = round((row.pop("_launch_ns") / 1e9) - start, 4)
+ launch_spread = round((max(launches) - min(launches)) / 1e9, 4) if launches else None
+ latencies = [r["latency_s"] for r in requests if r["ok"]]
+ ttfts = [r["ttft_s"] for r in requests if r["ok"] and r["ttft_s"] is not None]
+ tokens = [r["completion_tokens"] for r in requests if r["ok"]]
+ token_count_complete = (bool(tokens) and all(type(value) is int for value in tokens) and
+ (kind == "overload" or len(tokens) == len(requests)))
+ output_tokens = sum(tokens) if token_count_complete else None
+ rejected = sum(r["error_code"] == "admission_full" for r in requests)
+ timed_out_count = sum(r["error_code"] == "queue_wait_timeout" for r in requests)
+ expected_overload = rejected + timed_out_count
+ unexpected_failures = sum(not r["ok"] and r["error_code"] not in
+ ("admission_full", "queue_wait_timeout") for r in requests)
+ passed = (sum(bool(r["ok"]) for r in requests) > 0 and expected_overload > 0 and
+ unexpected_failures == 0) if kind == "overload" else all(r["ok"] for r in requests)
+ def counter_delta(key):
+ if (first_sample is None or last_sample is None or
+ first_sample.get("instance_id") != last_sample.get("instance_id") or
+ type(first_sample.get(key)) is not int or type(last_sample.get(key)) is not int):
+ return None
+ return last_sample[key] - first_sample[key] if last_sample[key] >= first_sample[key] else None
+ return {"kind": kind, "requested": count, "client_workers": concurrency,
+ "passed": passed,
+ "duration_s": round(elapsed, 4), "requests": requests, "telemetry_samples": samples,
+ "telemetry_sample_errors": sample_errors, "telemetry_samples_omitted": samples_omitted,
+ "summary": {"successful": sum(bool(r["ok"]) for r in requests),
+ "launch_spread_s": launch_spread,
+ "failed": unexpected_failures if kind == "overload" else sum(not r["ok"] for r in requests),
+ "expected_overload": expected_overload if kind == "overload" else 0,
+ "admission_full": rejected if kind == "overload" else 0,
+ "queue_wait_timeout": timed_out_count if kind == "overload" else 0,
+ "admission_rejected_delta": counter_delta("admission_rejected"),
+ "queue_timeouts_delta": counter_delta("queue_timeouts"),
+ "p50_latency_s": _percentile(latencies, 0.5),
+ "p95_latency_s": _percentile(latencies, 0.95),
+ "p50_ttft_s": _percentile(ttfts, 0.5),
+ "p95_ttft_s": _percentile(ttfts, 0.95),
+ "output_tokens": output_tokens,
+ "output_tok_s": round(output_tokens / elapsed, 3)
+ if output_tokens is not None and elapsed > 0 else None,
+ "peak_active": peaks.get("active"), "peak_queued": peaks.get("queued"),
+ "peak_waiting": peaks.get("waiting"),
+ "peak_occupied_slots": peaks.get("occupied_slots"), "peak_groups": peaks.get("groups"),
+ "peak_admission_rejected": peaks.get("admission_rejected")}}
+
+
+def _write_new(path: Path, data: bytes) -> None:
+ descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ try:
+ with os.fdopen(descriptor, "wb") as stream:
+ stream.write(data)
+ stream.flush()
+ os.fsync(stream.fileno())
+ except BaseException:
+ path.unlink(missing_ok=True)
+ raise
+
+
+def _progress_write(path: Path, record: dict, *, first: bool = False) -> None:
+ encoded = (json.dumps(record, ensure_ascii=False, sort_keys=True, allow_nan=False) + "\n").encode("utf-8")
+ if len(encoded) > 4096:
+ raise ProfileError("benchmark progress record exceeded 4 KiB", 6)
+ if first:
+ _write_new(path, encoded)
+ return
+ temporary = path.with_name(".progress-" + uuid.uuid4().hex + ".tmp")
+ try:
+ _write_new(temporary, encoded)
+ os.replace(temporary, path)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+
+def progress(path: Path) -> dict:
+ """Read only bounded phase evidence; a running record does not prove liveness."""
+ target = (path / "progress.json" if path.is_dir() else
+ path.with_name("progress.json") if path.name == "results.json" else path)
+ try:
+ details = target.lstat()
+ if not stat.S_ISREG(details.st_mode) or details.st_size > 4096 or \
+ (os.name == "posix" and (details.st_uid != os.getuid() or
+ stat.S_IMODE(details.st_mode) & 0o077)):
+ raise ProfileError("benchmark progress must be an owner-only regular file under 4 KiB", 5)
+ record = json.loads(target.read_text(encoding="utf-8"))
+ except (OSError, UnicodeError, ValueError) as exc:
+ if isinstance(exc, ProfileError):
+ raise
+ raise ProfileError("cannot read benchmark progress", 5) from None
+ phases = record.get("planned_phases") if isinstance(record, dict) else None
+ if (not isinstance(record, dict) or set(record) != {"schema_version", "kind", "suite", "instance_id",
+ "started_at", "updated_at", "state", "planned_phases",
+ "completed_phases", "current_phase", "last_completed",
+ "successful"} or
+ type(record.get("schema_version")) is not int or record["schema_version"] != 1 or
+ record.get("kind") != "strata.serving.benchmark.progress" or
+ record.get("suite") not in SUITES or not re.fullmatch(r"[0-9a-f]{32}", str(record.get("instance_id"))) or
+ not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\+00:00",
+ str(record.get("started_at"))) or
+ not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\+00:00",
+ str(record.get("updated_at"))) or
+ record.get("state") not in ("running", "report_saved", "cancelled") or
+ not isinstance(phases, list) or not 1 <= len(phases) <= 21 or
+ any(phase not in ("warmup", "serial", "mixed", "overload", "recovery",
+ "cancel_active", "cancel_queued", "cancel_prefill") for phase in phases) or
+ type(record.get("completed_phases")) is not int or
+ not 0 <= record["completed_phases"] <= len(phases) or
+ record.get("current_phase") not in (None, *phases) or
+ record.get("last_completed") not in (None, *phases) or
+ (record["state"] == "running" and record.get("successful") is not None) or
+ (record["state"] in ("report_saved", "cancelled") and type(record.get("successful")) is not bool) or
+ (record["state"] == "cancelled" and record.get("successful") is not False)):
+ raise ProfileError("benchmark progress has an unsupported shape", 5)
+ if record["state"] in ("report_saved", "cancelled"):
+ report = load(target.parent)
+ if (report["suite"] != record["suite"] or report["instance_id"] != record["instance_id"] or
+ report["successful"] != record["successful"] or
+ report.get("planned_phases") != record["planned_phases"] or
+ len(report["phases"]) != record["completed_phases"] or
+ bool(report.get("cancelled")) != (record["state"] == "cancelled")):
+ raise ProfileError("benchmark progress and report do not match", 5)
+ return record
+
+
+def run(endpoint: Endpoint, telemetry: Endpoint, out: Path, *, suite: str = "serving-smoke",
+ concurrency: int = 4, repeat: int = 1, request_timeout: float = 120,
+ profile_identity: dict | None = None, condition: str | None = None,
+ require_managed_match: bool = False) -> dict:
+ if suite not in SUITES:
+ raise ProfileError("unknown serving benchmark suite")
+ maximum = 64 if suite == "parallel-overload-v1" else 16
+ if not 1 <= concurrency <= maximum or not 1 <= repeat <= 5 or not 1 <= request_timeout <= 600:
+ raise ProfileError(f"concurrency must be 1..{maximum}, repeat 1..5 and request timeout 1..600 seconds")
+ if condition is not None and not re.fullmatch(r"[a-z][a-z0-9_-]{0,39}", condition):
+ raise ProfileError("benchmark condition must be a lowercase name up to 40 characters")
+ if out.exists() or out.is_symlink():
+ raise ProfileError("benchmark output directory already exists", 2)
+ before = telemetry.snapshot()
+ instance = (before.get("instance") or {}).get("id")
+ if not instance or (before.get("model") or {}).get("loaded") is not True:
+ raise ProfileError("benchmark needs a loaded Strata instance with versioned telemetry", 5)
+ managed_before = None
+ if require_managed_match:
+ managed_before = _managed_match(profile_identity or {}, endpoint.root, before)
+ if not managed_before["matched"]:
+ raise ProfileError("managed benchmark preflight failed: " + managed_before["reason"], 5)
+ if suite == "parallel-overload-v1":
+ work = before.get("work") or {}
+ limit = work.get("admission_limit")
+ deadline = work.get("queue_timeout_s")
+ if (type(limit) is not int or limit < 1 or type(deadline) not in (int, float) or
+ not math.isfinite(deadline) or deadline <= 0):
+ raise ProfileError("overload suite requires a server with max_queue and queue_timeout configured", 5)
+ if concurrency <= limit:
+ raise ProfileError(f"overload concurrency must exceed the admission limit ({limit})", 2)
+ slots = None
+ if suite in ("parallel-cancel-v1", "parallel-prefill-cancel-v1"):
+ work = before.get("work") or {}
+ slots = work.get("slots_effective")
+ if (type(slots) is not int or not 1 <= slots <= 16 or
+ type(work.get("client_disconnect_cancels")) is not int):
+ raise ProfileError("cancellation suite requires 1..16 effective slots and disconnect telemetry", 5)
+ if suite == "parallel-cancel-v1":
+ if (type(work.get("max_queue")) is not int or work["max_queue"] < 1 or
+ type(work.get("queue_timeout_s")) not in (int, float) or
+ not math.isfinite(work["queue_timeout_s"]) or work["queue_timeout_s"] < 2):
+ raise ProfileError("cancellation suite requires max_queue >= 1 and "
+ "queue_timeout >= 2 seconds", 5)
+ if concurrency < slots:
+ raise ProfileError(f"cancellation concurrency must cover all {slots} effective slots", 2)
+ elif slots < 2 or concurrency < 2:
+ raise ProfileError("prefill cancellation suite requires at least two effective slots and concurrency >= 2", 5)
+ out.mkdir(mode=0o700, parents=False)
+ phases = []
+ started = _utc_now()
+ planned_phases = _planned_phase_kinds(suite, repeat)
+ progress_record = {"schema_version": 1, "kind": "strata.serving.benchmark.progress",
+ "suite": suite, "instance_id": instance, "started_at": started,
+ "updated_at": started, "state": "running", "planned_phases": planned_phases,
+ "completed_phases": 0, "current_phase": None,
+ "last_completed": None, "successful": None}
+ progress_path = out / "progress.json"
+ _progress_write(progress_path, progress_record, first=True)
+
+ def mark(*, current: str | None = None, completed: str | None = None) -> None:
+ if completed is not None:
+ progress_record["completed_phases"] = len(phases)
+ progress_record["last_completed"] = completed
+ progress_record["current_phase"] = current
+ progress_record["updated_at"] = _utc_now()
+ _progress_write(progress_path, progress_record)
+
+ operator = OperatorCancellation(out)
+ with operator:
+ try:
+ for kind in SUITES[suite]:
+ if operator.event.is_set():
+ break
+ if kind in ("cancel_active", "cancel_queued", "cancel_prefill"):
+ mark(current=kind)
+ phase = _cancel_phase(endpoint, telemetry, kind=kind, slots=slots,
+ timeout=request_timeout, operator=operator)
+ if operator.event.is_set():
+ break
+ phases.append(phase)
+ mark(completed=kind)
+ continue
+ for _ in range(1 if kind in ("warmup", "recovery") else repeat):
+ if operator.event.is_set():
+ break
+ mark(current=kind)
+ count = 1 if kind in ("warmup", "recovery") else 2 if kind == "serial" else concurrency
+ workers = concurrency if kind in ("mixed", "overload") else 1
+ phase = _phase(endpoint, telemetry, kind=kind, count=count,
+ concurrency=workers, timeout=request_timeout, operator=operator)
+ if operator.event.is_set():
+ break
+ phases.append(phase)
+ mark(completed=kind)
+ if not phases[-1]["passed"] and kind != "overload":
+ break
+ if operator.event.is_set() or (phases and not phases[-1]["passed"] and kind != "overload"):
+ break
+ finally:
+ try:
+ after = telemetry.snapshot()
+ except (ClientError, ValueError):
+ after = {}
+ cancelled = operator.event.is_set() or operator.path.exists()
+ success = (not cancelled and len(phases) == len(planned_phases)
+ and all(p["passed"] for p in phases)
+ and (after.get("instance") or {}).get("id") == instance)
+ managed_after = (_managed_match(profile_identity or {}, endpoint.root, after)
+ if require_managed_match else None)
+ if require_managed_match and (not managed_after["matched"] or
+ managed_after.get("instance_id") != managed_before.get("instance_id")):
+ success = False
+ report = {"schema_version": SCHEMA, "kind": "strata.serving.benchmark",
+ "run_id": uuid.uuid4().hex, "suite": suite, "started_at": started,
+ "finished_at": _utc_now(), "server_root": endpoint.root,
+ "condition": condition, "environment": _environment(before),
+ "profile_identity": profile_identity,
+ "profile_running_match": "managed_launch_checked" if require_managed_match and success else "unverified",
+ "profile_running_check": {"before": managed_before, "after": managed_after}
+ if require_managed_match else None,
+ "instance_id": instance, "model_id": (before.get("model") or {}).get("id"),
+ "planned_phases": planned_phases,
+ "before": _sample(before), "after": _sample(after), "phases": phases,
+ "successful": success, "cancelled": cancelled,
+ "limitations": ["client-observed timings; no synchronized backend clock",
+ "missing telemetry samples are not zero",
+ "no engine batch-window or stage mapping measurement",
+ "condition is operator-supplied; monitor attachment is not verified",
+ "environment fields come from server telemetry, not hardware attestation",
+ "managed launch is checked only at the beginning and end; post-start changes are not continuously verified"
+ if require_managed_match else
+ "selected local profile is not authenticated as the running instance's config",
+ "driver and model artifact hashes not verified by this suite"] +
+ (["client-disconnect cancellation is inferred from a server counter and "
+ "request disappearance; run without unrelated clients"]
+ if suite in ("parallel-cancel-v1", "parallel-prefill-cancel-v1") else [])}
+ encoded = (json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False) + "\n").encode("utf-8")
+ if len(encoded) > MAX_REPORT_BYTES:
+ raise ProfileError("benchmark report exceeded 4 MiB", 6)
+ _write_new(out / "results.json", encoded)
+ progress_record.update({"state": "cancelled" if cancelled else "report_saved", "successful": success,
+ "current_phase": None, "updated_at": _utc_now()})
+ _progress_write(progress_path, progress_record)
+ return report
+
+
+def load(path: Path) -> dict:
+ target = path / "results.json" if path.is_dir() else path
+ try:
+ if not stat.S_ISREG(target.lstat().st_mode) or target.stat().st_size > MAX_REPORT_BYTES:
+ raise ProfileError("benchmark report must be a regular file under 4 MiB", 5)
+ result = json.loads(target.read_text(encoding="utf-8"))
+ except (OSError, UnicodeError, ValueError) as exc:
+ if isinstance(exc, ProfileError):
+ raise
+ raise ProfileError("cannot read benchmark report", 5) from None
+ planned = result.get("planned_phases") if isinstance(result, dict) else None
+ if not isinstance(result, dict) or type(result.get("schema_version")) is not int or \
+ result.get("schema_version") != SCHEMA or result.get("kind") != "strata.serving.benchmark" or \
+ not isinstance(result.get("phases"), list) or len(result["phases"]) > 21 or \
+ not re.fullmatch(r"[0-9a-f]{32}", str(result.get("run_id", ""))) or \
+ not isinstance(result.get("suite"), str) or result["suite"] not in SUITES or \
+ (result.get("condition") is not None and
+ (not isinstance(result["condition"], str) or
+ not re.fullmatch(r"[a-z][a-z0-9_-]{0,39}", result["condition"]))) or \
+ not re.fullmatch(r"[0-9a-f]{32}", str(result.get("instance_id", ""))) or \
+ type(result.get("successful")) is not bool or \
+ ("cancelled" in result and type(result["cancelled"]) is not bool) or \
+ (result.get("cancelled") is True and result["successful"] is not False) or \
+ (result.get("model_id") is not None and
+ (not isinstance(result["model_id"], str) or len(result["model_id"]) > 120 or
+ not result["model_id"].isprintable())) or \
+ not all(isinstance(phase, dict) and isinstance(phase.get("summary"), dict) and
+ phase.get("kind") in ("warmup", "serial", "mixed", "overload", "recovery",
+ "cancel_active", "cancel_queued", "cancel_prefill") and
+ type(phase.get("requested")) is int and
+ type(phase.get("client_workers")) is int and
+ type(phase["summary"].get("successful")) is int and
+ type(phase["summary"].get("failed")) is int and
+ ("passed" not in phase or type(phase["passed"]) is bool) and
+ (phase.get("kind") not in ("overload", "cancel_active", "cancel_queued", "cancel_prefill") or
+ type(phase.get("passed")) is bool) and
+ (phase.get("kind") not in ("cancel_active", "cancel_queued", "cancel_prefill") or
+ ("client_disconnect_delta" in phase["summary"] and
+ (phase["summary"]["client_disconnect_delta"] is None or
+ type(phase["summary"]["client_disconnect_delta"]) is int) and
+ type(phase["summary"].get("target_state_seen")) is bool and
+ (phase.get("kind") != "cancel_prefill" or
+ type(phase["summary"].get("prompt_read_seen")) is bool) and
+ type(phase["summary"].get("settled")) is bool)) and
+ all(key in phase["summary"] for key in ("p95_latency_s", "output_tok_s",
+ "peak_occupied_slots"))
+ for phase in result["phases"]):
+ raise ProfileError("unsupported benchmark report", 5)
+ kinds = [phase["kind"] for phase in result["phases"]]
+ valid_plans = [_planned_phase_kinds(result["suite"], repeat) for repeat in range(1, 6)]
+ if (planned is not None and
+ (not isinstance(planned, list) or planned not in valid_plans or
+ kinds != planned[:len(kinds)] or
+ (result["successful"] and len(kinds) != len(planned)))) or \
+ (result["successful"] and
+ (kinds not in valid_plans or any(phase.get("passed") is False
+ for phase in result["phases"]))):
+ raise ProfileError("unsupported benchmark report", 5)
+ return result
+
+
+def summary(report: dict) -> dict:
+ fields = ("successful", "failed", "expected_overload", "admission_full", "queue_wait_timeout",
+ "launch_spread_s",
+ "admission_rejected_delta",
+ "queue_timeouts_delta", "client_disconnect_delta", "target_state_seen", "client_closed",
+ "first_content_seen", "companion_successful", "settled",
+ "p50_latency_s", "p95_latency_s", "p50_ttft_s", "p95_ttft_s",
+ "output_tokens", "output_tok_s", "peak_active", "peak_queued", "peak_waiting",
+ "peak_occupied_slots", "peak_groups", "peak_admission_rejected")
+ rows = []
+ for phase in report["phases"]:
+ rows.append({"kind": phase["kind"], "requested": phase["requested"],
+ "passed": phase.get("passed", phase["summary"]["failed"] == 0),
+ "client_workers": phase["client_workers"],
+ **{key: phase["summary"].get(key) for key in fields}})
+ return {"run_id": report["run_id"], "suite": report["suite"],
+ "condition": report.get("condition"),
+ "profile_running_match": report.get("profile_running_match", "unverified"),
+ "instance_id": report["instance_id"], "model_id": report["model_id"],
+ "successful": report["successful"], "cancelled": report.get("cancelled", False),
+ "phases": rows,
+ "planned_phase_count": len(report["planned_phases"])
+ if isinstance(report.get("planned_phases"), list) else None,
+ "completed_phase_count": len(rows)}
+
+
+def _workload_signature(phase: dict) -> tuple:
+ rows = phase.get("requests")
+ if not isinstance(rows, list) or len(rows) > 64:
+ raise ProfileError("benchmark comparison needs bounded request evidence", 5)
+ signatures = []
+ for row in rows:
+ if not isinstance(row, dict) or not re.fullmatch(r"[0-9a-f]{64}", str(row.get("prompt_sha256", ""))) or \
+ type(row.get("max_tokens")) is not int or not 1 <= row["max_tokens"] <= 65536 or \
+ not isinstance(row.get("label"), str) or not re.fullmatch(r"[a-z_]{1,40}", row["label"]):
+ raise ProfileError("benchmark comparison needs valid request fingerprints", 5)
+ signatures.append((row["prompt_sha256"], row["max_tokens"], row["label"]))
+ return (phase["kind"], phase["requested"], phase["client_workers"], tuple(sorted(signatures)))
+
+
+def _metric(value: object) -> float | None:
+ if type(value) not in (int, float) or not 0 <= value <= 1e9:
+ return None
+ return float(value) if math.isfinite(value) else None
+
+
+def _change(baseline: object, candidate: object) -> dict:
+ old, new = _metric(baseline), _metric(candidate)
+ return {"baseline": old, "candidate": new,
+ "delta": round(new - old, 4) if old is not None and new is not None else None,
+ "delta_percent": round(100 * (new / old - 1), 2)
+ if old is not None and new is not None and old > 0 else None}
+
+
+def compare(baseline: dict, candidate: dict) -> dict:
+ """Compare two saved runs without claiming hardware or monitor-state attestation."""
+ if not baseline["successful"] or not candidate["successful"]:
+ raise ProfileError("benchmark comparison requires two successful runs", 5)
+ if baseline["run_id"] == candidate["run_id"]:
+ raise ProfileError("benchmark comparison needs two distinct runs", 2)
+ if (baseline["suite"] != candidate["suite"] or baseline["model_id"] != candidate["model_id"] or
+ not baseline["model_id"]):
+ raise ProfileError("benchmark suite and model ID must match", 5)
+ old_phases, new_phases = baseline["phases"], candidate["phases"]
+ if len(old_phases) != len(new_phases) or not old_phases:
+ raise ProfileError("benchmark phase counts differ", 5)
+ if any(_workload_signature(old) != _workload_signature(new)
+ for old, new in zip(old_phases, new_phases)):
+ raise ProfileError("benchmark request workload or concurrency differs", 5)
+
+ warnings = []
+ old_profile = baseline.get("profile_identity")
+ new_profile = candidate.get("profile_identity")
+ old_profile = old_profile if isinstance(old_profile, dict) else {}
+ new_profile = new_profile if isinstance(new_profile, dict) else {}
+ old_digest, new_digest = old_profile.get("source_sha256"), new_profile.get("source_sha256")
+ if old_digest and new_digest:
+ if old_digest != new_digest:
+ raise ProfileError("benchmark source config digests differ", 5)
+ else:
+ warnings.append("source config identity missing from one or both reports")
+ if (baseline.get("profile_running_match") != "managed_launch_checked" or
+ candidate.get("profile_running_match") != "managed_launch_checked"):
+ warnings.append("source config was not attested as the running server config")
+
+ old_env = baseline.get("environment")
+ new_env = candidate.get("environment")
+ old_env = old_env if isinstance(old_env, dict) else {}
+ new_env = new_env if isinstance(new_env, dict) else {}
+ for key in ("model_context", "slots_effective", "groups", "max_queue", "queue_timeout_s",
+ "selected_devices", "stages", "devices"):
+ old, new = old_env.get(key), new_env.get(key)
+ if old is None or new is None or old == [] or new == []:
+ warnings.append(f"{key} identity is unavailable in one or both reports")
+ elif old != new:
+ raise ProfileError(f"benchmark reported environment differs: {key}", 5)
+ warnings.append("driver, engine binary, model artifact and monitor attachment are not attested by these reports")
+
+ metric_keys = ("p95_ttft_s", "p95_latency_s", "output_tok_s", "admission_full",
+ "queue_wait_timeout", "admission_rejected_delta", "queue_timeouts_delta",
+ "client_disconnect_delta", "companion_successful", "launch_spread_s",
+ "peak_waiting", "peak_queued")
+ phases = []
+ for index, (old, new) in enumerate(zip(old_phases, new_phases)):
+ phases.append({"index": index, "kind": old["kind"], "requested": old["requested"],
+ "client_workers": old["client_workers"],
+ "duration_s": _change(old.get("duration_s"), new.get("duration_s")),
+ "metrics": {key: _change(old["summary"].get(key), new["summary"].get(key))
+ for key in metric_keys}})
+ primary_kind = next((kind for kind in ("mixed", "overload", "serial", "cancel_prefill",
+ "cancel_active", "cancel_queued", "recovery")
+ if any(phase["kind"] == kind for phase in phases)), phases[0]["kind"])
+ primary = [phase for phase in phases if phase["kind"] == primary_kind]
+ if len(primary) < 3:
+ warnings.append("fewer than three measured primary phases; repeat the workload for qualification")
+ medians = {}
+ for key in ("p95_ttft_s", "p95_latency_s", "output_tok_s"):
+ old_values = [phase["metrics"][key]["baseline"] for phase in primary]
+ new_values = [phase["metrics"][key]["candidate"] for phase in primary]
+ medians[key] = _change(statistics.median(old_values) if all(x is not None for x in old_values) else None,
+ statistics.median(new_values) if all(x is not None for x in new_values) else None)
+ return {"schema_version": 1, "kind": "strata.serving.benchmark_comparison",
+ "suite": baseline["suite"], "model_id": baseline["model_id"],
+ "baseline": {"run_id": baseline["run_id"], "condition": baseline.get("condition"),
+ "profile_running_match": baseline.get("profile_running_match", "unverified")},
+ "candidate": {"run_id": candidate["run_id"], "condition": candidate.get("condition"),
+ "profile_running_match": candidate.get("profile_running_match", "unverified")},
+ "workload_match": True, "qualification": "provisional",
+ "primary_kind": primary_kind, "primary_phases": len(primary),
+ "median_primary_metrics": medians, "phases": phases, "warnings": warnings}
+
+
+def format_comparison(value: dict) -> str:
+ def pair(metric: dict) -> str:
+ return (f"{metric['baseline']:g} -> {metric['candidate']:g}"
+ if metric["baseline"] is not None and metric["candidate"] is not None else "unavailable")
+
+ lines = [f"{value['suite']} - provisional comparison ({value['primary_phases']} "
+ f"{value['primary_kind']} phases)",
+ f"Baseline {value['baseline']['condition'] or value['baseline']['run_id']} "
+ f"Candidate {value['candidate']['condition'] or value['candidate']['run_id']}",
+ f"Managed launch: baseline {value['baseline']['profile_running_match']}, "
+ f"candidate {value['candidate']['profile_running_match']}"]
+ for label, key in (("p95 TTFT", "p95_ttft_s"), ("p95 latency", "p95_latency_s"),
+ ("output throughput", "output_tok_s")):
+ metric = value["median_primary_metrics"][key]
+ if metric["baseline"] is None or metric["candidate"] is None:
+ lines.append(f"{label}: unavailable")
+ else:
+ unit = " tok/s" if key == "output_tok_s" else " s"
+ change = (f"{metric['delta_percent']:+.2f}%" if metric["delta_percent"] is not None
+ else "percent unavailable")
+ lines.append(f"{label}: {metric['baseline']:.4f}{unit} -> "
+ f"{metric['candidate']:.4f}{unit} ({change})")
+ for phase in value["phases"]:
+ metrics = phase["metrics"]
+ if phase["kind"] == "overload":
+ lines.append(f"overload {phase['index']}: admission full {pair(metrics['admission_full'])}, "
+ f"queue timeout {pair(metrics['queue_wait_timeout'])}, "
+ f"duration {pair(phase['duration_s'])} s")
+ elif phase["kind"].startswith("cancel_"):
+ lines.append(f"{phase['kind']}: disconnects {pair(metrics['client_disconnect_delta'])}, "
+ f"companions {pair(metrics['companion_successful'])}, "
+ f"duration {pair(phase['duration_s'])} s")
+ lines.extend(f"Note: {warning}" for warning in value["warnings"])
+ return "\n".join(lines)
+
+
+def format_summary(value: dict) -> str:
+ def shown(value):
+ return "--" if value is None else value
+
+ condition = f" [{value['condition']}]" if value.get("condition") else ""
+ outcome = "cancelled" if value.get("cancelled") else "passed" if value["successful"] else "failed"
+ lines = [f"{value['suite']}{condition} - {outcome}",
+ f"Instance {value['instance_id']} Model {value['model_id']}",
+ f"Config match {value.get('profile_running_match', 'unverified')}"]
+ for phase in value["phases"]:
+ if phase["kind"] in ("cancel_active", "cancel_queued"):
+ lines.append(f"{phase['kind']}: {'passed' if phase['passed'] else 'failed'} "
+ f"companions {shown(phase.get('companion_successful'))}")
+ else:
+ lines.append(f"{phase['kind']}: {phase['successful']}/{phase['requested']} requests "
+ f"p95 TTFT {shown(phase.get('p95_ttft_s'))} s "
+ f"p95 latency {shown(phase.get('p95_latency_s'))} s "
+ f"output {shown(phase.get('output_tok_s'))} tok/s")
+ if phase["kind"] == "overload":
+ lines.append(f" launch spread {shown(phase.get('launch_spread_s'))} s "
+ f"rejected {shown(phase.get('admission_full'))} "
+ f"timed out {shown(phase.get('queue_wait_timeout'))} "
+ f"unexpected failures {shown(phase.get('failed'))} "
+ f"rejected delta {shown(phase.get('admission_rejected_delta'))} "
+ f"timeout delta {shown(phase.get('queue_timeouts_delta'))}")
+ if phase["kind"] in ("cancel_active", "cancel_queued"):
+ lines.append(f" target seen {shown(phase.get('target_state_seen'))} "
+ f"client closed {shown(phase.get('client_closed'))} "
+ f"disconnect delta {shown(phase.get('client_disconnect_delta'))} "
+ f"companions completed {shown(phase.get('companion_successful'))} "
+ f"settled {shown(phase.get('settled'))}")
+ lines.append(f" peak active {shown(phase.get('peak_active'))} "
+ f"occupied {shown(phase.get('peak_occupied_slots'))} "
+ f"engine waiting {shown(phase.get('peak_waiting'))} "
+ f"queued {shown(phase.get('peak_queued'))} groups {shown(phase.get('peak_groups'))}")
+ return "\n".join(lines)
+
+
+def _md_cell(value: object, *, limit: int = 120) -> str:
+ """Bound an untrusted report label before placing it in a Markdown cell."""
+ if value is None:
+ return "unavailable"
+ raw = str(value)
+ raw = " ".join(part for part in raw.split() if part)
+ raw = "".join(char for char in raw[:limit] if char.isprintable())
+ for char in ("\\", "|", "*", "_", "[", "]", "<", ">", "`"):
+ raw = raw.replace(char, "\\" + char)
+ return raw or "unavailable"
+
+
+def _md_number(value: object, *, digits: int = 3) -> str:
+ measured = _metric(value)
+ if measured is None:
+ return "unavailable"
+ return str(int(measured)) if measured.is_integer() else f"{measured:.{digits}f}"
+
+
+def _md_time(value: object) -> str:
+ return value if isinstance(value, str) and len(value) <= 40 and re.fullmatch(
+ r"[0-9TZ:+.\-]+", value) else "unavailable"
+
+
+def markdown_report(report: dict) -> str:
+ """Render a shareable, bounded summary without endpoint, paths or request text."""
+ compact = summary(report)
+ incomplete = (compact["planned_phase_count"] is not None and
+ compact["completed_phase_count"] < compact["planned_phase_count"])
+ result_label = ("Cancelled" if compact["cancelled"] else "Passed" if compact["successful"]
+ else "Incomplete" if incomplete else "Failed")
+ rows = ["# Strata serving benchmark", "",
+ "This report summarizes client-observed requests and server-reported telemetry. "
+ "It is not a hardware or model-quality qualification.", "",
+ "| Run | Value |", "| --- | --- |",
+ f"| Result | {result_label} |",
+ f"| Phases | {compact['completed_phase_count']} of {compact['planned_phase_count'] if compact['planned_phase_count'] is not None else 'unavailable'} |",
+ f"| Suite | {_md_cell(compact['suite'])} |",
+ f"| Run ID | {_md_cell(compact['run_id'])} |",
+ f"| Started (UTC) | {_md_time(report.get('started_at'))} |",
+ f"| Finished (UTC) | {_md_time(report.get('finished_at'))} |",
+ f"| Operator condition | {_md_cell(compact.get('condition'))} |",
+ f"| Model ID | {_md_cell(compact.get('model_id'))} |",
+ f"| Instance ID | {_md_cell(compact.get('instance_id'))} |",
+ f"| Managed launch check | {_md_cell(compact.get('profile_running_match'))} |",
+ "", "## Measured phases", "",
+ "| Phase | Clients | Succeeded | Failed | p95 TTFT (s) | p95 latency (s) | Output (tok/s) | Peak active | Peak queued | Peak slots | Peak groups | Result |",
+ "| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | --- |"]
+ for phase in compact["phases"][:21]:
+ rows.append("| " + " | ".join((
+ _md_cell(phase.get("kind")), _md_number(phase.get("client_workers")),
+ _md_number(phase.get("successful")), _md_number(phase.get("failed")),
+ _md_number(phase.get("p95_ttft_s")), _md_number(phase.get("p95_latency_s")),
+ _md_number(phase.get("output_tok_s")), _md_number(phase.get("peak_active")),
+ _md_number(phase.get("peak_queued")), _md_number(phase.get("peak_occupied_slots")),
+ _md_number(phase.get("peak_groups")), "Passed" if phase.get("passed") else "Failed",
+ )) + " |")
+ exceptional = [phase for phase in compact["phases"] if phase.get("kind") in
+ ("overload", "cancel_active", "cancel_queued", "cancel_prefill")]
+ if exceptional:
+ rows += ["", "## Admission and cancellation observations", "",
+ "| Phase | Expected overload | Admission full | Queue timeout | Disconnect delta | Companion completed | Settled |",
+ "| --- | ---: | ---: | ---: | ---: | ---: | --- |"]
+ for phase in exceptional:
+ rows.append("| " + " | ".join((
+ _md_cell(phase.get("kind")), _md_number(phase.get("expected_overload")),
+ _md_number(phase.get("admission_full")), _md_number(phase.get("queue_wait_timeout")),
+ _md_number(phase.get("client_disconnect_delta")),
+ _md_number(phase.get("companion_successful")),
+ "Yes" if phase.get("settled") is True else
+ "No" if phase.get("settled") is False else "unavailable",
+ )) + " |")
+ environment = report.get("environment")
+ environment = environment if isinstance(environment, dict) else {}
+ selected = environment.get("selected_devices")
+ selected = ", ".join(_md_number(item) for item in selected[:16]) if isinstance(selected, list) else "unavailable"
+ rows += ["", "## Server-reported environment", "",
+ "| Field | Value |", "| --- | --- |",
+ f"| Context tokens | {_md_number(environment.get('model_context'))} |",
+ f"| Effective slots | {_md_number(environment.get('slots_effective'))} |",
+ f"| Pipeline groups | {_md_number(environment.get('groups'))} |",
+ f"| Maximum queue | {_md_number(environment.get('max_queue'))} |",
+ f"| Selected device indices | {selected or 'unavailable'} |"]
+ devices = environment.get("devices")
+ if isinstance(devices, list):
+ for device in devices[:16]:
+ if isinstance(device, dict):
+ rows.append(f"| Reported device {_md_number(device.get('index'))} | "
+ f"{_md_cell(device.get('name'))} |")
+ rows += ["", "## Measurement limits", "",
+ "- Missing readings appear as `unavailable`; they are not zero.",
+ "- The condition label is operator supplied. Monitor attachment is not verified.",
+ "- Device names and serving configuration come from server telemetry. Driver, topology, "
+ "engine binary and model artifact hashes are not attested here.",
+ "- A managed launch check, when present, covers the beginning and end of the run only.",
+ "- Timings are observed by the client. This report does not measure GPU kernel occupancy "
+ "or independently synchronize backend clocks.", ""]
+ return "\n".join(rows)
+
+
+def markdown_comparison(comparison: dict) -> str:
+ """Render the workload-checked comparison with provisional status visible."""
+ rows = ["# Strata serving benchmark comparison", "",
+ "**Provisional comparison.** The saved runs passed workload checks; environment "
+ "and monitor attachment still need independent qualification.", "",
+ "| Run | Baseline | Candidate |", "| --- | --- | --- |",
+ f"| Suite | {_md_cell(comparison.get('suite'))} | {_md_cell(comparison.get('suite'))} |",
+ f"| Model ID | {_md_cell(comparison.get('model_id'))} | {_md_cell(comparison.get('model_id'))} |",
+ f"| Run ID | {_md_cell(comparison['baseline'].get('run_id'))} | {_md_cell(comparison['candidate'].get('run_id'))} |",
+ f"| Operator condition | {_md_cell(comparison['baseline'].get('condition'))} | {_md_cell(comparison['candidate'].get('condition'))} |",
+ f"| Managed launch check | {_md_cell(comparison['baseline'].get('profile_running_match'))} | {_md_cell(comparison['candidate'].get('profile_running_match'))} |",
+ "", f"Primary phase: {_md_cell(comparison.get('primary_kind'))} "
+ f"({_md_number(comparison.get('primary_phases'))} measured phase(s)).", "",
+ "| Median primary metric | Baseline | Candidate | Change |",
+ "| --- | ---: | ---: | ---: |"]
+ for label, key, unit in (("p95 TTFT", "p95_ttft_s", "s"),
+ ("p95 latency", "p95_latency_s", "s"),
+ ("Output throughput", "output_tok_s", "tok/s")):
+ metric = comparison["median_primary_metrics"][key]
+ change = metric.get("delta_percent")
+ change_text = (f"{change:+.2f}%" if type(change) in (int, float) and
+ math.isfinite(change) and abs(change) <= 1e9 else "unavailable")
+ rows.append(f"| {label} ({unit}) | {_md_number(metric.get('baseline'))} | "
+ f"{_md_number(metric.get('candidate'))} | {change_text} |")
+ rows += ["", "## Per-phase results", "",
+ "| Phase | Clients | Baseline p95 TTFT (s) | Candidate p95 TTFT (s) | Baseline output (tok/s) | Candidate output (tok/s) |",
+ "| --- | ---: | ---: | ---: | ---: | ---: |"]
+ for phase in comparison["phases"][:21]:
+ metrics = phase["metrics"]
+ rows.append("| " + " | ".join((
+ _md_cell(phase.get("kind")), _md_number(phase.get("client_workers")),
+ _md_number(metrics["p95_ttft_s"].get("baseline")),
+ _md_number(metrics["p95_ttft_s"].get("candidate")),
+ _md_number(metrics["output_tok_s"].get("baseline")),
+ _md_number(metrics["output_tok_s"].get("candidate")),
+ )) + " |")
+ rows += ["", "## Comparison limits", ""]
+ rows.extend(f"- {_md_cell(warning, limit=240)}" for warning in comparison.get("warnings", [])[:32])
+ rows += ["- A percentage change describes the observed result; it does not by itself "
+ "establish an improvement or hardware qualification.", ""]
+ return "\n".join(rows)
+
+
+def write_markdown(path: Path, content: str) -> None:
+ """Create a shareable report file without replacing an earlier result."""
+ encoded = content.encode("utf-8")
+ if len(encoded) > 64 * 1024:
+ raise ProfileError("Markdown benchmark report exceeded 64 KiB", 6)
+ if path.exists() or path.is_symlink():
+ raise ProfileError("Markdown output file already exists", 2)
+ _write_new(path, encoded)
diff --git a/strata_cli/cli.py b/strata_cli/cli.py
new file mode 100644
index 000000000..5894e6e90
--- /dev/null
+++ b/strata_cli/cli.py
@@ -0,0 +1,1741 @@
+"""Shared terminal command grammar and stable exit codes."""
+
+from __future__ import annotations
+
+import argparse
+import contextlib
+import io
+import json
+import math
+import os
+import re
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+from strata_control import profiles
+
+#: Backend families, as the engine package manifest records them. Kept here so the argument parsers
+#: stay declarative without importing the tuning module on every CLI start.
+BACKENDS = ("metal", "cuda", "hip", "sycl", "cpu")
+from strata_control.doctor import inspect as inspect_components
+from strata_control.profiles import ProfileError
+from strata_cli.client import ClientError, Endpoint
+from strata_cli import monitor_commands
+
+
+def parser() -> argparse.ArgumentParser:
+ ap = argparse.ArgumentParser(prog="strata", description="Strata serving and terminal clients")
+ sp = ap.add_subparsers(dest="command", required=True)
+ serve = sp.add_parser("serve", help="start the existing Strata inference server in the foreground")
+ serve.add_argument("--profile", "--config", dest="config", required=True, metavar="CONFIG.json")
+ serve.add_argument("--host")
+ serve.add_argument("--port", type=int)
+ serve.add_argument("--parallel", type=int, help="requested concurrent engine slots")
+ serve.add_argument("--batch-groups", help="requested pipeline groups (auto or positive integer)")
+ serve.add_argument("--max-queue", type=int, help="maximum pending inference calls beyond effective slots")
+ serve.add_argument("--queue-timeout", type=float, help="seconds to wait for the first engine turn (0.1..600)")
+ serve.add_argument("--batch-telemetry", action=argparse.BooleanOptionalAction, default=None,
+ help="sample actual engine decode-window rows for the monitor (opt-in)")
+ serve.add_argument("--offline", action="store_true", help="disable remote image fetches and MCP/tool subprocesses")
+ serve.add_argument("--ready-file", help="absolute path for a new instance record (use a private directory)")
+ serve.add_argument("--shutdown-timeout", type=float, default=30,
+ help="seconds to drain owned inference calls on stop (0..300)")
+ serve.add_argument("--plan", action="store_true", help="validate and print the effective launch without starting")
+ serve.add_argument("--output", choices=("human", "json", "jsonl"), default="human",
+ help="human output, JSON plan, or JSONL foreground lifecycle")
+ serve.add_argument("--json", action="store_true", help="alias for --plan --output json")
+ serve.add_argument("--quiet", action="store_true", help="suppress human informational output")
+
+ profile = sp.add_parser("profile", help="edit saved serving overrides outside setup's run config")
+ profile_sp = profile.add_subparsers(dest="profile_command", required=True)
+ profile_create = profile_sp.add_parser("create", help="save a named profile from an installed run config")
+ profile_create.add_argument("name")
+ profile_create.add_argument("--from-config", required=True, metavar="CONFIG.json")
+ profile_create.add_argument("--output", choices=("human", "json"), default="human")
+ profile_list = profile_sp.add_parser("list", help="list saved profiles")
+ profile_list.add_argument("--output", choices=("human", "json"), default="human")
+ profile_show = profile_sp.add_parser("show", help="show a profile and optional effective settings")
+ profile_show.add_argument("name")
+ profile_show.add_argument("--effective", action="store_true")
+ profile_show.add_argument("--output", choices=("human", "json"), default="human")
+ profile_validate = profile_sp.add_parser("validate", help="check the profile and referenced run config")
+ profile_validate.add_argument("name")
+ profile_validate.add_argument("--output", choices=("human", "json"), default="human")
+ profile_set = profile_sp.add_parser("set", help="set typed serving overrides, e.g. parallel=8")
+ profile_set.add_argument("name")
+ profile_set.add_argument("assignments", nargs="+")
+ profile_set.add_argument("--plan", action="store_true", help="show changes without saving")
+ profile_set.add_argument("--output", choices=("human", "json"), default="human")
+ profile_source = profile_sp.add_parser("use-config", help="point a saved profile at another run config file")
+ profile_source.add_argument("name")
+ profile_source.add_argument("--from-config", required=True, metavar="CONFIG.json")
+ profile_source.add_argument("--plan", action="store_true", help="show the source change without saving")
+ profile_source.add_argument("--if-revision", metavar="REVISION",
+ help="fail if the saved profile changed since preview")
+ profile_source.add_argument("--output", choices=("human", "json"), default="human")
+ profile_edit = profile_sp.add_parser("edit", help="edit a temporary JSON copy in VISUAL or EDITOR")
+ profile_edit.add_argument("name")
+ profile_edit.add_argument("--output", choices=("human", "json"), default="human")
+ profile_history = profile_sp.add_parser("history", help="list saved profile revisions")
+ profile_history.add_argument("name")
+ profile_history.add_argument("--output", choices=("human", "json"), default="human")
+ profile_rollback = profile_sp.add_parser("rollback", help="restore a saved profile revision")
+ profile_rollback.add_argument("name")
+ profile_rollback.add_argument("--to", required=True, metavar="REVISION")
+ profile_rollback.add_argument("--output", choices=("human", "json"), default="human")
+
+ doctor = sp.add_parser("doctor", help="read-only check of installed engine components")
+ doctor.add_argument("--profile", help="saved profile name or run config JSON path")
+ doctor.add_argument("--components", action="store_true", help="include component inventory (default)")
+ doctor.add_argument("--live", action="store_true", help="query host GPUs and compare selected device indices")
+ doctor.add_argument("--output", choices=("human", "json"), default="human")
+ components = sp.add_parser("components", help="read-only installed component inventory")
+ components_sp = components.add_subparsers(dest="components_command", required=True)
+ components_verify = components_sp.add_parser("verify", help="check required files for an installed profile")
+ components_verify.add_argument("--profile", required=True)
+ components_verify.add_argument("--live", action="store_true", help="query host GPUs and compare selected device indices")
+ components_verify.add_argument("--output", choices=("human", "json"), default="human")
+ components_plan = components_sp.add_parser(
+ "plan", help="read a component-package manifest and say whether it may be used here")
+ components_plan.add_argument("manifest", help="path to the component manifest (JSON)")
+ components_plan.add_argument("--backend", default=None,
+ help="the backend family to check the component against")
+ components_plan.add_argument("--target", default=None,
+ help="override the platform key, for checking another machine's "
+ "manifest on this one")
+ components_plan.add_argument("--output", choices=("human", "json"), default="human")
+ components_backend = components_sp.add_parser(
+ "backends", help="the OS and backend combinations that are committed to, and what is not")
+ components_backend.add_argument("--output", choices=("human", "json"), default="human")
+ models = sp.add_parser("models", help="inspect setup-written local model run configs")
+ models_sp = models.add_subparsers(dest="models_command", required=True)
+ models_list = models_sp.add_parser("list", help="list local installed-model config candidates")
+ models_scope = models_list.add_mutually_exclusive_group()
+ models_scope.add_argument("--installed", action="store_true", help="limit discovery to local setup run configs")
+ models_scope.add_argument("--served", action="store_true", help="inspect the currently served model")
+ models_list.add_argument("--install-dir", help="absolute path to a Strata installation")
+ models_list.add_argument("--url", help="Strata server root; remote connections require HTTPS")
+ models_list.add_argument("--connection", help="saved read-only connection")
+ models_list.add_argument("--credential-env", help="environment variable containing the server credential")
+ models_list.add_argument("--timeout", type=float, help="bounded request timeout in seconds")
+ models_list.add_argument("--output", choices=("human", "json"), default="human")
+ models_inspect = models_sp.add_parser("inspect", help="inspect a local model run config and its components")
+ models_inspect.add_argument("model_id")
+ models_inspect.add_argument("--install-dir", help="absolute path to a Strata installation")
+ models_inspect.add_argument("--output", choices=("human", "json"), default="human")
+ models_import = models_sp.add_parser("import", help="preview an existing GGUF file set without adopting it")
+ models_import.add_argument("path", metavar="PATH")
+ models_import.add_argument("--plan", action="store_true", required=True,
+ help="inspect only; adoption requires a qualified model workflow")
+ models_import.add_argument("--output", choices=("human", "json"), default="human")
+ engine = sp.add_parser("engine", help="engine tuning and component actions")
+ engine_sp = engine.add_subparsers(dest="engine_command", required=True)
+ calibrate = engine_sp.add_parser("calibrate", help="measure, review and apply engine tuning")
+ calibrate.add_argument("--profile", required=True)
+ calibrate_actions = calibrate.add_mutually_exclusive_group(required=True)
+ calibrate_actions.add_argument("--plan", action="store_true", help="read-only calibration preflight")
+ calibrate_actions.add_argument("--measure", action="store_true", help="run decode sweep and save a report")
+ calibrate_actions.add_argument("--review-result", metavar="REPORT.json", help="show a candidate and its freshness")
+ calibrate_actions.add_argument("--apply-result", metavar="REPORT.json", help="smoke-test and apply a fresh report")
+ calibrate_actions.add_argument("--review-rollback", metavar="REPORT.json",
+ help="check whether an applied result can be restored")
+ calibrate_actions.add_argument("--rollback-result", metavar="REPORT.json",
+ help="smoke-test and restore the configuration before an application")
+ calibrate.add_argument("--out", metavar="REPORT.json", help="new report path for --measure")
+ calibrate.add_argument("--exclusive", action="store_true", help="assert all model instances using these devices are stopped")
+ calibrate.add_argument("--output", choices=("human", "json"), default="human")
+ runtime = sp.add_parser("runtime", help="manage an owned local Strata server instance")
+ runtime_sp = runtime.add_subparsers(dest="runtime_command", required=True)
+ runtime_start = runtime_sp.add_parser("start", help="start a saved profile under the local owner host")
+ runtime_start.add_argument("--profile", required=True)
+ runtime_start.add_argument("--plan", action="store_true")
+ runtime_start.add_argument("--wait", type=float, default=300)
+ runtime_start.add_argument("--shutdown-timeout", type=float, default=30)
+ runtime_start.add_argument("--output", choices=("human", "json"), default="human")
+ runtime_status = runtime_sp.add_parser("status", help="inspect an owned local instance")
+ runtime_status.add_argument("--profile", required=True)
+ runtime_status.add_argument("--output", choices=("human", "json"), default="human")
+ runtime_verify = runtime_sp.add_parser("verify", help="recheck the owned API and one-token generation")
+ runtime_verify.add_argument("--profile", required=True)
+ runtime_verify.add_argument("--wait", type=float, default=300)
+ runtime_verify.add_argument("--load", action="store_true", help="load an unloaded model for the generation check")
+ runtime_verify.add_argument("--plan", action="store_true", help="preview the owned instance and verification effect")
+ runtime_verify.add_argument("--if-owner-id", metavar="OWNER_ID",
+ help="require the owner shown by verify --plan")
+ runtime_verify.add_argument("--if-instance-id", metavar="INSTANCE_ID",
+ help="require the instance shown by verify --plan")
+ runtime_verify.add_argument("--output", choices=("human", "json"), default="human")
+ runtime_stop = runtime_sp.add_parser("stop", help="drain and stop an owned local instance")
+ runtime_stop.add_argument("--profile", required=True)
+ runtime_stop.add_argument("--plan", action="store_true", help="review the current owner and instance")
+ runtime_stop.add_argument("--wait", type=float, default=330)
+ runtime_stop.add_argument("--if-owner-id", help="require the owner ID from --plan")
+ runtime_stop.add_argument("--if-instance-id", help="require the instance ID from --plan")
+ runtime_stop.add_argument("--output", choices=("human", "json"), default="human")
+ runtime_restart = runtime_sp.add_parser("restart", help="drain and rerun an owned saved profile")
+ runtime_restart.add_argument("--profile", required=True)
+ runtime_restart.add_argument("--plan", action="store_true", help="compare current and saved launch without draining")
+ runtime_restart.add_argument("--allow-source-switch", action="store_true",
+ help="permit a new source config file when the old file remains available for rollback")
+ runtime_restart.add_argument("--allow-source-migration", action="store_true",
+ help="permit edited run config bytes using a private rollback snapshot")
+ runtime_restart.add_argument("--wait", type=float, default=1000)
+ runtime_restart.add_argument("--startup-wait", type=float, default=300)
+ runtime_restart.add_argument("--if-profile-revision", metavar="REVISION")
+ runtime_restart.add_argument("--if-owner-id", metavar="OWNER_ID",
+ help="require the owner ID shown in --plan")
+ runtime_restart.add_argument("--if-instance-id", metavar="INSTANCE_ID",
+ help="require the instance ID shown in --plan")
+ runtime_restart.add_argument("--if-source-sha256", metavar="SHA256",
+ help="require the candidate source bytes shown in --plan")
+ runtime_restart.add_argument("--output", choices=("human", "json"), default="human")
+ ops = sp.add_parser("ops", help="edit and run typed local operator recipes")
+ ops_sp = ops.add_subparsers(dest="ops_command", required=True)
+ ops_items = []
+ for action in ("init", "list", "create", "show", "edit", "set", "history", "rollback",
+ "plan", "run", "runs", "result"):
+ item = ops_sp.add_parser(action)
+ ops_items.append(item)
+ if action == "result":
+ item.add_argument("operation_id")
+ elif action not in ("init", "list", "runs"):
+ item.add_argument("name")
+ item.add_argument("--profile", required=True)
+ item.add_argument("--output", choices=("human", "json"), default="human")
+ if action == "runs":
+ item.add_argument("--limit", type=int, default=20)
+ if action == "create":
+ item.add_argument("--kind", choices=("runtime.restart", "engine.calibrate.measure",
+ "components.verify"), required=True)
+ if action == "set":
+ item.add_argument("assignment", metavar="KEY=VALUE")
+ item.add_argument("--plan", action="store_true")
+ if action == "rollback":
+ item.add_argument("--to", required=True, metavar="REVISION")
+ if action == "run":
+ item.add_argument("--exclusive", action="store_true",
+ help="assert exclusive device access for a calibration measurement")
+ item.add_argument("--if-revision", metavar="REVISION",
+ help="fail if the saved recipe changed since preview")
+ item.add_argument("--if-profile-revision", metavar="REVISION",
+ help="fail if the saved serving profile changed since preview")
+ item.add_argument("--if-owner-id", metavar="OWNER_ID",
+ help="require the runtime owner shown in a restart recipe plan")
+ item.add_argument("--if-instance-id", metavar="INSTANCE_ID",
+ help="require the runtime instance shown in a restart recipe plan")
+ item.add_argument("--if-source-sha256", metavar="SHA256",
+ help="require the candidate run-config bytes shown in a restart recipe plan")
+ bench = sp.add_parser("bench", help="explicit serving benchmark with local JSON evidence")
+ bench_sp = bench.add_subparsers(dest="bench_command", required=True)
+ bench_run = bench_sp.add_parser("run", help="measure streaming requests and sample serving telemetry")
+ bench_source = bench_run.add_mutually_exclusive_group(required=True)
+ bench_source.add_argument("--profile", help="saved serving profile or installed run config")
+ bench_source.add_argument("--url", help="server root; remote connections require HTTPS")
+ bench_run.add_argument("--suite", choices=("serving-smoke", "parallel-mixed-v1", "parallel-overload-v1",
+ "parallel-cancel-v1", "parallel-prefill-cancel-v1"),
+ default="serving-smoke")
+ bench_run.add_argument("--concurrency", type=int, default=4,
+ help="simultaneous requests (1..16, or 1..64 for parallel-overload-v1)")
+ bench_run.add_argument("--repeat", type=int, default=1, help="repeat measured phases (1..5)")
+ bench_run.add_argument("--condition", help="operator label for this run, e.g. baseline or monitor-default")
+ bench_run.add_argument("--require-managed-match", action="store_true",
+ help="require the local owner host and current profile to match the serving instance")
+ bench_run.add_argument("--request-timeout", type=float, default=120)
+ bench_run.add_argument("--out", required=True, metavar="NEW_DIRECTORY")
+ bench_run.add_argument("--credential-env", default="STRATA_API_KEY")
+ bench_run.add_argument("--telemetry-credential-env", default=None)
+ bench_run.add_argument("--output", choices=("human", "json"), default="human")
+ bench_cancel = bench_sp.add_parser("cancel", help="stop the exact active saved-profile benchmark")
+ bench_cancel.add_argument("--profile", required=True, help="saved serving profile")
+ bench_cancel.add_argument("--path", required=True, help="absolute run directory or results.json")
+ bench_cancel.add_argument("--output", choices=("human", "json"), default="human")
+ bench_report = bench_sp.add_parser("report", help="summarize an existing benchmark report")
+ bench_report.add_argument("path")
+ bench_report.add_argument("--output", choices=("human", "json", "markdown"), default="human")
+ bench_report.add_argument("--out", metavar="NEW_FILE", help="write Markdown to a new file")
+ bench_compare = bench_sp.add_parser("compare", help="compare two saved runs with workload checks")
+ bench_compare.add_argument("baseline")
+ bench_compare.add_argument("candidate")
+ bench_compare.add_argument("--output", choices=("human", "json", "markdown"), default="human")
+ bench_compare.add_argument("--out", metavar="NEW_FILE", help="write Markdown to a new file")
+ timeskip = sp.add_parser(
+ "timeskip", help="retain a good result, try a bounded improvement, check it and decide")
+ timeskip_sp = timeskip.add_subparsers(dest="timeskip_command", required=True)
+
+ ts_run = timeskip_sp.add_parser("run", help="checkpoint, attempt a revision, check it and decide")
+ ts_run.add_argument("--workspace", required=True,
+ help="the directory holding the work (and, optionally, .strata/checks.json)")
+ ts_run.add_argument("--prompt", required=True, help="what the revision should achieve")
+ ts_run.add_argument("--attempts", type=int, default=2,
+ help="bounded revision attempts (0 = checkpoint and check the baseline only); "
+ "the specification's default is two")
+ ts_run.add_argument("--revise-command", default=None,
+ help="the command that performs ONE revision attempt. It runs with the "
+ "candidate directory as its working directory, receives the prompt in "
+ "STRATA_TIMESKIP_PROMPT and the attempt number in "
+ "STRATA_TIMESKIP_ATTEMPT, and must not touch the workspace. Without it "
+ "no revision is attempted, which yields an inconclusive run rather than "
+ "a fabricated improvement.")
+ ts_run.add_argument("--state-dir", default=None,
+ help="where runs are recorded (default: $STRATA_TIMESKIP_DIR or "
+ "$XDG_STATE_HOME/strata/time-skip)")
+ ts_run.add_argument("--output", choices=("human", "json"), default="human")
+
+ ts_status = timeskip_sp.add_parser("status", help="read a run's durable state and evidence")
+ ts_status.add_argument("run_id")
+ ts_status.add_argument("--state-dir", default=None)
+ ts_status.add_argument("--output", choices=("human", "json"), default="human")
+
+ ts_list = timeskip_sp.add_parser("list", help="list recorded runs")
+ ts_list.add_argument("--state-dir", default=None)
+ ts_list.add_argument("--output", choices=("human", "json"), default="human")
+
+ ts_apply = timeskip_sp.add_parser(
+ "apply", help="apply the retained result, refusing if the destination changed")
+ ts_apply.add_argument("run_id")
+ ts_apply.add_argument("--workspace", default=None,
+ help="destination (default: the workspace the run recorded)")
+ ts_apply.add_argument("--dry-run", action="store_true",
+ help="report what would change without writing anything")
+ ts_apply.add_argument("--restore", action="store_true",
+ help="put the original back instead of applying the result")
+ ts_apply.add_argument("--state-dir", default=None)
+ ts_apply.add_argument("--output", choices=("human", "json"), default="human")
+
+ tune = sp.add_parser("tune", help="bounded engine-configuration search with retained evidence")
+ tune_sp = tune.add_subparsers(dest="tune_command", required=True)
+
+ tune_plan = tune_sp.add_parser("plan", help="show exactly what a sweep would search, and why not")
+ tune_plan.add_argument("--engine", required=True, help="the engine binary to interrogate and measure")
+ tune_plan.add_argument("--backend", required=True, choices=list(BACKENDS),
+ help="the backend family the engine package claims")
+ tune_plan.add_argument("--model", required=True, help="the model identifier the measurements belong to")
+ tune_plan.add_argument("--objective", choices=("generation", "prefill", "latency"),
+ default="generation")
+ tune_plan.add_argument("--trials", type=int, default=16, help="the bounded short sweep (default 16)")
+ tune_plan.add_argument("--time", dest="total_time", type=float, default=1800.0,
+ help="displayed total-time bound in seconds")
+ tune_plan.add_argument("--repeats", type=int, default=3,
+ help="paired repeats per candidate (default 3, the specification's floor)")
+ tune_plan.add_argument("--hold", action="append", default=[],
+ help="hold a dimension constant instead of searching it (repeatable)")
+ tune_plan.add_argument("--output", choices=("human", "json"), default="human")
+
+ tune_run = tune_sp.add_parser(
+ "run", help="run a bounded sweep: measure the baseline and candidates, then report")
+ tune_run.add_argument("--engine", required=True, help="the engine binary to measure")
+ tune_run.add_argument("--backend", required=True, choices=list(BACKENDS))
+ tune_run.add_argument("--model", required=True, help="the model the measurements belong to")
+ tune_run.add_argument("--objective", choices=("generation", "prefill", "latency"),
+ default="generation")
+ tune_run.add_argument("--trials", type=int, default=16,
+ help="bounded number of candidate configurations (default 16)")
+ tune_run.add_argument("--time", dest="total_time", type=float, default=1800.0,
+ help="displayed total-time bound in seconds")
+ tune_run.add_argument("--repeats", type=int, default=3,
+ help="paired repeats per candidate (default 3, the specification's floor)")
+ tune_run.add_argument("--prompt-tokens", type=int, default=512,
+ help="the workload's prompt length; fixed for the whole sweep")
+ tune_run.add_argument("--max-new", type=int, default=128,
+ help="the workload's output length; fixed for the whole sweep")
+ tune_run.add_argument("--mode", choices=("protocol", "api"), default="protocol",
+ help="protocol measures the engine's own serve protocol (cheap, for every "
+ "candidate); api drives the real HTTP API the agent uses (the "
+ "confirmation, and the only mode that reflects a user's wait)")
+ tune_run.add_argument("--api-prompt", default="In one short sentence, what is a hash table?",
+ help="the prompt the api mode sends")
+ tune_run.add_argument("--api-expect", default=None,
+ help="a regular expression the answer must match for the run to count as "
+ "correct; without it correctness is not checked")
+ tune_run.add_argument("--api-port", type=int, default=8123)
+ tune_run.add_argument("--config", default=None,
+ help="the run configuration the api mode starts the worker with")
+ tune_run.add_argument("--boot-timeout", type=float, default=600.0,
+ help="how long one candidate may take to become ready")
+ tune_run.add_argument("--request-timeout", type=float, default=600.0,
+ help="how long one measured request may take")
+ tune_run.add_argument("--model-path", default=None,
+ help="the model's file, so the sweep's identity is a content digest rather "
+ "than a name. Without it the record is incomparable to everything, "
+ "which is safer than being falsely comparable.")
+ tune_run.add_argument("--context", type=int, default=None,
+ help="the context the measurements were taken at")
+ tune_run.add_argument("--full-digests", action="store_true",
+ help="hash the model and engine completely instead of sampling; slower but "
+ "the strongest identity")
+ tune_run.add_argument("--hold", action="append", default=[],
+ help="hold a dimension constant instead of searching it (repeatable)")
+ tune_run.add_argument("--state-dir", default=None)
+ tune_run.add_argument("--output", choices=("human", "json"), default="human")
+
+ tune_apply = tune_sp.add_parser(
+ "apply", help="apply a reviewed recommendation, after verifying the candidate runs")
+ tune_apply.add_argument("job_id", help="the completed sweep whose recommendation to apply")
+ tune_apply.add_argument("--config", default=None,
+ help="the run configuration to change (strata-<model>.json)")
+ tune_apply.add_argument("--model-path", default=None,
+ help="the model file, to re-check the identity before writing")
+ tune_apply.add_argument("--context", type=int, default=None)
+ tune_apply.add_argument("--state-dir", default=None)
+ tune_apply.add_argument("--output", choices=("human", "json"), default="human")
+
+ tune_rollback = tune_sp.add_parser("rollback", help="restore the configuration before an apply")
+ tune_rollback.add_argument("application_id")
+ tune_rollback.add_argument("--state-dir", default=None)
+ tune_rollback.add_argument("--output", choices=("human", "json"), default="human")
+
+ tune_status = tune_sp.add_parser("status", help="read a job's durable state and report")
+ tune_status.add_argument("job_id")
+ tune_status.add_argument("--state-dir", default=None)
+ tune_status.add_argument("--output", choices=("human", "json"), default="human")
+
+ tune_list = tune_sp.add_parser("list", help="list recorded jobs")
+ tune_list.add_argument("--state-dir", default=None)
+ tune_list.add_argument("--output", choices=("human", "json"), default="human")
+
+ monitor_commands.add_status(sp)
+ monitor_commands.add_monitor(sp)
+ monitor_commands.add_logs(sp)
+ monitor_commands.add_connections(sp)
+ code = sp.add_parser("code", help="coding client for the shared Desktop harness")
+ code.add_argument("--workspace")
+ code.add_argument("--resume")
+ code.add_argument("--quiet", action="store_true", help="suppress human informational output")
+ code_sp = code.add_subparsers(dest="code_command")
+ code_run = code_sp.add_parser("run", help="scripted harness turn (requires the shared harness component)")
+ code_run.add_argument("--prompt-file", required=True)
+ code_run.add_argument("--policy", required=True)
+ code_run.add_argument("--output", choices=("jsonl",), default="jsonl")
+ code_run.add_argument("--quiet", action="store_true", default=argparse.SUPPRESS,
+ help="suppress human informational output")
+ code_sessions = code_sp.add_parser("sessions", help="shared harness sessions")
+ code_sessions.add_argument("action", choices=("list",))
+ code_sessions.add_argument("--output", choices=("human", "json"), default="human")
+ for one_shot in (profile_create, profile_list, profile_show, profile_validate, profile_set,
+ profile_source, profile_edit, profile_history, profile_rollback, doctor,
+ components_verify, models_list, models_inspect, models_import, calibrate,
+ runtime_start, runtime_status, runtime_verify, runtime_stop, runtime_restart,
+ *ops_items, bench_run, bench_report, bench_compare, code_sessions):
+ one_shot.add_argument("--json", action="store_true", help="alias for --output json")
+ one_shot.add_argument("--quiet", action="store_true", default=argparse.SUPPRESS,
+ help="suppress human informational output")
+ return ap
+
+
+def _error(message: str, code: int, machine: bool = False) -> int:
+ if machine:
+ print(json.dumps({"schema_version": 1, "ok": False, "error": {"code": code, "message": message}}))
+ else:
+ print(f"strata: {message}", file=sys.stderr)
+ return code
+
+
+def _success(payload: dict, *, machine: bool, human: str | None = None) -> int:
+ if machine:
+ print(json.dumps({"schema_version": 1, "ok": True, **payload}, ensure_ascii=False, allow_nan=False))
+ elif human is not None:
+ print(human)
+ else:
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
+ return 0
+
+
+def _source(ref: str) -> tuple[Path, dict | None, str | None, dict]:
+ path, saved, revision = profiles.resolve(ref)
+ return path, saved, revision, profiles.read_run_config(path)
+
+
+def _models(a: argparse.Namespace) -> int:
+ from strata_control import models
+ if a.models_command == "import":
+ result = models.plan_import(a.path)
+ if result["issues"]:
+ if a.output == "json":
+ print(json.dumps({"schema_version": 1, "ok": False, "plan": result},
+ ensure_ascii=False, allow_nan=False))
+ else:
+ print(f"GGUF file set is incomplete or invalid: {', '.join(result['issues'])}", file=sys.stderr)
+ return 5
+ return _success({"plan": result}, machine=a.output == "json",
+ human=f"{result['file_count']} GGUF file(s): {result['file_set_status']}\n"
+ f"Adoption: {result['adoption_status']}\nNo files changed")
+ if a.models_command == "list":
+ if a.served:
+ if a.install_dir:
+ return _error("--install-dir applies only to local installed models", 2, a.output == "json")
+ from strata_cli import connections
+ resolved = connections.resolve(url=a.url, connection=a.connection,
+ credential_env=a.credential_env, timeout=a.timeout)
+ endpoint = Endpoint(resolved["url"], os.environ.get(resolved["credential_env"]),
+ resolved["timeout_s"], resolved["prefix"])
+ snapshot = endpoint.snapshot()
+ model = snapshot["model"]
+ rows = ([{"id": model["id"], "loaded": model["loaded"],
+ "instance_id": snapshot["instance"]["id"], "execution_compatibility": "unverified"}]
+ if model["id"] else [])
+ result = {"scope": "served_current_instance", "server": endpoint.base_url,
+ "models": rows, "model_count": len(rows),
+ "note": "current instance only; not an installed-model inventory"}
+ return _success(result, machine=a.output == "json",
+ human="\n".join(f"{row['id']} " +
+ ("loaded" if row["loaded"] is True else
+ "unloaded" if row["loaded"] is False else "load state unknown")
+ for row in rows) or "No model ID reported by this server")
+ if a.url or a.connection or a.credential_env or a.timeout is not None:
+ return _error("connection options require --served", 2, a.output == "json")
+ result = models.list_installed(a.install_dir)
+ lines = [f"{item['id']} {item['component_status']} "
+ f"{item.get('name', item.get('error', ''))}" for item in result["models"]]
+ return _success(result, machine=a.output == "json", human="\n".join(lines) or "No local model run configs")
+ result = models.inspect(a.model_id, a.install_dir)
+ item = result["model"]
+ return _success(result, machine=a.output == "json",
+ human=f"{item['id']}: {item['component_status']}; engine compatibility unverified\n"
+ f"Config: {item['source_config']}\n"
+ f"Components: {len(result['components']['components'])}, "
+ f"issues: {len(result['components']['issues'])}")
+
+
+def _redact_argv(args: list[str]) -> list[str]:
+ out = []
+ conceal_next = False
+ for item in args:
+ if conceal_next:
+ out.append("<redacted>")
+ conceal_next = False
+ continue
+ if item.startswith("-") and any(word in item.lower() for word in ("key", "token", "secret", "password", "credential")):
+ if "=" in item:
+ out.append(item.partition("=")[0] + "=<redacted>")
+ else:
+ out.append(item)
+ conceal_next = True
+ else:
+ out.append(item)
+ return out
+
+
+def _effective(cfg: dict, saved: dict | None, cli: argparse.Namespace | None = None) -> tuple[dict, dict]:
+ overrides = saved["overrides"] if saved else {}
+ values = {}
+ origins = {}
+ for key, default in (("host", "127.0.0.1"), ("port", 8095), ("parallel", None),
+ ("batch_groups", None), ("max_queue", None), ("queue_timeout", None),
+ ("offline", False), ("batch_telemetry", False)):
+ explicit = getattr(cli, key, None) if cli is not None else None
+ if key == "offline" and explicit is False:
+ explicit = None
+ if explicit is not None:
+ value, origin = explicit, "command"
+ elif key in overrides:
+ value, origin = overrides[key], "saved_profile"
+ elif key in cfg:
+ value, origin = cfg[key], "run_config"
+ elif key == "batch_telemetry" and "STRATA_BATCH_TELEMETRY" in os.environ:
+ value, origin = os.environ["STRATA_BATCH_TELEMETRY"] == "1", "environment"
+ else:
+ value, origin = default, "default"
+ values[key], origins[key] = value, origin
+ profiles.validate_overrides({key: value for key, value in values.items() if key in
+ ("host", "port", "parallel", "batch_groups", "max_queue", "queue_timeout",
+ "offline", "batch_telemetry")
+ and value is not None})
+ if values["queue_timeout"] is not None and values["max_queue"] is None:
+ raise ProfileError("queue_timeout requires max_queue to bound pending calls")
+ if values["parallel"] is not None and any(flag in cfg["args"] for flag in ("--batch", "--slots")):
+ if origins["parallel"] != "run_config":
+ raise ProfileError("parallel override conflicts with --batch/--slots in run config args")
+ if values["batch_groups"] is not None and "--batch-groups" in cfg["args"]:
+ raise ProfileError("batch_groups override conflicts with --batch-groups in run config args")
+ if values["offline"] and (cfg.get("mcp_servers") or cfg.get("before_load")):
+ raise ProfileError("offline serving requires MCP servers and before_load to be absent")
+ return values, origins
+
+
+def _launch_plan(ref: str, cli: argparse.Namespace | None = None) -> tuple[dict, list[str]]:
+ path, saved, revision, cfg = _source(ref)
+ values, origins = _effective(cfg, saved, cli)
+ host = values["host"]
+ from serve.server import api_key_of, key_list
+ try:
+ has_key = bool(key_list(api_key_of(os.environ.get("STRATA_API_KEY") or cfg.get("api_key", ""))))
+ except ValueError:
+ raise ProfileError("the inference API key is invalid", 5) from None
+ if host not in ("127.0.0.1", "localhost", "::1") and not has_key:
+ raise ProfileError("non-loopback serving requires an API key in the run config or STRATA_API_KEY")
+ server_args = ["--engine", "strata", "--config", str(path), "--host", str(host),
+ "--port", str(values["port"])]
+ if cli is not None:
+ server_args += ["--shutdown-timeout", str(cli.shutdown_timeout)]
+ for key, flag in (("parallel", "--parallel"), ("batch_groups", "--batch-groups"),
+ ("max_queue", "--max-queue"), ("queue_timeout", "--queue-timeout")):
+ if values[key] is not None and origins[key] != "run_config":
+ server_args += [flag, str(values[key])]
+ if values["offline"]:
+ server_args.append("--offline")
+ if origins["batch_telemetry"] not in ("run_config", "default"):
+ server_args.append("--batch-telemetry" if values["batch_telemetry"] else "--no-batch-telemetry")
+ ready_path = None
+ if cli is not None and cli.ready_file:
+ from serve.ready import preflight as ready_preflight
+ ready_path = str(ready_preflight(cli.ready_file))
+ server_args += ["--ready-file", ready_path]
+ effective_cfg = {**cfg, "args": list(cfg["args"])}
+ if values["parallel"] is not None:
+ effective_cfg["parallel"] = values["parallel"]
+ if values["batch_groups"] is not None:
+ effective_cfg["args"] += ["--batch-groups", str(values["batch_groups"])]
+ from serve.server import engine_args
+ notes = io.StringIO()
+ with contextlib.redirect_stdout(notes):
+ engine_argv = engine_args(effective_cfg)
+ plan = {"profile": saved["id"] if saved else None, "profile_revision": revision,
+ "source_config": str(path), "model_name": cfg.get("model_name"),
+ "effective": values, "origin": origins, "server_argv": server_args,
+ "ready_file": ready_path,
+ "engine_exe": cfg["exe"], "engine_argv": _redact_argv(engine_argv),
+ "notes": [line for line in notes.getvalue().splitlines() if line]}
+ return plan, server_args
+
+
+def _serve_error(a: argparse.Namespace, message: str, code: int = 2) -> int:
+ if a.output == "jsonl":
+ print(json.dumps({"schema_version": 1, "event": "failed", "at": time.time(),
+ "exit_code": code, "error": {"message": message}},
+ ensure_ascii=False, allow_nan=False))
+ return code
+ return _error(message, code, a.output == "json")
+
+
+def _serve_jsonl(server_main, args: list[str], plan: dict, *, quiet: bool = False) -> int:
+ output = sys.stdout
+ output_open = True
+ ready = False
+ stopped = False
+ fields = {"starting": ("profile", "model_id", "pid"),
+ "ready": ("instance_id", "pid", "api_url", "bound_host", "bound_port",
+ "model_id", "model_state", "api_state"),
+ "stopping": ("instance_id", "reason"),
+ "draining": ("instance_id", "pending_requests", "deadline_s"),
+ "stopped": ("instance_id", "reason", "drained", "cancelled_requests", "exit_code"),
+ "failed": ("phase", "exit_code")}
+
+ def emit(kind: str, values: dict) -> None:
+ nonlocal output_open, ready, stopped
+ if kind not in fields:
+ return
+ ready |= kind == "ready"
+ stopped |= kind == "stopped"
+ if not output_open:
+ return
+ record = {"schema_version": 1, "event": kind, "at": time.time(),
+ **{key: values[key] for key in fields[kind] if key in values}}
+ try:
+ output.write(json.dumps(record, ensure_ascii=False, allow_nan=False) + "\n")
+ output.flush()
+ except BrokenPipeError:
+ # Losing a log consumer must not kill an owned inference service.
+ output_open = False
+
+ emit("starting", {"profile": plan["profile"], "model_id": plan["model_name"], "pid": os.getpid()})
+ try:
+ with (open(os.devnull, "w", encoding="utf-8") if quiet else
+ contextlib.nullcontext(sys.stderr)) as human_output:
+ with contextlib.redirect_stdout(human_output):
+ result = server_main(args, lifecycle_event=emit, interrupt_exit_code=130)
+ except SystemExit as exc:
+ result = exc.code if type(exc.code) is int else 6
+ if result == 0 and not ready:
+ result = 6
+ if not isinstance(exc.code, int):
+ print("strata: foreground service startup failed; inspect the profile and component checks",
+ file=sys.stderr)
+ emit("failed", {"phase": "startup" if not ready else "running", "exit_code": result})
+ return result
+ except KeyboardInterrupt:
+ emit("failed", {"phase": "startup" if not ready else "running", "exit_code": 130})
+ return 130
+ except Exception as exc:
+ print(f"strata: foreground service failed ({type(exc).__name__})", file=sys.stderr)
+ emit("failed", {"phase": "startup" if not ready else "running", "exit_code": 6})
+ return 6
+ if not ready:
+ emit("failed", {"phase": "startup", "exit_code": result or 6})
+ return result or 6
+ if not stopped:
+ emit("failed" if result else "stopped",
+ {"phase": "running", "exit_code": result,
+ "reason": "normal", "drained": result == 0})
+ return result
+
+
+def _serve_foreground(server_main, args: list[str], plan: dict, *, output: str, quiet: bool) -> int:
+ if output == "jsonl":
+ return _serve_jsonl(server_main, args, plan, quiet=quiet)
+ if quiet:
+ with open(os.devnull, "w", encoding="utf-8") as human_output:
+ with contextlib.redirect_stdout(human_output):
+ result = server_main(args, interrupt_exit_code=130)
+ if result == 8:
+ print("strata: shutdown drain deadline expired; owned requests were cancelled", file=sys.stderr)
+ elif result:
+ print(f"strata: foreground service exited with code {result}", file=sys.stderr)
+ return result
+ return server_main(args, interrupt_exit_code=130)
+
+
+def _serve(a: argparse.Namespace) -> int:
+ if a.output == "json" and not a.plan:
+ return _serve_error(a, "--output json requires --plan; use --output jsonl for foreground events")
+ if a.output == "jsonl" and a.plan:
+ return _serve_error(a, "--plan uses --output human or json; jsonl is for foreground events")
+ if a.port is not None and not 0 <= a.port <= 65535:
+ return _serve_error(a, "--port must be in 0..65535")
+ if a.parallel is not None and not 1 <= a.parallel <= 1024:
+ return _serve_error(a, "--parallel must be in 1..1024")
+ if a.max_queue is not None and not 0 <= a.max_queue <= 4096:
+ return _serve_error(a, "--max-queue must be in 0..4096")
+ if a.queue_timeout is not None and (not math.isfinite(a.queue_timeout)
+ or not 0.1 <= a.queue_timeout <= 600):
+ return _serve_error(a, "--queue-timeout must be finite seconds in 0.1..600")
+ if not 0 <= a.shutdown_timeout <= 300:
+ return _serve_error(a, "--shutdown-timeout must be in 0..300 seconds")
+ try:
+ if a.batch_groups is not None:
+ profiles.validate_overrides({"batch_groups": a.batch_groups if a.batch_groups == "auto"
+ else int(a.batch_groups) if a.batch_groups.isdecimal() else a.batch_groups})
+ plan, args = _launch_plan(a.config, a)
+ except ValueError as exc:
+ if a.output == "jsonl":
+ return _serve_error(a, str(exc), getattr(exc, "exit_code", 2))
+ raise
+ if a.plan:
+ return _success({"plan": plan}, machine=a.output == "json")
+ from serve.server import main as server_main
+ if os.name != "posix":
+ return _serve_foreground(server_main, args, plan, output=a.output, quiet=a.quiet)
+ from strata_control import runtime
+ try:
+ lease = runtime.acquire_activity_lease(shared=True)
+ except ValueError as exc:
+ if a.output == "jsonl":
+ return _serve_error(a, str(exc), getattr(exc, "exit_code", 6))
+ raise
+ try:
+ return _serve_foreground(server_main, args, plan, output=a.output, quiet=a.quiet)
+ finally:
+ os.close(lease)
+
+
+def _profile_command(a: argparse.Namespace) -> int:
+ machine = a.output == "json"
+ if a.profile_command == "create":
+ saved, revision = profiles.create(a.name, a.from_config)
+ return _success({"profile": saved, "revision": revision}, machine=machine,
+ human=f"Saved profile {a.name} at revision {revision}")
+ if a.profile_command == "list":
+ items = profiles.list_profiles()
+ human = "\n".join(f"{item['id']} {item.get('revision', item.get('error'))}" for item in items) or "No saved profiles"
+ return _success({"profiles": items}, machine=machine, human=human)
+ saved, revision = profiles.load(a.name)
+ if a.profile_command == "use-config":
+ proposed, previous = profiles.propose_source(a.name, a.from_config)
+ if previous != revision:
+ raise ProfileError("profile changed during source preview; plan it again", 6)
+ if a.if_revision is not None and a.if_revision != previous:
+ raise ProfileError("profile changed after preview; plan it again before selecting a config", 6)
+ change = {"before": saved["source_config"], "after": proposed["source_config"]}
+ if a.plan:
+ return _success({"profile": a.name, "revision": previous, "source_config": change,
+ "model_name": profiles.read_run_config(Path(proposed["source_config"])).get("model_name"),
+ "would_save": change["before"] != change["after"]}, machine=machine,
+ human=f"Config: {change['before']} -> {change['after']}")
+ saved, revision = profiles.save(a.name, proposed, expected_revision=previous)
+ return _success({"profile": saved, "previous_revision": previous, "revision": revision,
+ "source_config": change}, machine=machine,
+ human=f"Saved source config for {a.name}: {change['before']} -> {change['after']}; "
+ "running instance unchanged")
+ if a.profile_command == "set":
+ proposed, previous = profiles.propose_values(a.name, a.assignments)
+ changes = {key: {"before": saved["overrides"].get(key), "after": value}
+ for key, value in proposed["overrides"].items() if saved["overrides"].get(key) != value}
+ if a.plan:
+ return _success({"profile": a.name, "revision": previous, "changes": changes,
+ "would_save": bool(changes)}, machine=machine)
+ saved, revision = profiles.save(a.name, proposed, expected_revision=previous)
+ return _success({"profile": saved, "previous_revision": previous, "revision": revision,
+ "changes": changes}, machine=machine,
+ human=f"Saved profile {a.name}: {previous} -> {revision}\n" +
+ "\n".join(f" {key}: {value['before']!r} -> {value['after']!r}" for key, value in changes.items()))
+ if a.profile_command == "edit":
+ previous_value = saved
+ saved, previous, revision = profiles.edit(a.name)
+ changes = {key: {"before": previous_value.get(key), "after": saved.get(key)}
+ for key in saved if previous_value.get(key) != saved.get(key)}
+ return _success({"profile": saved, "previous_revision": previous, "revision": revision,
+ "changes": changes}, machine=machine,
+ human=f"Saved profile {a.name}: {previous} -> {revision}")
+ if a.profile_command == "history":
+ entries = profiles.history(a.name)
+ return _success({"profile": a.name, "history": entries}, machine=machine,
+ human="\n".join(f"{item['revision']} {'current' if item.get('current') else 'saved'}"
+ for item in entries))
+ if a.profile_command == "rollback":
+ saved, previous, revision = profiles.rollback(a.name, a.to)
+ return _success({"profile": saved, "previous_revision": previous, "revision": revision}, machine=machine,
+ human=f"Restored profile {a.name}: {previous} -> {revision}; running instances are unchanged")
+ result = {"profile": saved, "revision": revision}
+ if a.profile_command == "validate" or a.effective:
+ plan, _ = _launch_plan(a.name)
+ result["plan"] = plan
+ return _success(result, machine=machine, human=(f"Profile {a.name} is valid at revision {revision}"
+ if a.profile_command == "validate" else None))
+
+
+def _doctor(a: argparse.Namespace) -> int:
+ machine = a.output == "json"
+ ref = getattr(a, "profile", None)
+ path, saved, _ = profiles.resolve(ref) if ref else (None, None, None)
+ report = inspect_components(path, profile_id=saved["id"] if saved else None,
+ live=getattr(a, "live", False))
+ if machine:
+ print(json.dumps({"schema_version": 1, "ok": report["ok"], "report": report},
+ ensure_ascii=False, allow_nan=False))
+ else:
+ for item in report["components"]:
+ detail = item.get("path") or item.get("reason") or \
+ (f"version {item['version']}" if item.get("version") else "")
+ print(f"{item['status']:>16} {item['name']} {detail}")
+ for issue in report["issues"]:
+ print(f"{issue['severity']}: {issue['code']}: {issue['message']}")
+ live_probe = report["live_gpu_probe"]
+ if live_probe is not None:
+ print(f"Live GPU probe: {live_probe['status']}")
+ for card in live_probe["cards"]:
+ print(f" GPU {card['index']}: {card['name']} | {card['memory_mib']} MiB | "
+ f"driver {card['driver_version']} | {card['uuid']}")
+ return 0 if report["ok"] else 5
+
+
+def _direct_calibration(ref: str, kind: str, report_path: Path, action) -> tuple[str | None, dict]:
+ """Saved profiles share the local journal; explicit run-config paths keep legacy behavior."""
+ _, saved, revision = profiles.resolve(ref)
+ if saved is None:
+ return None, action()
+ from strata_control import journal
+ return journal.run_direct(saved["id"], kind, revision,
+ {"report_path": str(report_path.expanduser().resolve()), "exclusive_ack": True},
+ action)
+
+
+def _calibration(a: argparse.Namespace) -> int:
+ from strata_control import calibration
+ machine = a.output == "json"
+ if (a.out and not a.measure) or (a.exclusive and not (a.measure or a.apply_result or a.rollback_result)):
+ return _error("--out is only for --measure; --exclusive is only for --measure, --apply-result "
+ "or --rollback-result", 2, machine)
+ if a.measure:
+ if not a.exclusive or not a.out:
+ return _error("--measure requires --exclusive and --out REPORT.json", 2, machine)
+ with contextlib.redirect_stdout(sys.stderr):
+ operation_id, result = _direct_calibration(a.profile, "engine.calibrate.measure", Path(a.out),
+ lambda: {"ok": True, "report_path": str(Path(a.out).resolve()),
+ "report": calibration.measure(a.profile, Path(a.out), exclusive_ack=True,
+ say=lambda message: print(message, file=sys.stderr))})
+ return _success({"report": result["report"], "path": str(Path(a.out).resolve()),
+ **({"operation_id": operation_id} if operation_id else {})}, machine=machine,
+ human=f"Calibration measured; review {Path(a.out).resolve()} before applying")
+ if a.review_result:
+ result = calibration.review(a.profile, Path(a.review_result))
+ result["before_args"] = _redact_argv(result["before_args"])
+ result["after_args"] = _redact_argv(result["after_args"])
+ if machine:
+ print(json.dumps({"schema_version": 1, "ok": result["applicable"], "review": result},
+ ensure_ascii=False, allow_nan=False))
+ else:
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+ return 0 if result["applicable"] else 6
+ if a.apply_result:
+ if not a.exclusive:
+ return _error("--apply-result requires --exclusive", 2, machine)
+ with contextlib.redirect_stdout(sys.stderr):
+ operation_id, result = _direct_calibration(a.profile, "engine.calibrate.apply", Path(a.apply_result),
+ lambda: {"ok": True, "application": calibration.apply_result(
+ a.profile, Path(a.apply_result), exclusive_ack=True)})
+ return _success({"application": result["application"],
+ **({"operation_id": operation_id} if operation_id else {})}, machine=machine,
+ human=f"Calibration applied; rollback evidence: {result['application']['application_record']}")
+ if a.review_rollback:
+ result = calibration.review_rollback(a.profile, Path(a.review_rollback))
+ if machine:
+ print(json.dumps({"schema_version": 1, "ok": result["applicable"], "rollback_review": result},
+ ensure_ascii=False, allow_nan=False))
+ else:
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+ return 0 if result["applicable"] else 6
+ if a.rollback_result:
+ if not a.exclusive:
+ return _error("--rollback-result requires --exclusive", 2, machine)
+ with contextlib.redirect_stdout(sys.stderr):
+ operation_id, result = _direct_calibration(a.profile, "engine.calibrate.rollback",
+ Path(a.rollback_result), lambda: {"ok": True, "rollback": calibration.rollback_result(
+ a.profile, Path(a.rollback_result), exclusive_ack=True)})
+ return _success({"rollback": result["rollback"],
+ **({"operation_id": operation_id} if operation_id else {})}, machine=machine,
+ human="Previous calibration configuration restored; restart the model to use it")
+ plan = calibration.preview(a.profile)
+ components = plan["component_preflight"]
+ if machine:
+ print(json.dumps({"schema_version": 1, "ok": components["ok"], "plan": plan},
+ ensure_ascii=False, allow_nan=False))
+ else:
+ print(f"Calibration plan for {plan['model_name'] or Path(plan['source_config']).name}")
+ print(f"Run config: {plan['source_config']}")
+ print("Measure engine settings for roughly 15–30 minutes with exclusive GPU access.")
+ print("This preview did not start the engine or change configuration.")
+ if not components["ok"]:
+ print("Required components are missing; run strata doctor --profile first.")
+ return 0 if components["ok"] else 5
+
+
+def _bench(a: argparse.Namespace) -> int:
+ from strata_cli import bench
+ machine = a.output == "json"
+ if a.bench_command in ("report", "compare") and a.out and a.output != "markdown":
+ return _error("--out requires --output markdown", 2, machine)
+ if a.bench_command == "report":
+ report = bench.load(Path(a.path))
+ result = bench.summary(report)
+ if a.output == "markdown":
+ rendered = bench.markdown_report(report)
+ if a.out:
+ bench.write_markdown(Path(a.out), rendered)
+ print(f"Markdown report: {Path(a.out).resolve()}")
+ else:
+ print(rendered, end="")
+ return 0
+ return _success({"summary": result}, machine=machine,
+ human=bench.format_summary(result))
+ if a.bench_command == "compare":
+ result = bench.compare(bench.load(Path(a.baseline)), bench.load(Path(a.candidate)))
+ if a.output == "markdown":
+ rendered = bench.markdown_comparison(result)
+ if a.out:
+ bench.write_markdown(Path(a.out), rendered)
+ print(f"Markdown comparison: {Path(a.out).resolve()}")
+ else:
+ print(rendered, end="")
+ return 0
+ return _success({"comparison": result}, machine=machine,
+ human=bench.format_comparison(result))
+ if a.bench_command == "cancel":
+ from strata_control import benchmarking, profiles
+ if not Path(a.path).is_absolute():
+ return _error("benchmark cancel path must be absolute", 2, machine)
+ profiles.load(a.profile)
+ result = benchmarking.request_cancel(a.profile, Path(a.path))
+ return _success(result, machine=machine,
+ human="Cancellation requested; check the saved report for the final outcome.")
+ if not a.credential_env.isidentifier() or (a.telemetry_credential_env and
+ not a.telemetry_credential_env.isidentifier()):
+ return _error("credential options must name environment variables", 2, machine)
+ maximum = 64 if a.suite == "parallel-overload-v1" else 16
+ if not 1 <= a.concurrency <= maximum or not 1 <= a.repeat <= 5 or not 1 <= a.request_timeout <= 600:
+ return _error(f"concurrency must be 1..{maximum}, repeat 1..5 and request timeout 1..600 seconds", 2,
+ machine)
+ if a.require_managed_match and not a.profile:
+ return _error("--require-managed-match needs a saved --profile", 2, machine)
+ profile_identity = None
+ if a.profile:
+ path, saved, revision, cfg = _source(a.profile)
+ if a.require_managed_match and saved is None:
+ return _error("--require-managed-match needs a saved profile name", 2, machine)
+ plan, _ = _launch_plan(a.profile)
+ host = plan["effective"]["host"]
+ host = "127.0.0.1" if host in ("0.0.0.0", "::") else host
+ authority = f"[{host}]" if ":" in host and not host.startswith("[") else host
+ url = f"http://{authority}:{plan['effective']['port']}"
+ import hashlib
+ profile_identity = {"profile": saved["id"] if saved else None, "revision": revision,
+ "source_config": str(path), "source_sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
+ "model_name": cfg.get("model_name"), "gpu": cfg.get("gpu")}
+ else:
+ url = a.url
+ key = os.environ.get(a.credential_env)
+ endpoint = Endpoint(url, key, timeout=10)
+ telemetry = Endpoint(url, os.environ.get(a.telemetry_credential_env) if a.telemetry_credential_env else key,
+ timeout=3)
+ from strata_control.benchmarking import benchmark_lease
+ lease = benchmark_lease(saved["id"], Path(a.out)) if a.profile and saved else contextlib.nullcontext()
+ with lease, contextlib.redirect_stdout(sys.stderr):
+ report = bench.run(endpoint, telemetry, Path(a.out), suite=a.suite,
+ concurrency=a.concurrency, repeat=a.repeat,
+ request_timeout=a.request_timeout, profile_identity=profile_identity,
+ condition=a.condition, require_managed_match=a.require_managed_match)
+ compact = bench.summary(report)
+ if machine:
+ print(json.dumps({"schema_version": 1, "ok": report["successful"],
+ "path": str((Path(a.out) / "results.json").resolve()), "summary": compact},
+ ensure_ascii=False, allow_nan=False))
+ else:
+ print(bench.format_summary(compact))
+ print(f"Evidence: {Path(a.out).resolve() / 'results.json'}")
+ return 0 if report["successful"] else 6
+
+
+def _runtime(a: argparse.Namespace) -> int:
+ from strata_control import management
+ machine = a.output == "json"
+ result = management.runtime_action(
+ a.runtime_command, a.profile, plan=getattr(a, "plan", False),
+ wait=getattr(a, "wait", 300),
+ shutdown_timeout=getattr(a, "shutdown_timeout", 30),
+ startup_wait=getattr(a, "startup_wait", 300), load=getattr(a, "load", False),
+ if_profile_revision=getattr(a, "if_profile_revision", None),
+ if_owner_id=getattr(a, "if_owner_id", None),
+ if_instance_id=getattr(a, "if_instance_id", None),
+ allow_source_switch=getattr(a, "allow_source_switch", False),
+ allow_source_migration=getattr(a, "allow_source_migration", False),
+ if_source_sha256=getattr(a, "if_source_sha256", None))
+ if a.runtime_command in ("start", "stop", "verify") and a.plan and result.get("ok"):
+ return _success({"plan": result["plan"]}, machine=machine)
+ if machine:
+ print(json.dumps({"schema_version": 1, **result}, ensure_ascii=False, allow_nan=False))
+ else:
+ readiness_label = {"generation_ready": "generation checked",
+ "unloaded": "API verified; model unloaded"}.get(result.get("readiness_state"))
+ print(f"{a.profile}: {result.get('state', 'unknown')}" +
+ (f" instance {result['instance_id']}" if result.get("instance_id") else "") +
+ (f" {result['api_url']}" if result.get("api_url") else "") +
+ (" config/launch verified" if result.get("launch_attested") else "") +
+ (f" {readiness_label}" if readiness_label else "") +
+ (f" {result['error']}" if result.get("error") else ""))
+ return 0 if result["ok"] else result.get("exit_code", 6)
+
+
+def _ops(a: argparse.Namespace) -> int:
+ from strata_control import journal, recipes
+ machine = a.output == "json"
+ action = a.ops_command
+ if action == "init":
+ created = recipes.initialize(a.profile)
+ return _success({"profile": a.profile, "created": created}, machine=machine,
+ human=("Created: " + ", ".join(created) if created else "Recipes already initialized"))
+ if action == "list":
+ items = recipes.list_recipes(a.profile)
+ return _success({"profile": a.profile, "recipes": items}, machine=machine,
+ human="\n".join(f"{item['id']} {item.get('kind', item.get('error'))}" for item in items)
+ or "No recipes; use strata ops init --profile NAME")
+ if action == "runs":
+ runs = journal.list_runs(a.profile, limit=a.limit)
+ return _success({"profile": a.profile, "runs": runs}, machine=machine,
+ human="\n".join(f"{item['operation_id']} {item.get('state', item.get('error'))}"
+ for item in runs) or "No operation runs recorded")
+ if action == "result":
+ record = journal.load(a.profile, a.operation_id)
+ return _success({"record": record}, machine=machine)
+ if action == "create":
+ recipe, revision = recipes.create(a.profile, a.name, a.kind)
+ return _success({"recipe": recipe, "revision": revision}, machine=machine,
+ human=f"Created recipe {a.name} ({a.kind}) at {revision}")
+ if action == "show":
+ recipe, revision = recipes.load(a.profile, a.name)
+ return _success({"recipe": recipe, "revision": revision}, machine=machine)
+ if action == "edit":
+ recipe, previous, revision = recipes.edit(a.profile, a.name)
+ return _success({"recipe": recipe, "previous_revision": previous, "revision": revision},
+ machine=machine, human=f"Saved recipe {a.name}: {previous} -> {revision}")
+ if action == "set":
+ recipe, revision = recipes.propose_value(a.profile, a.name, a.assignment)
+ if a.plan:
+ current, _ = recipes.load(a.profile, a.name)
+ return _success({"recipe": recipe, "revision": revision, "would_save": recipe != current}, machine=machine)
+ saved, new_revision = recipes.save(a.profile, a.name, recipe, revision)
+ return _success({"recipe": saved, "previous_revision": revision, "revision": new_revision},
+ machine=machine, human=f"Saved recipe {a.name}: {revision} -> {new_revision}")
+ if action == "history":
+ entries = recipes.history(a.profile, a.name)
+ return _success({"profile": a.profile, "recipe": a.name, "history": entries}, machine=machine,
+ human="\n".join(f"{item['revision']} {'current' if item.get('current') else 'saved'}"
+ for item in entries))
+ if action == "rollback":
+ recipe, previous, revision = recipes.rollback(a.profile, a.name, a.to)
+ return _success({"recipe": recipe, "previous_revision": previous, "revision": revision},
+ machine=machine, human=f"Restored recipe {a.name}: {previous} -> {revision}")
+ if action == "plan":
+ plan = recipes.plan(a.profile, a.name)
+ ok = plan["operation"]["ok"]
+ if machine:
+ print(json.dumps({"schema_version": 1, "ok": ok, "plan": plan}, ensure_ascii=False, allow_nan=False))
+ else:
+ print(json.dumps(plan, indent=2, ensure_ascii=False))
+ return 0 if ok else plan["operation"].get("exit_code", 5)
+ recipe, _ = recipes.load(a.profile, a.name)
+ if a.exclusive and recipe["kind"] != "engine.calibrate.measure":
+ return _error("--exclusive applies only to calibration recipes", 2, machine)
+ with contextlib.redirect_stdout(sys.stderr):
+ operation = recipes.run(a.profile, a.name, exclusive_ack=a.exclusive,
+ expected_revision=a.if_revision,
+ expected_profile_revision=a.if_profile_revision,
+ expected_owner_id=a.if_owner_id,
+ expected_instance_id=a.if_instance_id,
+ expected_source_sha256=a.if_source_sha256)
+ ok = operation["result"]["ok"]
+ if machine:
+ print(json.dumps({"schema_version": 1, "ok": ok, "operation": operation},
+ ensure_ascii=False, allow_nan=False))
+ else:
+ print(json.dumps(operation, indent=2, ensure_ascii=False))
+ return 0 if ok else operation["result"].get("exit_code", 5)
+
+
+def _timeskip(a: argparse.Namespace) -> int:
+ """Real Time-skip: retain, revise, check, decide.
+
+ The decision is evidence-driven and the terminal states are honest: a run whose checks are
+ missing, unevaluable or unchanged ends inconclusive and asks the user to review, and cancelling
+ or crashing leaves the last complete checkpoint selected. No timer decides anything here.
+ """
+ from strata_control import time_skip
+
+ def state_root() -> Path:
+ if getattr(a, "state_dir", None):
+ return Path(a.state_dir)
+ env = os.environ.get("STRATA_TIMESKIP_DIR")
+ if env:
+ return Path(env)
+ base = os.environ.get("XDG_STATE_HOME") or str(Path.home() / ".local" / "state")
+ return Path(base) / "strata" / "time-skip"
+
+ store = time_skip.TimeSkipStore(state_root())
+
+ if a.timeskip_command == "list":
+ runs = store.list()
+ if a.output == "json":
+ return _success({"runs": runs}, machine=True)
+ if not runs:
+ print("no Time-skip runs recorded")
+ return 0
+ for r in runs:
+ decision = (r.get("decision") or {}).get("outcome") or "-"
+ print(f"{r['id'][:12]} {str(r.get('state','?')):<18} {decision:<12} "
+ f"{(r.get('prompt') or '')[:48]}")
+ return 0
+
+ if a.timeskip_command == "status":
+ try:
+ data = store.get(a.run_id)
+ except time_skip.TimeSkipError as e:
+ return _error(str(e), 2, a.output == "json")
+ if a.output == "json":
+ return _success({"run": data}, machine=True)
+ print(f"run {data['id']}")
+ print(f"state {data['state']}")
+ print(f"workspace {data['workspace']}")
+ print(f"prompt {data['prompt']}")
+ for cp in data.get("checkpoints", []):
+ outcomes = ", ".join(f"{c['id']}={c['outcome']}" for c in cp.get("checks", [])) or "no checks"
+ print(f" {cp['id']:<16} {cp['digest'][:12]} {outcomes}")
+ for att in data.get("attempts", []):
+ print(f" attempt {att['index']}: {att.get('decision')} - {att.get('reason','')}")
+ dec = data.get("decision") or {}
+ if dec:
+ print(f"decision {dec.get('outcome')} ({dec.get('reason')})")
+ print(f"retained {dec.get('retained')}")
+ if dec.get("needs_user_review"):
+ print(" needs user review: the evidence does not justify an automatic choice")
+ return 0
+
+ if a.timeskip_command == "apply":
+ try:
+ data = store.get(a.run_id)
+ except time_skip.TimeSkipError as e:
+ return _error(str(e), 2, a.output == "json")
+ run = _reopen_run(store, data)
+ destination = Path(a.workspace) if a.workspace else None
+ try:
+ if a.restore:
+ outcome = run.restore_original(destination)
+ if a.output == "json":
+ return _success({"restore": outcome}, machine=True)
+ print(f"restored {outcome['checkpoint']} to {destination or data['workspace']}")
+ return 0
+ outcome = run.apply(destination, dry_run=a.dry_run)
+ except time_skip.TimeSkipError as e:
+ return _error(str(e), 2, a.output == "json")
+ if outcome.get("conflict"):
+ # A concurrent user edit is a conflict to report, never something to overwrite.
+ return _error(outcome["reason"], 6, a.output == "json")
+ if not outcome.get("applied") and not outcome.get("dry_run"):
+ return _error(outcome.get("reason", "apply did not complete"), 6, a.output == "json")
+ if a.output == "json":
+ return _success({"apply": outcome}, machine=True)
+ if outcome.get("dry_run"):
+ print("would write: " + (", ".join(outcome.get("would_write") or []) or "(nothing)"))
+ if outcome.get("would_remove"):
+ print("would remove: " + ", ".join(outcome["would_remove"]))
+ return 0
+ print("applied " + (", ".join(outcome.get("wrote") or []) or "(no changes)"))
+ print(f"rollback copy: {outcome.get('rollback')}")
+ return 0
+
+ # run
+ workspace = Path(a.workspace)
+ if not workspace.is_dir():
+ return _error(f"workspace is not a directory: {workspace}", 2, a.output == "json")
+ try:
+ checks = store.load_checks(workspace)
+ except (time_skip.TimeSkipError, ValueError, OSError) as e:
+ return _error(f"could not read .strata/checks.json: {e}", 2, a.output == "json")
+ if not checks:
+ print("strata: no checks are declared for this workspace (.strata/checks.json); the run "
+ "will checkpoint and report inconclusive rather than claim an improvement",
+ file=sys.stderr)
+
+ run = time_skip.TimeSkipRun(state_root(), workspace, a.prompt, checks, max_attempts=a.attempts)
+
+ def revise(candidate: Path, prompt: str, attempt: int):
+ if not a.revise_command:
+ return None
+ env = {**os.environ, "STRATA_TIMESKIP_PROMPT": prompt,
+ "STRATA_TIMESKIP_ATTEMPT": str(attempt)}
+ proc = subprocess.run(a.revise_command, shell=True, cwd=str(candidate), env=env,
+ capture_output=True, text=True)
+ if proc.returncode != 0:
+ raise time_skip.TimeSkipError(
+ f"the revision command failed (exit {proc.returncode}): "
+ f"{(proc.stderr or proc.stdout or '')[-300:]}")
+ return (proc.stdout or "").strip()[-500:] or None
+
+ result = run.run(revise)
+ if a.output == "json":
+ if result["state"] in ("failed", "interrupted"):
+ return _error(result.get("error") or result["state"], 6, True)
+ return _success({"run": result}, machine=True)
+ print(f"run {result['id']} -> {result['state']}")
+ for att in result.get("attempts", []):
+ print(f" attempt {att['index']}: {att.get('decision')} - {att.get('reason','')}")
+ dec = result.get("decision") or {}
+ if dec:
+ print(f" decision: {dec.get('outcome')} ({dec.get('reason')})")
+ if dec.get("needs_user_review"):
+ print(" the evidence does not justify an automatic choice; compare and select")
+ print(f" inspect: strata timeskip status {result['id']}")
+ print(f" preview: strata timeskip apply {result['id']} --dry-run")
+ if result["state"] in ("failed", "interrupted"):
+ return _error(result.get("error") or result["state"], 6, False)
+ return 0
+
+
+def _reopen_run(store, data: dict):
+ """Rebuild a run object from its durable record so apply/restore survive a restart."""
+ from strata_control import time_skip
+ run = time_skip.TimeSkipRun(store.root, Path(data["workspace"]), data["prompt"], [],
+ run_id=data["id"])
+ run.state = data.get("state", run.state)
+ run.checkpoints = [time_skip.Checkpoint(**cp) for cp in data.get("checkpoints", [])]
+ run.attempts = [time_skip.Attempt(**att) for att in data.get("attempts", [])]
+ run.selected_checkpoint = data.get("selected_checkpoint")
+ run.decision = data.get("decision")
+ run.events = data.get("events", [])
+ run.started_at = data.get("started_at", run.started_at)
+ run.finished_at = data.get("finished_at")
+ return run
+
+
+def _tune(a: argparse.Namespace) -> int:
+ """Engine tuning: a bounded search that returns a recommendation, never an automatic change.
+
+ `plan` is the review surface. It reports which dimensions the selected backend may search and
+ *why* the rest were excluded, so a sweep can never measure a configuration the engine would
+ refuse. Running a sweep is a separate, longer step and is deliberately not exposed here yet: it
+ needs a measurement harness for the selected engine, and this Mac has no workload to measure.
+ """
+ from strata_control import tuning
+ machine = a.output == "json"
+
+ def state_root() -> Path:
+ if getattr(a, "state_dir", None):
+ return Path(a.state_dir)
+ env = os.environ.get("STRATA_TUNE_DIR")
+ if env:
+ return Path(env)
+ base = os.environ.get("XDG_STATE_HOME") or str(Path.home() / ".local" / "state")
+ return Path(base) / "strata" / "tuning"
+
+ if a.tune_command == "list":
+ root = state_root()
+ jobs = []
+ if root.is_dir():
+ for d in sorted(root.iterdir()):
+ f = d / "job.json"
+ if f.is_file():
+ try:
+ data = json.loads(f.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ continue
+ jobs.append({"id": data.get("id"), "state": data.get("state"),
+ "backend": (data.get("plan") or {}).get("backend"),
+ "objective": (data.get("plan") or {}).get("objective")})
+ if machine:
+ return _success({"jobs": jobs}, machine=True)
+ if not jobs:
+ print("no tuning jobs recorded")
+ return 0
+ for j in jobs:
+ print(f"{str(j['id'])[:12]} {str(j['state']):<10} {str(j['backend']):<8} {j['objective']}")
+ return 0
+
+ if a.tune_command == "status":
+ root = state_root()
+ f = root / a.job_id / "job.json"
+ if not f.is_file():
+ return _error(f"no tuning job {a.job_id}", 2, machine)
+ data = json.loads(f.read_text(encoding="utf-8"))
+ if machine:
+ return _success({"job": data}, machine=True)
+ print(f"job {data['id']}")
+ print(f"state {data['state']}")
+ plan = data.get("plan") or {}
+ print(f"backend {plan.get('backend')} objective {plan.get('objective')}")
+ rep = data.get("report") or {}
+ if rep:
+ print(f"metric {rep.get('metric')} (higher is better: {rep.get('higher_is_better')})")
+ print(f"trials {rep.get('trials_run')} of {plan.get('max_trials')}")
+ base = rep.get("baseline") or {}
+ if base:
+ print(f"baseline median {base.get('median')} over {base.get('measured')} runs")
+ if rep.get("recommendation_available"):
+ rec = rep["recommendation"]
+ print(f"recommend index {rec['candidate_index']} median {rec['median']} "
+ f"(baseline {rec['baseline_median']})")
+ print(f" args: {' '.join(f'{k} {v}' for k, v in rec['args'].items())}")
+ else:
+ print(f"recommend none - {rep.get('reason')}")
+ for f_ in rep.get("failures") or []:
+ print(f" failed #{f_['index']} {f_['status']}: {f_['reason'][:90]}")
+ return 0
+
+ if a.tune_command == "run":
+ return _tune_run(a, store_root=state_root())
+ if a.tune_command == "apply":
+ return _tune_apply(a, store_root=state_root())
+ if a.tune_command == "rollback":
+ return _tune_rollback(a, store_root=state_root())
+
+ # plan
+ engine = Path(a.engine)
+ plan = tuning.plan_tuning(engine, a.backend, a.model, a.objective,
+ {"note": "the workload is supplied by the measurement harness"},
+ hold=a.hold, max_trials=a.trials, total_time_s=a.total_time,
+ repeats=a.repeats, devices=[],
+ model_path=getattr(a, "model_path", None))
+ if machine:
+ return _success({"plan": plan.to_dict()}, machine=True)
+ print(f"engine {plan.engine}")
+ print(f"flags {'read from the binary' if plan.engine_flags_known else 'could not be read; the static table was used and this is recorded'}")
+ print(f"backend {plan.backend} objective {plan.objective} repeats {plan.repeats}")
+ print(f"bounds at most {plan.max_trials} trials, {plan.total_time_s:.0f}s total")
+ print("searches:")
+ for d in plan.dimensions:
+ mark = " (benchmark only: never exported)" if d["benchmark_only"] else ""
+ print(f" {d['id']:<18} {', '.join(d['flags'])} values {d['values']}{mark}")
+ if not plan.dimensions:
+ print(" (none: this backend offers no searchable dimension)")
+ print("excluded:")
+ for e in plan.excluded:
+ print(f" {e['id']:<18} {e['reason']}")
+ print()
+ print("Applying a result is a separate step; a sweep never writes the active profile.")
+ return 0
+
+
+def _tune_run(a: argparse.Namespace, *, store_root: Path) -> int:
+ """Run a bounded sweep and write its report.
+
+ The measurement is `tune_engine.EngineHarness`: it boots the engine with one candidate's flags,
+ sends the fixed workload and reads the engine's own protocol output. Nothing here invents a
+ number — a candidate that cannot be measured is recorded with the engine's reason and excluded
+ from selection.
+
+ Two honest limitations are printed with the result rather than buried:
+
+ * the winner is measured through the engine's own serve protocol, **not** through the full
+ HTTP API the Harness uses, so the recommendation still needs the exported-configuration
+ retest the qualification kit describes before it is trusted;
+ * no profile is written. Applying is a separate, reversible step.
+ """
+ from strata_control import tune_engine, tuning
+
+ engine = Path(a.engine)
+ if not engine.exists():
+ return _error(f"no engine binary at {engine}", 2, a.output == "json")
+
+ plan = tuning.plan_tuning(
+ engine, a.backend, a.model, a.objective,
+ {"prompt_tokens": a.prompt_tokens, "max_new": a.max_new, "seed": 1, "temperature": 0.0},
+ hold=a.hold, max_trials=a.trials, total_time_s=a.total_time, repeats=a.repeats, devices=[],
+ model_path=Path(a.model_path) if a.model_path else None, context=a.context,
+ full_digests=a.full_digests)
+
+ workload = {"prompt_tokens": a.prompt_tokens, "max_new": a.max_new, "seed": 1, "temperature": 0.0}
+ if a.mode == "api":
+ from strata_control import tune_api
+ if not a.config:
+ return _error("--mode api needs --config: the worker is started from a run "
+ "configuration so the candidate's flags are the ones it boots with",
+ 2, a.output == "json")
+ if not a.api_expect:
+ return _error("--mode api needs --api-expect: without an expectation a fast wrong answer "
+ "cannot be told from a fast right one", 2, a.output == "json")
+ measure = tune_api.make_api_measure(
+ python=sys.executable, serve_dir=Path(__file__).resolve().parents[1],
+ config_path=Path(a.config), prompt=a.api_prompt, max_new=a.max_new,
+ expect=a.api_expect, port=a.api_port, boot_timeout_s=a.boot_timeout,
+ request_timeout_s=a.request_timeout)
+ else:
+ measure = tune_engine.make_measure(engine, workload=workload)
+
+ if a.output != "json":
+ searched = ", ".join(d["id"] for d in plan.dimensions) or "(nothing)"
+ print(f"sweeping {searched}")
+ if a.mode == "api":
+ print(f"measuring through the HTTP API at port {a.api_port}, "
+ f"checking the answer against {a.api_expect!r}")
+ else:
+ print("measuring the engine's own serve protocol")
+ print(f"backend {plan.backend} · objective {plan.objective} · repeats {plan.repeats} · "
+ f"at most {plan.max_trials} trials / {plan.total_time_s:.0f}s")
+ if not plan.dimensions:
+ print("strata: this backend offers no searchable dimension for this engine, so the "
+ "sweep will measure the baseline and stop", file=sys.stderr)
+
+ job = tuning.Tuner(store_root, plan, measure)
+ result = job.run()
+
+ if a.output == "json":
+ return _success({"job": result}, machine=True)
+
+ rep = result.get("report") or {}
+ print(f"job {result['id']} -> {result['state']}")
+ base = rep.get("baseline") or {}
+ if base:
+ print(f" baseline median {base.get('median')} over {base.get('measured')} runs")
+ total = rep.get("combinations_total") or 0
+ ran = rep.get("trials_run", 0)
+ if rep.get("trials_are_a_prefix") and total:
+ # Say plainly that this was a prefix of the space. Otherwise "4 trials" reads as "4 was all
+ # there was", and a partial search gets mistaken for a complete one.
+ print(f" trials {ran} of {plan.max_trials} allowed, from {total} possible combinations "
+ f"(a prefix of the enumeration)")
+ else:
+ print(f" trials {ran} of {plan.max_trials}")
+ for f in rep.get("failures") or []:
+ print(f" failed #{f['index']} {f['status']}: {f['reason'][:90]}")
+ if rep.get("drift") and rep.get("drift_material"):
+ d = rep["drift"]
+ print(f" drift baseline {d['first']:.1f} -> {d['last']:.1f} "
+ f"({d['relative'] * 100:+.1f}%) — the comparison is weaker than the repeat count suggests")
+ elif rep.get("drift"):
+ d = rep["drift"]
+ print(f" drift baseline {d['first']:.1f} -> {d['last']:.1f} "
+ f"({d['relative'] * 100:+.1f}%) — within noise")
+ if rep.get("recommendation_available"):
+ rec = rep["recommendation"]
+ args = " ".join(f"{k} {v}" for k, v in rec["args"].items()) or "(no flags)"
+ print(f" recommend index {rec['candidate_index']}: {args}")
+ print(f" median {rec['median']:.1f} against a baseline of {rec['baseline_median']:.1f}")
+ else:
+ print(f" recommend none — {rep.get('reason')}")
+ print()
+ if a.mode == "api":
+ print(" measured through the worker's HTTP API, which is what a user waits for.")
+ else:
+ print(" measured through the engine's own serve protocol, which is not what a user waits")
+ print(" for. Confirm any recommendation with --mode api before trusting it.")
+ print(" Apply it as a separate reviewed step: strata tune apply <job>. No profile has changed.")
+ print(f" report: strata tune status {result['id']}")
+ return 0
+
+
+def _tune_apply(a: argparse.Namespace, *, store_root: Path) -> int:
+ """Apply a recommendation to a run configuration, after verifying the candidate runs.
+
+ The verification is a real start: the candidate configuration is booted and required to produce at
+ least one token before the file is touched. A sweep cannot see that failure, because a sweep
+ measures generation on a configuration it never writes.
+ """
+ from strata_control import tune_apply, tune_history
+
+ job = _load_job(store_root, a.job_id)
+ if job is None:
+ return _error(f"no tuning job {a.job_id} in {store_root}", 2, a.output == "json")
+
+ config = Path(a.config) if a.config else _find_config_for(job)
+ if config is None or not config.exists():
+ return _error("no run configuration found; pass --config strata-<model>.json",
+ 2, a.output == "json")
+
+ identity = None
+ if a.model_path or (job.get("plan") or {}).get("identity"):
+ try:
+ engine_path = Path((job.get("plan") or {}).get("engine") or "")
+ identity = tune_history.comparison_key(
+ engine=tune_history.file_identity(engine_path),
+ model=tune_history.file_identity(Path(a.model_path)) if a.model_path
+ else {"path": None, "exists": False, "method": None, "digest": None, "bytes": None},
+ backend=(job.get("plan") or {}).get("backend") or "",
+ workload=((job.get("report") or {}).get("metric") and
+ _workload_of(job)) or {},
+ context=(job.get("plan") or {}).get("context"))
+ except Exception: # noqa: BLE001 - an unavailable identity means "cannot verify", below
+ identity = None
+
+ # The recorded sweep has to carry a model digest before anything is written. A sweep planned
+ # without `--model-path` records `model_digest: null`, and `null` does not equal any real digest,
+ # so such a recommendation can never be matched to what is installed -- which means it cannot be
+ # applied, however plausible its numbers look. This is a refusal, not a warning.
+ recorded = ((job.get("report") or {}).get("identity") or {})
+ if not recorded.get("model_digest"):
+ return _error(
+ "the sweep recorded no model digest, so its recommendation cannot be matched to the "
+ "installed weights; re-run the sweep with --model-path and apply that result instead",
+ 2, a.output == "json")
+ if a.model_path and identity is not None and not identity.get("model_digest"):
+ return _error(f"no model file at {a.model_path}", 2, a.output == "json")
+ if identity is None:
+ return _error("the sweep's identity could not be re-derived; refusing to apply a "
+ "configuration that may have been measured against different bytes",
+ 2, a.output == "json")
+
+ try:
+ result = tune_apply.apply_recommendation(
+ job=job, config_path=config, current_identity=identity, state_dir=store_root,
+ verify=None) # a real verification needs a model; the plan is still checked
+ except tune_apply.ApplyError as e:
+ return _error(str(e), e.code, a.output == "json")
+
+ if a.output == "json":
+ return _success(result, machine=True)
+ plan = result["plan"]
+ print(f"applied to {plan['config_path']}")
+ for item in plan["added"]:
+ print(f" + {item}")
+ for item in plan["removed"]:
+ print(f" - {item}")
+ print(f" before {plan['before_sha256'][:16]} after {plan['after_sha256'][:16]}")
+ print(f" rollback: strata tune rollback {result['application']['application_id']}")
+ print()
+ print(" The candidate was NOT verified against a running model: no supported model fits this")
+ print(" machine. The configuration was checked for staleness, identity and diff, and the")
+ print(" previous bytes were retained. Verify generation before relying on this configuration.")
+ return 0
+
+
+def _find_config_for(job: dict) -> Path | None:
+ """The run configuration for the sweep's model, found next to the repository."""
+ from strata_control import tune_apply
+ model = (job.get("plan") or {}).get("model") or ""
+ candidates = tune_apply.find_config_files(Path.cwd())
+ if not candidates:
+ return None
+ for path in candidates:
+ if model and model.lower() in path.stem.lower():
+ return path
+ return candidates[0] if len(candidates) == 1 else None
+
+
+def _workload_of(job: dict) -> dict:
+ return dict(((job.get("plan") or {}).get("identity") or {}).get("workload") or {})
+
+
+def _load_job(store_root: Path, job_id: str) -> dict | None:
+ if not re.fullmatch(r"[0-9a-f]{8,64}", str(job_id or "")):
+ return None
+ path = Path(store_root) / job_id / "job.json"
+ if not path.exists():
+ return None
+ try:
+ return json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return None
+
+
+def _tune_rollback(a: argparse.Namespace, *, store_root: Path) -> int:
+ from strata_control import tune_apply
+ try:
+ result = tune_apply.rollback(application_id=a.application_id, state_dir=store_root)
+ except tune_apply.ApplyError as e:
+ return _error(str(e), e.code, a.output == "json")
+ if a.output == "json":
+ return _success(result, machine=True)
+ print(f"restored {result['restored']}")
+ print(f" application {result['application']['application_id']} marked rolled back")
+ return 0
+
+
+def _components_plan(a: argparse.Namespace) -> int:
+ """Read a component manifest and report whether it may be used on this machine.
+
+ This is the input that decides what gets downloaded and unpacked, so it is read strictly and the
+ platform and backend gates are applied before anything is fetched. An unsupported combination is
+ reported as unsupported rather than attempted.
+ """
+ from strata_control import components
+ path = Path(a.manifest)
+ if not path.exists():
+ return _error(f"no component manifest at {path}", 2, a.output == "json")
+ try:
+ component = components.parse_manifest(path.read_text(encoding="utf-8"))
+ except components.ComponentError as e:
+ return _error(str(e), e.code, a.output == "json")
+
+ target = a.target or components.host_platform()
+ reasons = components.check_compatible(component, target=target, backend=a.backend)
+ payload = {
+ "id": component.id, "version": component.version, "kind": component.kind,
+ "backend": component.backend, "target": target,
+ "platforms": list(component.platforms), "cache_key": component.cache_key,
+ "usable": not reasons, "reasons": reasons,
+ "artifacts": [{"name": art.name, "bytes": art.bytes, "sha256": art.sha256,
+ "format": art.format} for art in component.artifacts],
+ "total_bytes": sum(art.bytes for art in component.artifacts),
+ "requires": list(component.requires), "entrypoint": component.entrypoint,
+ }
+ if a.output == "json":
+ return _success(payload, machine=True)
+ print(f"{component.id} {component.version} ({component.kind}"
+ + (f", {component.backend}" if component.backend else "") + ")")
+ print(f" platforms {', '.join(component.platforms)}")
+ print(f" target {target}")
+ print(f" payload {payload['total_bytes'] / (1 << 20):.1f} MiB in "
+ f"{len(component.artifacts)} artifact(s)")
+ print(f" cache key {component.cache_key[:16]} (the bytes, not the version label)")
+ if a.backend:
+ print(f" backend {a.backend}")
+ print(f" usable {'yes' if payload['usable'] else 'NO'}")
+ for reason in reasons:
+ print(f" - {reason}")
+ if component.requires:
+ print(f" requires {', '.join(component.requires)}")
+ print(" nothing was downloaded, unpacked or changed")
+ return 0
+
+
+def _components_backends(a: argparse.Namespace) -> int:
+ """The committed OS and backend matrix, so an unsupported combination is visible up front."""
+ from strata_control import components
+ here = components.host_platform()
+ rows = []
+ for backend, platforms in sorted(components.BACKEND_MATRIX.items()):
+ rows.append({"backend": backend, "platforms": list(platforms), "here": here in platforms})
+ if a.output == "json":
+ return _success({"host": here, "matrix": rows}, machine=True)
+ print(f"this machine is {here}")
+ print()
+ for row in rows:
+ mark = "supported here" if row["here"] else "not supported here"
+ print(f" {row['backend']:<6} {', '.join(row['platforms']):<45} {mark}")
+ print()
+ print(" Unsupported combinations are not attempted. A combination that is listed but has not")
+ print(" been qualified on real hardware is prepared, not claimed: see packaging/README.md.")
+ return 0
+
+
+def _run(a: argparse.Namespace) -> int:
+ try:
+ if a.command == "serve":
+ return _serve(a)
+ if a.command == "profile":
+ return _profile_command(a)
+ if a.command == "components" and a.components_command == "plan":
+ return _components_plan(a)
+ if a.command == "components" and a.components_command == "backends":
+ return _components_backends(a)
+ if a.command in ("doctor", "components"):
+ return _doctor(a)
+ if a.command == "models":
+ return _models(a)
+ if a.command == "engine":
+ return _calibration(a)
+ if a.command == "bench":
+ return _bench(a)
+ if a.command == "timeskip":
+ return _timeskip(a)
+ if a.command == "tune":
+ return _tune(a)
+ if a.command == "runtime":
+ return _runtime(a)
+ if a.command == "ops":
+ return _ops(a)
+ if a.command == "code":
+ return _error("the shared Desktop harness component is not installed; coding sessions are unavailable", 5,
+ getattr(a, "output", None) in ("json", "jsonl"))
+ return monitor_commands.run(a)
+ except ValueError as e:
+ if a.command == "serve" and a.output == "jsonl":
+ return _serve_error(a, str(e), getattr(e, "exit_code", 2))
+ return _error(str(e), getattr(e, "exit_code", 2),
+ bool(getattr(a, "json", False) or getattr(a, "output", None) in ("json", "jsonl")))
+ except BrokenPipeError:
+ return 0
+ except OSError as e:
+ if a.command == "serve" and a.output == "jsonl":
+ return _serve_error(a, f"local file operation failed ({type(e).__name__})", 6)
+ return _error(f"local file operation failed ({type(e).__name__})", 6,
+ bool(getattr(a, "output", None) in ("json", "jsonl")))
+ except ClientError as e:
+ if a.command == "serve" and a.output == "jsonl":
+ return _serve_error(a, str(e), e.exit_code)
+ return _error(str(e), e.exit_code,
+ bool(getattr(a, "json", False) or getattr(a, "output", None) in ("json", "jsonl")))
+ except KeyboardInterrupt:
+ if a.command == "serve" and a.output == "jsonl":
+ return _serve_error(a, "interrupted; operation completion may be unknown", 130)
+ return _error("interrupted; operation completion may be unknown", 130,
+ bool(getattr(a, "json", False) or getattr(a, "output", None) in ("json", "jsonl")))
+
+
+class _QuietCapture:
+ """Keep the last human output to show only when an operation fails."""
+
+ def __init__(self, limit: int = 64 * 1024):
+ self.limit = limit
+ self.text = ""
+ self.truncated = False
+
+ def write(self, value: str) -> int:
+ if len(self.text) + len(value) > self.limit:
+ self.truncated = True
+ self.text = (self.text + value)[-self.limit:]
+ return len(value)
+
+ def flush(self) -> None:
+ pass
+
+ def getvalue(self) -> str:
+ return self.text
+
+
+def main(argv: list[str] | None = None) -> int:
+ ap = parser()
+ a = ap.parse_args(argv)
+ if getattr(a, "json", False) and a.command not in ("status", "monitor", "logs", "connection", "config"):
+ if a.output == "jsonl":
+ return _serve_error(a, "--json is one-shot only; use --output jsonl for foreground events")
+ a.output = "json"
+ if not getattr(a, "quiet", False) or getattr(a, "output", "human") in ("json", "jsonl"):
+ return _run(a)
+ if a.command in ("status", "monitor", "logs", "connection", "config") or \
+ (a.command == "serve" and not a.plan):
+ return _run(a)
+ captured = _QuietCapture()
+ with contextlib.redirect_stdout(captured):
+ code = _run(a)
+ if code and captured.getvalue():
+ if captured.truncated:
+ sys.stderr.write("strata: earlier human output omitted in quiet mode\n")
+ sys.stderr.write(captured.getvalue())
+ return code
diff --git a/strata_cli/client.py b/strata_cli/client.py
new file mode 100644
index 000000000..90c9a7c4f
--- /dev/null
+++ b/strata_cli/client.py
@@ -0,0 +1,531 @@
+"""Bounded, read-only transport and normalization for Strata telemetry."""
+
+from __future__ import annotations
+
+import json
+import math
+import re
+import socket
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+from dataclasses import dataclass
+from typing import Any
+
+
+MAX_BODY = 2 * 1024 * 1024
+
+
+def complete_slots(work: dict) -> list[dict] | None:
+ """Return the effective slot set only when its identity and states are sound."""
+ slots, effective = work.get("slots"), work.get("slots_effective")
+ if (not isinstance(slots, list) or not isinstance(effective, int) or
+ isinstance(effective, bool) or effective <= 0 or len(slots) != effective):
+ return None
+ identities: set[int] = set()
+ for row in slots:
+ if not isinstance(row, dict):
+ return None
+ index, state = row.get("slot"), row.get("state")
+ if (not isinstance(index, int) or isinstance(index, bool) or not 0 <= index < effective or
+ index in identities or state not in ("idle", "reading", "decoding")):
+ return None
+ identities.add(index)
+ return slots
+
+
+class ClientError(Exception):
+ def __init__(self, message: str, exit_code: int = 3, *, http_status: int | None = None):
+ super().__init__(message)
+ self.exit_code = exit_code
+ self.http_status = http_status
+
+
+def server_url(raw: str) -> str:
+ """Require a server root and prevent credential/path ambiguity."""
+ if not isinstance(raw, str):
+ raise ValueError("URL must be an http(s) server root")
+ u = urllib.parse.urlsplit(raw)
+ if u.scheme not in ("http", "https") or not u.hostname or "@" in u.netloc:
+ raise ValueError("URL must be an http(s) server root without embedded credentials")
+ if u.path not in ("", "/") or u.query or u.fragment:
+ raise ValueError("URL must be the server root, without a path, query or fragment")
+ try:
+ port = u.port
+ except ValueError as e:
+ raise ValueError("invalid server port") from e
+ host = u.hostname.lower()
+ local = host in ("localhost", "127.0.0.1", "::1")
+ if u.scheme != "https" and not local:
+ raise ValueError("remote monitoring requires HTTPS or a local SSH tunnel")
+ authority = f"[{host}]" if ":" in host else host
+ return f"{u.scheme}://{authority}{':' + str(port) if port is not None else ''}"
+
+
+def url_prefix(value: str) -> str:
+ """A saved reverse-proxy path, never an alternate origin or query."""
+ if not isinstance(value, str) or len(value) > 256:
+ raise ValueError("connection prefix must be a short URL path")
+ if value in ("", "/"):
+ return ""
+ parts = value.split("/")
+ if parts[0] or len(parts) < 2 or any(not re.fullmatch(r"[A-Za-z0-9._~-]+", part) or part in (".", "..")
+ for part in parts[1:]):
+ raise ValueError("connection prefix must use simple /path segments without traversal")
+ return value
+
+
+class _NoRedirect(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, request, fp, code, msg, headers, newurl):
+ return None
+
+
+@dataclass(frozen=True)
+class Endpoint:
+ root: str
+ credential: str | None = None
+ timeout: float = 3.0
+ prefix: str = ""
+
+ def __post_init__(self):
+ object.__setattr__(self, "root", server_url(self.root))
+ object.__setattr__(self, "prefix", url_prefix(self.prefix))
+ if not 0 < self.timeout <= 30:
+ raise ValueError("timeout must be between 0 and 30 seconds")
+
+ @property
+ def base_url(self) -> str:
+ return self.root + self.prefix
+
+ def get(self, path: str) -> dict[str, Any]:
+ if path not in ("/v1/telemetry", "/v1/status", "/metrics", "/health"):
+ raise ValueError("endpoint is not part of the read-only telemetry contract")
+ headers = {"Accept": "application/json", "User-Agent": "Strata-Terminal/0.1"}
+ if self.credential:
+ headers["Authorization"] = "Bearer " + self.credential
+ req = urllib.request.Request(self.base_url + path, headers=headers)
+ opener = urllib.request.build_opener(_NoRedirect)
+ try:
+ with opener.open(req, timeout=self.timeout) as response:
+ content_type = response.headers.get("Content-Type", "")
+ if "application/json" not in content_type:
+ raise ClientError("server did not return JSON telemetry")
+ body = response.read(MAX_BODY + 1)
+ if len(body) > MAX_BODY:
+ raise ClientError("telemetry response exceeds the 2 MiB limit")
+ except urllib.error.HTTPError as e:
+ if e.code in (401, 403):
+ raise ClientError("telemetry authentication or permission failed", 4, http_status=e.code) from e
+ if e.code in (301, 302, 303, 307, 308):
+ raise ClientError("telemetry endpoint redirected; use the final server root",
+ http_status=e.code) from e
+ raise ClientError(f"telemetry request failed: HTTP {e.code}", http_status=e.code) from e
+ except (urllib.error.URLError, TimeoutError, socket.timeout, OSError) as e:
+ raise ClientError(f"cannot reach Strata server: {type(e).__name__}") from e
+ try:
+ data = json.loads(body)
+ except (ValueError, UnicodeDecodeError, RecursionError) as e:
+ raise ClientError("server returned malformed JSON telemetry") from e
+ if not isinstance(data, dict):
+ raise ClientError("server returned a non-object telemetry response")
+ return data
+
+ def snapshot(self) -> dict[str, Any]:
+ """Prefer the versioned endpoint; adapt the existing server if unavailable."""
+ try:
+ snapshot = self.get("/v1/telemetry")
+ except ClientError as e:
+ if e.http_status != 404:
+ raise
+ else:
+ if snapshot.get("schema_version") != 1:
+ raise ClientError("incompatible telemetry schema version", 5)
+ return sanitize_telemetry(snapshot)
+ try:
+ metrics = self.get("/metrics")
+ except ClientError as e:
+ if e.http_status != 404:
+ raise
+ return sanitize_telemetry(normalize_status_only(self.get("/v1/status")))
+ status = self.get("/v1/status")
+ return sanitize_telemetry(normalize_legacy(metrics, status))
+
+
+def _number(value: Any) -> int | float | None:
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
+ return None
+ return value
+
+
+def _short(value: Any, limit: int = 120) -> str | None:
+ if not isinstance(value, str):
+ return None
+ # Data is untrusted even if it came from the user's own model/server.
+ return "".join(c if c.isprintable() and c not in "\x1b\x7f" else " " for c in value)[:limit]
+
+
+def _object(value: Any) -> dict:
+ return value if isinstance(value, dict) else {}
+
+
+def _rows(value: Any, fields: tuple[str, ...], limit: int) -> list[dict]:
+ if not isinstance(value, list):
+ return []
+ out = []
+ for item in value[:limit]:
+ if not isinstance(item, dict):
+ continue
+ out.append({key: _short(item.get(key)) if key in ("id", "request_id", "state", "name", "finish")
+ else _number(item.get(key)) for key in fields})
+ return out
+
+
+def _selected_devices(value: Any) -> list[int]:
+ """Preserve the declared serving order without accepting ambiguous indices."""
+ if not isinstance(value, list):
+ return []
+ selected: list[int] = []
+ for index in value[:16]:
+ if type(index) is int and 0 <= index <= 65535 and index not in selected:
+ selected.append(index)
+ return selected
+
+
+def _replica_devices(value: Any) -> list[dict]:
+ """Accept only a bounded, unambiguous configured card assignment."""
+ if not isinstance(value, list):
+ return []
+ rows, seen_replicas, seen_devices = [], set(), set()
+ for entry in value[:16]:
+ if not isinstance(entry, dict):
+ continue
+ replica = entry.get("replica")
+ raw = entry.get("devices")
+ devices = _selected_devices(raw)
+ if (type(replica) is not int or not 0 <= replica < 16 or replica in seen_replicas or
+ not isinstance(raw, list) or not devices or len(devices) != len(raw) or
+ any(device in seen_devices for device in devices)):
+ continue
+ rows.append({"replica": replica, "devices": devices})
+ seen_replicas.add(replica)
+ seen_devices.update(devices)
+ return rows
+
+
+def _replica_stages(value: Any, devices: list[dict]) -> list[dict]:
+ """Keep child log ranges, resolving a card only inside that replica's configured set."""
+ if not isinstance(value, list):
+ return []
+ cards = {row["replica"]: set(row["devices"]) for row in devices}
+ rows, seen = [], set()
+ for raw in value[:16]:
+ if not isinstance(raw, dict):
+ continue
+ replica = raw.get("replica")
+ if type(replica) is not int or not 0 <= replica < 16 or replica in seen:
+ continue
+ seen.add(replica)
+ stages = _stage_rows(raw.get("stages"))
+ allowed = cards.get(replica, set())
+ for stage in stages:
+ if stage["device_index"] not in allowed:
+ stage["device_index"] = None
+ rows.append({"replica": replica, "stages": stages,
+ "resolved": bool(stages) and all(stage["device_index"] is not None for stage in stages)})
+ return rows
+
+
+_ACTIVITY_EVENTS = frozenset(("queued", "admitted", "reading", "first_token", "finished",
+ "cancelled", "disconnected", "timeout", "error"))
+_ACTIVITY_OUTCOMES = frozenset(("stop", "length", "cancel", "disconnect", "timeout", "error"))
+
+
+def _activity(value: Any) -> dict:
+ """Keep only the server's fixed-shape, bounded request transitions."""
+ if not isinstance(value, dict) or type(value.get("last_seq")) is not int or value["last_seq"] < 0 \
+ or not isinstance(value.get("events"), list):
+ return {"available": False, "last_seq": None, "events": []}
+ last_seq = value["last_seq"]
+ events = []
+ previous = 0
+ for row in value["events"][-32:]:
+ if not isinstance(row, dict):
+ continue
+ seq, at, request_id, event = (row.get(k) for k in ("seq", "at", "request_id", "event"))
+ if (type(seq) is not int or seq <= previous or seq > last_seq or
+ not isinstance(at, (int, float)) or isinstance(at, bool) or not math.isfinite(at) or
+ not 0 <= at <= 4_102_444_800 or
+ not isinstance(request_id, str) or not re.fullmatch(r"[0-9a-f]{12}", request_id) or
+ not isinstance(event, str) or event not in _ACTIVITY_EVENTS):
+ continue
+ outcome = row.get("outcome")
+ if outcome is not None and (not isinstance(outcome, str) or outcome not in _ACTIVITY_OUTCOMES):
+ continue
+ events.append({"seq": seq, "at": at, "request_id": request_id,
+ "event": event, "outcome": outcome})
+ previous = seq
+ return {"available": True, "last_seq": last_seq, "events": events}
+
+
+def _stage_rows(value: Any) -> list[dict]:
+ """Keep a bounded, contiguous stage plan; remote telemetry is untrusted."""
+ if not isinstance(value, list) or not 2 <= len(value) <= 16:
+ return []
+ out, next_layer = [], 0
+ for i, row in enumerate(value):
+ if not isinstance(row, dict):
+ return []
+ stage, first, last = row.get("stage"), row.get("layer_start"), row.get("layer_end")
+ ordinal, device = row.get("engine_ordinal"), row.get("device_index")
+ if (not all(isinstance(v, int) and not isinstance(v, bool) for v in (stage, first, last, ordinal))
+ or stage != i or first != next_layer or last < first or last > 65535
+ or not 0 <= ordinal <= 15
+ or (device is not None and (not isinstance(device, int) or isinstance(device, bool)
+ or not 0 <= device <= 65535))):
+ return []
+ out.append({"stage": stage, "layer_start": first, "layer_end": last,
+ "engine_ordinal": ordinal, "device_index": device})
+ next_layer = last + 1
+ return out
+
+
+def _batch_sample(work: dict) -> dict | None:
+ """A remote average is trusted only with bounded, internally consistent engine counts."""
+ windows, rows, active = (work.get(k) for k in
+ ("batch_sample_windows", "batch_sample_rows", "batch_sample_active_rows"))
+ age = _number(work.get("batch_sample_age_s"))
+ span = _number(work.get("batch_sample_span_s"))
+ if (not all(type(v) is int for v in (windows, rows, active)) or
+ not 1 <= windows <= 1_000_000_000 or not 1 <= active <= rows <= windows * 8 or
+ age is None or not 0 <= age <= 86_400 or span is None or not 0 < span <= 86_400):
+ return None
+ return {"effective_rows_window": rows / windows, "batch_active_rows_window": active / windows,
+ "batch_sample_windows": windows, "batch_sample_rows": rows,
+ "batch_sample_active_rows": active, "batch_sample_span_s": span,
+ "batch_sample_age_s": age}
+
+
+def _replica_batches(value: Any) -> list[dict]:
+ """Retain separate bounded engine samples; do not combine their unrelated windows."""
+ if not isinstance(value, list):
+ return []
+ rows, seen = [], set()
+ for raw in value[:16]:
+ if not isinstance(raw, dict):
+ continue
+ replica = raw.get("replica")
+ if type(replica) is not int or not 0 <= replica < 16 or replica in seen:
+ continue
+ seen.add(replica)
+ rows.append({"replica": replica, **(_batch_sample(raw) or {})})
+ return rows
+
+
+def _stage_sample(work: dict, known_stages: int) -> dict | None:
+ """Validate one bounded, internally consistent pipeline host-time sample."""
+ elapsed = work.get("stage_sample_elapsed_us")
+ busy = work.get("stage_in_flight_us")
+ age = _number(work.get("stage_sample_age_s"))
+ if type(elapsed) is not int or not 1 <= elapsed <= 86_400_000_000 or \
+ not isinstance(busy, list) or not 2 <= len(busy) <= 16 or \
+ (known_stages and len(busy) != known_stages) or \
+ age is None or not 0 <= age <= 86_400 or \
+ any(type(value) is not int or not 0 <= value <= elapsed for value in busy):
+ return None
+ return {"stage_in_flight": [
+ {"stage": i, "percent": round(100.0 * value / elapsed, 1),
+ "in_flight_ms": round(value / 1000.0, 3)}
+ for i, value in enumerate(busy)],
+ "stage_sample_span_s": elapsed / 1_000_000.0,
+ "stage_sample_age_s": age}
+
+
+def _replica_stage_samples(value: Any, replica_stages: list[dict]) -> list[dict]:
+ """Keep child host-span samples separate and check each against its own stage plan."""
+ if not isinstance(value, list):
+ return []
+ counts = {row["replica"]: len(row["stages"]) for row in replica_stages}
+ rows, seen = [], set()
+ for raw in value[:16]:
+ if not isinstance(raw, dict):
+ continue
+ replica = raw.get("replica")
+ if type(replica) is not int or not 0 <= replica < 16 or replica in seen:
+ continue
+ seen.add(replica)
+ rows.append({"replica": replica, **(_stage_sample(raw, counts.get(replica, 0)) or {})})
+ return rows
+
+
+def sanitize_telemetry(raw: dict[str, Any]) -> dict[str, Any]:
+ """Accept only bounded, privacy-safe v1 fields from a potentially remote server."""
+ instance, model = _object(raw.get("instance")), _object(raw.get("model"))
+ work, rates = _object(raw.get("work")), _object(raw.get("rates"))
+ topology, ram = _object(raw.get("topology")), _object(raw.get("ram"))
+ quality, totals = _object(raw.get("quality")), _object(raw.get("totals"))
+ activity = _activity(raw.get("activity"))
+ stages = _stage_rows(topology.get("stages"))
+ replica_devices = _replica_devices(topology.get("replica_devices"))
+ replica_stages = _replica_stages(topology.get("replica_stages"), replica_devices)
+ batch = _batch_sample(work)
+ replica_batches = _replica_batches(work.get("replica_batches"))
+ replica_mode = (str(topology.get("mode") or "").startswith("replicas") or
+ bool(replica_batches) or bool(replica_stages))
+ replica_stage_samples = (_replica_stage_samples(work.get("replica_stage_samples"), replica_stages)
+ if replica_mode else [])
+ if replica_mode:
+ batch = None
+ stages = []
+ stage_sample = None if replica_mode else _stage_sample(work, len(stages))
+ safe_slots = _rows(work.get("slots"), ("slot", "group", "replica", "request_id", "state", "held_tokens",
+ "prompt_tokens", "prompt_read", "generated", "elapsed_s", "tok_s"), 64)
+ for row in safe_slots:
+ replica = row.get("replica")
+ row["replica"] = replica if type(replica) is int and 0 <= replica < 16 else None
+ safe_requests = _rows(work.get("requests"), ("id", "state", "queued_at", "admitted_at", "slot",
+ "group", "replica", "prompt_tokens", "prompt_read",
+ "generated", "first_engine_token_s"), 50)
+ for row in safe_requests:
+ replica = row.get("replica")
+ row["replica"] = replica if type(replica) is int and 0 <= replica < 16 else None
+ reported_slots = complete_slots({"slots": safe_slots, "slots_effective": _number(work.get("slots_effective"))})
+ occupied_slots = (sum(row["state"] != "idle" for row in reported_slots)
+ if reported_slots is not None else None)
+ placement_resolved = topology.get("resolved") is True and bool(stages) and all(
+ row["device_index"] is not None for row in stages)
+ return {
+ "schema_version": 1, "source": _short(raw.get("source")), "sampled_at": _number(raw.get("sampled_at")),
+ "instance": {"id": _short(instance.get("id"), 64), "boot_time": _number(instance.get("boot_time")),
+ "server": _short(instance.get("server")),
+ "state": instance.get("state") if instance.get("state") in ("ready", "draining") else None},
+ "model": {"id": _short(model.get("id")),
+ "loaded": model.get("loaded") if isinstance(model.get("loaded"), bool) else None,
+ "context": _number(model.get("context"))},
+ "work": {**{k: _number(work.get(k)) for k in ("slots_requested", "slots_effective", "active", "queued",
+ "waiting", "outside_slots", "groups",
+ "requests_omitted", "max_queue", "admission_limit",
+ "admission_reserved", "admission_rejected", "oldest_queue_s",
+ "queue_timeout_s", "queue_timeouts",
+ "client_disconnect_cancels")},
+ **(batch or {"effective_rows_window": None, "batch_active_rows_window": None,
+ "batch_sample_windows": None, "batch_sample_rows": None,
+ "batch_sample_active_rows": None, "batch_sample_span_s": None,
+ "batch_sample_age_s": None}),
+ **(stage_sample or {"stage_in_flight": [], "stage_sample_span_s": None,
+ "stage_sample_age_s": None}),
+ "occupied_slots": occupied_slots,
+ "replica_batches": replica_batches,
+ "replica_stage_samples": replica_stage_samples,
+ "slots": safe_slots,
+ "requests": safe_requests},
+ "rates": {k: _number(rates.get(k)) for k in ("answer_tok_s", "answer_window_s", "prefill_tok_s",
+ "output_tokens_server_counter")},
+ "topology": {"mode": _short(topology.get("mode")), "configured_split": _short(topology.get("configured_split")),
+ "selected_devices": _selected_devices(topology.get("selected_devices")),
+ "replica_devices": replica_devices, "replica_stages": replica_stages,
+ "resolved": placement_resolved,
+ "stages": stages, "source": _short(topology.get("source"), 40)},
+ "devices": _rows(raw.get("devices"), ("index", "name", "mem_used", "mem_total", "util", "temp", "power"), 16),
+ "ram": {"used": _number(ram.get("used")), "total": _number(ram.get("total"))},
+ "recent": _rows(raw.get("recent"), ("id", "time", "duration_s", "finish", "prompt_tokens",
+ "reused", "output_tokens", "prompt_ms", "decode_ms",
+ "first_engine_token_s"), 50),
+ "totals": {k: _number(totals.get(k)) for k in ("since", "requests", "prompt_tokens", "output_tokens")},
+ "activity": activity,
+ "quality": {**{k: _short(quality.get(k)) for k in ("request_correlation", "per_device")},
+ "telemetry": "unavailable" if raw.get("source") == "status-only" else "available",
+ "batch_window_rows": "measured" if batch else "unavailable",
+ "batch_window_source": "engine_bstat" if batch else None,
+ "stage_in_flight": "measured_host_span" if stage_sample else "unavailable",
+ "stage_in_flight_source": "engine_pstat_host_span" if stage_sample else None,
+ "replica_stage_in_flight": ("measured_host_span" if any(
+ row.get("stage_in_flight") for row in replica_stage_samples) else "unavailable"),
+ "replica_stage_in_flight_source": ("engine_pstat_host_span" if any(
+ row.get("stage_in_flight") for row in replica_stage_samples) else None),
+ "placement": "reported" if placement_resolved else "partial" if stages else "unavailable"},
+ }
+
+
+def normalize_status_only(status: dict[str, Any]) -> dict[str, Any]:
+ """A reachable old server can still identify its model without metrics."""
+ concurrency = _object(status.get("concurrency"))
+ return {"schema_version": 1, "source": "status-only", "sampled_at": time.time(),
+ "instance": {"boot_time": _number(status.get("started")),
+ "server": _short(status.get("service"))},
+ "model": {"id": _short(status.get("model")),
+ "loaded": status.get("loaded") if isinstance(status.get("loaded"), bool) else None,
+ "context": _number(status.get("cache_max_tokens"))},
+ "work": {"slots_effective": _number(concurrency.get("serving"))}}
+
+
+def normalize_legacy(metrics: dict[str, Any], status: dict[str, Any]) -> dict[str, Any]:
+ """Keep null distinct from zero; never infer group/stage work from GPU count."""
+ live = metrics.get("live") if isinstance(metrics.get("live"), dict) else {}
+ engine = metrics.get("engine") if isinstance(metrics.get("engine"), dict) else {}
+ hardware = metrics.get("hardware") if isinstance(metrics.get("hardware"), dict) else {}
+ static = metrics.get("hardware_static") if isinstance(metrics.get("hardware_static"), dict) else {}
+ concurrency = status.get("concurrency") if isinstance(status.get("concurrency"), dict) else {}
+ slots = live.get("slots") if isinstance(live.get("slots"), list) else []
+ devices = hardware.get("gpus") if isinstance(hardware.get("gpus"), list) else []
+ safe_slots = []
+ for row in slots[:64]:
+ if isinstance(row, dict):
+ safe_slots.append({k: row.get(k) for k in ("slot", "group", "replica", "request_id", "state", "held_tokens",
+ "prompt_tokens", "prompt_read", "generated", "elapsed_s", "tok_s")})
+ effective_slots = _number(concurrency.get("serving"))
+ reported_slots = complete_slots({"slots": safe_slots, "slots_effective": effective_slots})
+ safe_devices = []
+ for row in devices[:16]:
+ if isinstance(row, dict):
+ safe_devices.append({"index": row.get("index"), "name": _short(row.get("name")),
+ "mem_used": _number(row.get("mem_used")),
+ "mem_total": _number(row.get("mem_total")),
+ "util": _number(row.get("util")), "temp": _number(row.get("temp")),
+ "power": _number(row.get("power"))})
+ # Old single-GPU servers report only aggregate GPU fields. It is one device only
+ # when the static sampler says so; never duplicate an aggregate into four rows.
+ if not safe_devices and static.get("gpu_count") == 1 and static.get("gpu_name"):
+ safe_devices = [{"index": 0, "name": _short(static.get("gpu_name")),
+ "mem_used": _number(hardware.get("gpu_mem_used")),
+ "mem_total": _number(hardware.get("gpu_mem_total")),
+ "util": _number(hardware.get("gpu_util")), "temp": _number(hardware.get("gpu_temp")),
+ "power": _number(hardware.get("gpu_power"))}]
+ recent = []
+ for row in (metrics.get("requests") if isinstance(metrics.get("requests"), list) else [])[:50]:
+ if isinstance(row, dict):
+ recent.append({k: row.get(k) for k in ("id", "time", "duration_s", "finish", "prompt_tokens",
+ "reused", "output_tokens", "prompt_ms", "decode_ms",
+ "first_engine_token_s")})
+ return {"schema_version": 1, "source": "legacy-adapter", "sampled_at": _number(metrics.get("time")),
+ "instance": {"boot_time": _number(status.get("started")), "server": _short(status.get("service"))},
+ "model": {"id": _short(status.get("model")), "loaded": status.get("loaded") if isinstance(status.get("loaded"), bool) else None,
+ "context": _number(status.get("cache_max_tokens"))},
+ "work": {"slots_requested": None, "slots_effective": effective_slots,
+ "active": _number(live.get("running")) if "running" in live else (1 if live.get("state") in ("reading", "generating") else 0),
+ "occupied_slots": (sum(row["state"] != "idle" for row in reported_slots)
+ if reported_slots is not None else None),
+ "queued": _number(live.get("queued")), "waiting": _number(live.get("waiting")),
+ "outside_slots": _number(live.get("outside_slots")), "slots": safe_slots,
+ "groups": _number(engine.get("batch_groups")), "effective_rows_window": None,
+ "batch_active_rows_window": None, "batch_sample_windows": None,
+ "batch_sample_rows": None, "batch_sample_active_rows": None,
+ "batch_sample_span_s": None, "batch_sample_age_s": None,
+ "stage_in_flight": [], "stage_sample_span_s": None, "stage_sample_age_s": None,
+ "requests": [], "requests_omitted": None, "max_queue": None,
+ "admission_limit": None, "admission_reserved": None,
+ "admission_rejected": None, "oldest_queue_s": None,
+ "queue_timeout_s": None, "queue_timeouts": None,
+ "client_disconnect_cancels": None},
+ "rates": {"answer_tok_s": _number(live.get("tok_s")),
+ "answer_window_s": _number(live.get("tok_s_window_s")),
+ "prefill_tok_s": _number(live.get("prefill_tok_s_mean"))},
+ "topology": {"mode": None, "stages": []}, "devices": safe_devices,
+ "ram": {"used": _number(hardware.get("ram_used")), "total": _number(hardware.get("ram_total"))},
+ "recent": recent, "totals": {k: _number(v) for k, v in
+ (metrics.get("totals") if isinstance(metrics.get("totals"), dict) else {}).items()
+ if k in ("since", "requests", "prompt_tokens", "output_tokens")},
+ "quality": {"request_correlation": "unavailable", "batch_window_rows": "unavailable",
+ "batch_window_source": None,
+ "stage_in_flight": "unavailable", "stage_in_flight_source": None,
+ "per_device": "measured" if safe_devices else "unavailable"}}
diff --git a/strata_cli/connections.py b/strata_cli/connections.py
new file mode 100644
index 000000000..75a3de2ed
--- /dev/null
+++ b/strata_cli/connections.py
@@ -0,0 +1,284 @@
+"""Owner-local monitor connections; store references, never credential values.
+
+This module is standard-library only so the portable monitor bundle and source
+CLI resolve the same saved connection without importing server or installer code.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import re
+import stat
+import tempfile
+from contextlib import contextmanager
+from pathlib import Path
+
+from strata_cli.client import server_url, url_prefix
+
+
+NAME = re.compile(r"[a-z][a-z0-9_-]{0,63}\Z")
+ENV_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_]{0,127}\Z")
+MAX_BYTES = 4096
+DEFAULT_URL = "http://127.0.0.1:8095"
+
+
+class ConnectionError(ValueError):
+ def __init__(self, message: str, exit_code: int = 2):
+ super().__init__(message)
+ self.exit_code = exit_code
+
+
+def _name(value: str) -> str:
+ if not isinstance(value, str) or not NAME.fullmatch(value):
+ raise ConnectionError("connection name must use lowercase a-z, 0-9, _ or - and start with a letter")
+ return value
+
+
+def prefix_path(value: str) -> str:
+ try:
+ return url_prefix(value)
+ except ValueError as exc:
+ raise ConnectionError(str(exc)) from None
+
+
+def credential_name(value: str) -> str:
+ if not isinstance(value, str) or not ENV_NAME.fullmatch(value):
+ raise ConnectionError("credential reference must be an ASCII environment variable name")
+ return value
+
+
+def connection_dir(*, create: bool = False) -> Path:
+ explicit = os.environ.get("STRATA_CONNECTION_DIR")
+ if explicit:
+ directory = Path(explicit).expanduser()
+ if not directory.is_absolute():
+ raise ConnectionError("STRATA_CONNECTION_DIR must be absolute")
+ elif os.name == "nt":
+ base = os.environ.get("APPDATA")
+ directory = (Path(base) if base else Path.home() / "AppData" / "Roaming") / "Strata" / "connections"
+ else:
+ directory = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "strata" / "connections"
+ if create:
+ directory.mkdir(mode=0o700, parents=True, exist_ok=True)
+ if directory.exists() or directory.is_symlink():
+ details = directory.lstat()
+ if not stat.S_ISDIR(details.st_mode) or (os.name == "posix" and
+ (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)):
+ raise ConnectionError("connection directory must be owner-only", 5)
+ return directory
+
+
+def _path(name: str, *, create_dir: bool = False) -> Path:
+ return connection_dir(create=create_dir) / f"{_name(name)}.json"
+
+
+def _validate(value: object, *, expected_name: str | None = None) -> dict:
+ if not isinstance(value, dict) or set(value) != {"schema_version", "id", "url", "prefix", "credential_env"}:
+ raise ConnectionError("connection has an unsupported schema", 5)
+ if type(value["schema_version"]) is not int or value["schema_version"] != 1:
+ raise ConnectionError("connection has an unsupported schema version", 5)
+ name = _name(value["id"])
+ if expected_name is not None and name != expected_name:
+ raise ConnectionError("connection ID does not match its filename", 5)
+ try:
+ url = server_url(value["url"])
+ except (ValueError, TypeError):
+ raise ConnectionError("connection URL must be a safe server root", 5) from None
+ prefix = prefix_path(value["prefix"])
+ credential = credential_name(value["credential_env"])
+ if url != value["url"] or prefix != value["prefix"]:
+ raise ConnectionError("connection URL or prefix is not canonical", 5)
+ return {"schema_version": 1, "id": name, "url": url, "prefix": prefix,
+ "credential_env": credential}
+
+
+def _bytes(value: dict) -> bytes:
+ data = (json.dumps(value, sort_keys=True, indent=2, ensure_ascii=False) + "\n").encode("utf-8")
+ if len(data) > MAX_BYTES:
+ raise ConnectionError("connection record exceeds 4 KiB", 5)
+ return data
+
+
+def _revision(data: bytes) -> str:
+ return hashlib.sha256(data).hexdigest()[:16]
+
+
+def load(name: str) -> tuple[dict, str]:
+ path = _path(name)
+ try:
+ details = path.lstat()
+ if not stat.S_ISREG(details.st_mode) or details.st_size > MAX_BYTES or \
+ (os.name == "posix" and (details.st_uid != os.getuid() or
+ stat.S_IMODE(details.st_mode) & 0o077)):
+ raise ConnectionError("connection file must be a private regular file under 4 KiB", 5)
+ data = path.read_bytes()
+ value = json.loads(data.decode("utf-8"))
+ except FileNotFoundError:
+ raise ConnectionError(f"connection {name!r} is not saved; use strata connection create", 5) from None
+ except (OSError, UnicodeError, ValueError) as exc:
+ if isinstance(exc, ConnectionError):
+ raise
+ raise ConnectionError("connection file is unreadable", 5) from None
+ try:
+ return _validate(value, expected_name=name), _revision(data)
+ except (ConnectionError, ValueError, TypeError) as exc:
+ raise ConnectionError(f"connection file has invalid values ({type(exc).__name__})", 5) from None
+
+
+def list_connections() -> list[dict]:
+ directory = connection_dir()
+ if not directory.exists():
+ return []
+ paths = [path for path in sorted(directory.glob("*.json")) if NAME.fullmatch(path.stem)]
+ if len(paths) > 100:
+ raise ConnectionError("more than 100 connection records need inspection", 5)
+ result = []
+ for path in paths:
+ try:
+ value, revision = load(path.stem)
+ result.append({"id": value["id"], "url": value["url"], "prefix": value["prefix"],
+ "credential_env": value["credential_env"], "revision": revision})
+ except ConnectionError as exc:
+ result.append({"id": path.stem, "error": str(exc)})
+ return result
+
+
+def _replace(path: Path, data: bytes) -> None:
+ descriptor, name = tempfile.mkstemp(prefix=f".{path.stem}-", suffix=".tmp", dir=path.parent)
+ try:
+ with os.fdopen(descriptor, "wb") as stream:
+ stream.write(data)
+ stream.flush()
+ os.fsync(stream.fileno())
+ os.replace(name, path)
+ if os.name == "posix":
+ try:
+ parent = os.open(path.parent, os.O_RDONLY)
+ try:
+ os.fsync(parent)
+ finally:
+ os.close(parent)
+ except OSError:
+ # The replacement succeeded; do not report a failed save afterward.
+ pass
+ finally:
+ if os.path.exists(name):
+ os.unlink(name)
+
+
+@contextmanager
+def _lock(name: str):
+ path = connection_dir(create=True) / f".{_name(name)}.lock"
+ descriptor = os.open(path, os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0), 0o600)
+ with os.fdopen(descriptor, "r+b") as stream:
+ details = os.fstat(stream.fileno())
+ if not stat.S_ISREG(details.st_mode) or (os.name == "posix" and
+ (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)):
+ raise ConnectionError("connection lock must be owner-only", 5)
+ if os.name == "nt":
+ import msvcrt
+ stream.seek(0)
+ if not stream.read(1):
+ stream.write(b"0")
+ stream.flush()
+ stream.seek(0)
+ msvcrt.locking(stream.fileno(), msvcrt.LK_LOCK, 1)
+ try:
+ yield
+ finally:
+ stream.seek(0)
+ msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1)
+ else:
+ import fcntl
+ fcntl.flock(stream.fileno(), fcntl.LOCK_EX)
+ try:
+ yield
+ finally:
+ fcntl.flock(stream.fileno(), fcntl.LOCK_UN)
+
+
+def create(name: str, url: str, *, prefix: str = "",
+ credential_env: str = "STRATA_TELEMETRY_KEY") -> tuple[dict, str]:
+ name = _name(name)
+ value = _validate({"schema_version": 1, "id": name, "url": server_url(url),
+ "prefix": prefix_path(prefix), "credential_env": credential_name(credential_env)},
+ expected_name=name)
+ data = _bytes(value)
+ path = _path(name, create_dir=True)
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
+ try:
+ descriptor = os.open(path, flags, 0o600)
+ except FileExistsError:
+ raise ConnectionError(f"connection {name!r} already exists") from None
+ try:
+ with os.fdopen(descriptor, "wb") as stream:
+ stream.write(data)
+ stream.flush()
+ os.fsync(stream.fileno())
+ except BaseException:
+ path.unlink(missing_ok=True)
+ raise
+ return value, _revision(data)
+
+
+def propose(name: str, assignment: str) -> tuple[dict, str]:
+ current, revision = load(name)
+ key, sep, raw = assignment.partition("=")
+ if not sep or key not in ("url", "prefix", "credential_env"):
+ raise ConnectionError("expected url=ROOT, prefix=/PATH or credential_env=ENV_NAME")
+ candidate = dict(current)
+ candidate[key] = (server_url(raw) if key == "url" else
+ prefix_path(raw) if key == "prefix" else credential_name(raw))
+ return _validate(candidate, expected_name=name), revision
+
+
+def save(name: str, value: dict, *, expected_revision: str) -> tuple[dict, str]:
+ name = _name(name)
+ value = _validate(value, expected_name=name)
+ if not isinstance(expected_revision, str) or not re.fullmatch(r"[0-9a-f]{16}", expected_revision):
+ raise ConnectionError("connection revision must be 16 lowercase hex characters")
+ path = _path(name)
+ with _lock(name):
+ current, revision = load(name)
+ if revision != expected_revision:
+ raise ConnectionError("connection changed since preview; inspect it again", 6)
+ data = _bytes(value)
+ if value == current:
+ return current, revision
+ _replace(path, data)
+ return value, _revision(data)
+
+
+def resolve(*, url: str | None = None, connection: str | None = None,
+ credential_env: str | None = None, timeout: float | None = None,
+ environment: dict | None = None) -> dict:
+ env = os.environ if environment is None else environment
+ selected = connection or (None if url is not None else env.get("STRATA_CONNECTION"))
+ if url is not None and connection is not None:
+ raise ConnectionError("choose --url or --connection, not both")
+ if selected:
+ saved, revision = load(selected)
+ root, prefix = saved["url"], saved["prefix"]
+ key_ref = saved["credential_env"]
+ origins = {"url": "connection", "prefix": "connection", "credential_env": "connection"}
+ else:
+ revision = None
+ root = url if url is not None else env.get("STRATA_URL", DEFAULT_URL)
+ prefix = ""
+ key_ref = "STRATA_API_KEY"
+ origins = {"url": "flag" if url is not None else "environment" if "STRATA_URL" in env else "default",
+ "prefix": "default", "credential_env": "default"}
+ if credential_env is not None:
+ key_ref = credential_env
+ origins["credential_env"] = "flag"
+ if timeout is not None and (type(timeout) not in (int, float) or not 0 < timeout <= 30):
+ raise ConnectionError("timeout must be greater than zero and at most 30 seconds")
+ origins["timeout_s"] = "flag" if timeout is not None else "default"
+ normalized_url, normalized_prefix = server_url(root), prefix_path(prefix)
+ return {"url": normalized_url, "prefix": normalized_prefix,
+ "base_url": normalized_url + normalized_prefix,
+ "credential_env": credential_name(key_ref), "credential_present": bool(env.get(key_ref)),
+ "timeout_s": timeout if timeout is not None else 3.0,
+ "connection": selected, "connection_revision": revision, "origins": origins}
diff --git a/strata_cli/dashboard.py b/strata_cli/dashboard.py
new file mode 100644
index 000000000..258479678
--- /dev/null
+++ b/strata_cli/dashboard.py
@@ -0,0 +1,902 @@
+"""Rich, read-only overview for the interactive monitor.
+
+The layout follows YASD's one-screen dashboard idea while using Strata's
+bounded telemetry contract and theme. No server text is treated as markup.
+"""
+
+from __future__ import annotations
+
+import math
+import time
+from collections import deque
+from typing import Any
+
+from rich import box
+from rich.align import Align
+from rich.console import Group
+from rich.panel import Panel
+from rich.table import Table
+from rich.text import Text
+
+from strata_cli.client import complete_slots
+from strata_cli.render import (_queue_wait, activity_continuity_notice, activity_label, display_width,
+ field, group_occupancy, number, safe)
+
+
+WORK_SAMPLE_MAX_AGE_S = 5.0
+
+
+def _current_sample(row: dict, age_key: str) -> bool:
+ """A retained engine sample stops representing current work after five seconds."""
+ age = row.get(age_key)
+ return (isinstance(age, (int, float)) and not isinstance(age, bool) and
+ math.isfinite(age) and 0 <= age <= WORK_SAMPLE_MAX_AGE_S)
+
+
+def _current_batch_value(row: dict, key: str) -> Any:
+ return row.get(key) if _current_sample(row, "batch_sample_age_s") else None
+
+
+class MonitorHistory:
+ """Small display-only device history, reset when the server changes."""
+
+ def __init__(self, limit: int = 32):
+ self.limit = limit
+ self.instance: tuple[str, str] | None = None
+ self.device_util: dict[int, deque[float | None]] = {}
+ self.device_vram: dict[int, deque[float | None]] = {}
+ self.output_rate: deque[float | None] = deque(maxlen=limit)
+ self.prefill_rate: deque[float | None] = deque(maxlen=limit)
+ self.answer_rate: deque[float | None] = deque(maxlen=limit)
+ self.batch_rows: deque[float | None] = deque(maxlen=limit)
+ self.pre_admit: deque[float | None] = deque(maxlen=limit)
+ self.replica_batch_rows: dict[int, deque[float | None]] = {}
+
+ @staticmethod
+ def _sample(value: Any) -> float | None:
+ return (float(value) if isinstance(value, (int, float)) and not isinstance(value, bool)
+ and math.isfinite(value) and 0 <= value <= 1_000_000_000 else None)
+
+ def gap(self) -> None:
+ """Keep an outage visible between samples from the same instance."""
+ self.output_rate.append(None)
+ self.prefill_rate.append(None)
+ self.answer_rate.append(None)
+ self.batch_rows.append(None)
+ self.pre_admit.append(None)
+ for series in (*self.device_util.values(), *self.device_vram.values(),
+ *self.replica_batch_rows.values()):
+ series.append(None)
+
+ def add(self, snapshot: dict, instance: tuple[str, str] | None) -> None:
+ if instance != self.instance:
+ self.device_util.clear()
+ self.device_vram.clear()
+ self.output_rate.clear()
+ self.prefill_rate.clear()
+ self.answer_rate.clear()
+ self.batch_rows.clear()
+ self.pre_admit.clear()
+ self.replica_batch_rows.clear()
+ self.instance = instance
+ value = (snapshot.get("rates") or {}).get("aggregate_output_tok_s")
+ self.output_rate.append(self._sample(value))
+ self.prefill_rate.append(self._sample((snapshot.get("rates") or {}).get("prefill_tok_s")))
+ self.answer_rate.append(self._sample((snapshot.get("rates") or {}).get("answer_tok_s")))
+ work = snapshot.get("work") or {}
+ self.batch_rows.append(self._sample(_current_batch_value(work, "effective_rows_window")))
+ self.pre_admit.append(self._sample(work.get("queued")))
+ replica_rows = work.get("replica_batches") or []
+ reported: dict[int, dict] = {}
+ ambiguous: set[int] = set()
+ for row in (replica_rows if isinstance(replica_rows, list) else [])[:16]:
+ if not isinstance(row, dict):
+ continue
+ replica = row.get("replica")
+ if type(replica) is not int or not 0 <= replica < 16:
+ continue
+ if replica in reported:
+ ambiguous.add(replica)
+ reported[replica] = row
+ topology = snapshot.get("topology") or {}
+ configured = {row.get("replica") for row in (topology.get("replica_devices") or [])[:16]
+ if isinstance(row, dict) and type(row.get("replica")) is int and
+ 0 <= row["replica"] < 16}
+ current_replicas = configured or set(reported)
+ self.replica_batch_rows = {
+ replica: self.replica_batch_rows.get(replica, deque(maxlen=self.limit))
+ for replica in current_replicas
+ }
+ for replica, series in self.replica_batch_rows.items():
+ row = reported.get(replica, {}) if replica not in ambiguous else {}
+ series.append(self._sample(_current_batch_value(row, "effective_rows_window")))
+ reported: dict[int, dict] = {}
+ ambiguous: set[int] = set()
+ devices = snapshot.get("devices")
+ for row in (devices if isinstance(devices, list) else [])[:16]:
+ if not isinstance(row, dict):
+ continue
+ index = row.get("index")
+ if type(index) is not int or not 0 <= index <= 65535:
+ continue
+ if index in reported:
+ ambiguous.add(index)
+ reported[index] = row
+ topology = snapshot.get("topology") or {}
+ selected = topology.get("selected_devices")
+ selected = selected if isinstance(selected, list) else []
+ indices = list(dict.fromkeys(index for index in selected[:16]
+ if type(index) is int and 0 <= index <= 65535))
+ if not indices:
+ indices = list(reported)
+ self.device_util = {index: self.device_util.get(index, deque(maxlen=self.limit))
+ for index in indices}
+ self.device_vram = {index: self.device_vram.get(index, deque(maxlen=self.limit))
+ for index in indices}
+ for index in indices:
+ row = reported.get(index) if index not in ambiguous else None
+ value = row.get("util") if row else None
+ if not isinstance(value, (int, float)) or isinstance(value, bool) or not math.isfinite(value):
+ value = None
+ self.device_util[index].append(value)
+ used, total = (row.get("mem_used"), row.get("mem_total")) if row else (None, None)
+ if (not all(isinstance(item, (int, float)) and not isinstance(item, bool) and
+ math.isfinite(item) for item in (used, total)) or
+ total <= 0 or used < 0 or used > total):
+ vram = None
+ else:
+ vram = 100.0 * (used / total)
+ self.device_vram[index].append(vram)
+
+
+def _spark(values: Any, glyphs: str, width: int = 8) -> str:
+ samples = list(values or [])[-(width * 2 if glyphs == "braille" else width):]
+ if not samples or all(value is None for value in samples):
+ return "--"
+ if glyphs != "braille":
+ ramp = ".:-=+*#@" if glyphs == "ascii" else "▁▂▃▄▅▆▇█"
+ return "".join(" " if value is None else ramp[min(7, max(0, int(value / 100 * 7)))]
+ for value in samples)
+ # Braille has two columns and four rows per cell. A cell represents two
+ # consecutive utilization samples, with the newest sample at the right.
+ left, right = (0x40, 0x04, 0x02, 0x01), (0x80, 0x20, 0x10, 0x08)
+ if len(samples) % 2:
+ samples.insert(0, None)
+ graph = []
+ for first, second in zip(samples[::2], samples[1::2]):
+ bits = 0
+ for value, dots in ((first, left), (second, right)):
+ if value is not None:
+ level = max(1, min(4, round(value / 100 * 4)))
+ bits |= sum(dots[:level])
+ graph.append(chr(0x2800 + bits) if bits else " ")
+ return "".join(graph)
+
+
+def _output_trend(values: Any, glyphs: str, compact: bool) -> str:
+ width = 6 if compact else 8
+ samples = list(values or [])[-width * (2 if glyphs == "braille" else 1):]
+ valid = [value for value in samples if value is not None]
+ label = "Output" if compact else "Output trend"
+ if len(valid) < 2 or samples[-1] is None:
+ return f"{label} --"
+ low, high = min(valid), max(valid)
+ scaled = [None if value is None else
+ 0 if high == 0 else 50 if high == low else 100 * (value - low) / (high - low)
+ for value in samples]
+ graph = _spark(scaled, glyphs, width)
+ span = f"{low:.3g}" if high == low else f"{low:.3g}-{high:.3g}"
+ return f"{label} {graph} {span} tok/s"
+
+
+def _work_trend(values: Any, glyphs: str, label: str, unit: str, digits: int = 0) -> str | None:
+ """Show the range of displayed samples; never turn missing work into zero."""
+ width = 8
+ samples = list(values or [])[-width * (2 if glyphs == "braille" else 1):]
+ valid = [value for value in samples if value is not None]
+ if len(valid) < 2 or samples[-1] is None:
+ return None
+ low, high = min(valid), max(valid)
+ scaled = [None if value is None else
+ 0 if high == 0 else 50 if high == low else 100 * (value - low) / (high - low)
+ for value in samples]
+ span = number(low, "", digits)
+ if high != low:
+ span += "-" + number(high, "", digits)
+ return f"{label} {_spark(scaled, glyphs, width)} {span}{unit}"
+
+
+def _panel(lines: list[str], title: str, accent: str, *, color: bool) -> Panel:
+ body = Text("\n".join(lines), no_wrap=True, overflow="crop")
+ if color:
+ body.highlight_regex(r"\b(?:READY|LIVE|GENERATING|READING)\b", accent)
+ body.highlight_regex(r"\b(?:STALE|FROZEN|QUEUED|DRAINING)\b", "yellow")
+ body.highlight_regex(r"\b(?:DISCONNECTED|INCOMPATIBLE|REJECTED|AUTH REQUIRED)\b", "red")
+ body.highlight_regex(r"[\u2800-\u28ff▁▂▃▄▅▆▇█]+", accent)
+ return Panel(body, title=Text(title, style=f"bold {accent}" if color else "bold"),
+ border_style="dim" if color else "", box=box.ROUNDED, padding=(0, 1))
+
+
+def _columns(left: list[Panel], right: list[Panel]) -> Table:
+ """Keep the YASD-style metric stack beside hardware and request activity."""
+ grid = Table.grid(expand=True, padding=(0, 1))
+ grid.add_column(ratio=3)
+ grid.add_column(ratio=4)
+ grid.add_row(Group(*left), Group(*right))
+ return grid
+
+
+def _state(snapshot: dict, connection_state: str, frozen: bool) -> tuple[str, bool]:
+ age = _age(snapshot)
+ telemetry = (snapshot.get("quality") or {}).get("telemetry")
+ state = ("NO TELEMETRY" if telemetry == "unavailable" and connection_state == "connected" else
+ {"connected": "LIVE", "connecting": "CONNECTING", "stale": "STALE",
+ "disconnected": "DISCONNECTED", "auth_required": "AUTH REQUIRED",
+ "incompatible": "INCOMPATIBLE", "telemetry_unavailable": "NO TELEMETRY"}
+ .get(connection_state, "STALE"))
+ if state == "LIVE" and (age is None or age > 5 or age < -5):
+ state = "STALE"
+ if state == "LIVE" and (snapshot.get("model") or {}).get("loaded") is False:
+ state = "SLEEPING"
+ return (f"FROZEN / {state}" if frozen else state), state == "LIVE"
+
+
+def _prompt_progress(work: dict, compact: bool, glyphs: str) -> str | None:
+ for row in work.get("requests") or []:
+ if row.get("state") != "reading":
+ continue
+ done, total = row.get("prompt_read"), row.get("prompt_tokens")
+ if any(not isinstance(value, (int, float)) or isinstance(value, bool) or
+ not math.isfinite(value) for value in (done, total)) or total <= 0 or done < 0:
+ continue
+ size = 6 if compact else 8
+ filled = min(size, max(0, round(done / total * size)))
+ full, empty = ("#", ".") if glyphs == "ascii" else ("█", "░")
+ prefix = "Read" if compact else f"Reading {safe(row.get('id'), 11)}"
+ return f"{prefix} {number(done)}/{number(total)} [{full * filled}{empty * (size - filled)}]"
+ return None
+
+
+def _age(snapshot: dict) -> float | None:
+ sampled = snapshot.get("sampled_at")
+ if not isinstance(sampled, (int, float)) or isinstance(sampled, bool) or not math.isfinite(sampled):
+ return None
+ return time.time() - sampled
+
+
+def _gib(value: Any) -> str:
+ if not isinstance(value, (int, float)) or isinstance(value, bool):
+ return "--"
+ return number(value / 2**30, "", 1)
+
+
+def _groups(work: dict, compact: bool, glyphs: str) -> list[str]:
+ occupancy = group_occupancy(work)
+ if occupancy is None:
+ return ["Group occupancy --"]
+ owner_sets: dict[int, set[int | None]] = {}
+ for row in complete_slots(work) or []:
+ group = row.get("group")
+ if type(group) is int:
+ replica = row.get("replica")
+ owner_sets.setdefault(group, set()).add(replica if type(replica) is int else None)
+ owners = {group: next(iter(values)) for group, values in owner_sets.items() if len(values) == 1}
+ def label(group: int) -> str:
+ replica = owners.get(group)
+ return f"R{replica} G{group}" if replica is not None else f"G{group}"
+ labels = [f"{label(group)} {busy}/{total}"
+ for group, (busy, total) in sorted(occupancy.items())]
+ if compact:
+ lines = [" ".join(labels[:2]), " ".join(labels[2:4])] if len(labels) > 2 else [" ".join(labels)]
+ if len(labels) > 4:
+ lines.append(f"+{len(labels) - 4} groups; press 2")
+ return lines
+ full, empty = ("#", ".") if glyphs == "ascii" else ("█", "░")
+ lines = ["Pipeline groups · occupied slots" if glyphs != "ascii" else "Pipeline groups / occupied slots"]
+ for group, (busy, total) in sorted(occupancy.items())[:5]:
+ bar = full * min(busy, 8) + empty * min(max(0, total - busy), 8)
+ lines.append(f"{label(group):<6} {bar} {busy}/{total} slots")
+ if len(occupancy) > 5:
+ lines.append(f"+{len(occupancy) - 5} groups; press 2")
+ return lines
+
+
+def _replica_batch_line(work: dict, compact: bool) -> str:
+ """Each replica reports its own batch window; there is no cross-replica average."""
+ rows = sorted(work.get("replica_batches") or [], key=lambda row: row["replica"])
+ if not rows:
+ return "Batch rows -- across replicas" if compact else "Rows/window -- across replicas"
+ shown = rows[:2]
+ if compact:
+ text = "Proc/win " + " ".join(
+ f"R{row['replica']} {number(_current_batch_value(row, 'effective_rows_window'), '', 1)}" for row in shown)
+ else:
+ text = "Rows/win p/a " + " ".join(
+ f"R{row['replica']} {number(_current_batch_value(row, 'effective_rows_window'), '', 1)}/"
+ f"{number(_current_batch_value(row, 'batch_active_rows_window'), '', 1)}" for row in shown)
+ return text + (f" +{len(rows) - 2}" if len(rows) > 2 else "")
+
+
+def _slot_phases(work: dict, compact: bool) -> str | None:
+ """Summarize slot states only when the complete effective slot set is present."""
+ slots = complete_slots(work)
+ if slots is None:
+ return None
+ counts = {"reading": 0, "decoding": 0, "idle": 0}
+ for row in slots:
+ counts[row["state"]] += 1
+ prefix = "Slot phases" if not compact else "Phases"
+ return (f"{prefix} read {counts['reading']} decode {counts['decoding']} "
+ f"idle {counts['idle']}")
+
+
+def _hardware(snapshot: dict, history: MonitorHistory, glyphs: str, compact: bool) -> list[str]:
+ devices = snapshot.get("devices") or []
+ topology = snapshot.get("topology") or {}
+ selected = [index for index in topology.get("selected_devices") or []
+ if type(index) is int and index >= 0]
+ selected = list(dict.fromkeys(selected))
+ if selected:
+ reported = {}
+ ambiguous = set()
+ for row in devices:
+ index = row.get("index")
+ if type(index) is not int or index < 0:
+ continue
+ if index in reported:
+ ambiguous.add(index)
+ reported[index] = row
+ rows = [(reported[index], True) if index in reported and index not in ambiguous
+ else ({"index": index}, False) for index in selected]
+ else:
+ rows = [(row, True) for row in devices]
+ if not rows:
+ return ["Per-device readings unavailable"]
+ stages = (topology.get("stages") or []) if topology.get("resolved") is True else []
+ mapped = {row.get("device_index"): row.get("stage") for row in stages}
+ replica_map = {device: row.get("replica") for row in topology.get("replica_devices") or []
+ for device in row.get("devices") or []}
+ replica_stages: dict[int, list[tuple[int, int]]] = {}
+ for entry in topology.get("replica_stages") or []:
+ replica = entry.get("replica")
+ for stage in entry.get("stages") or []:
+ device = stage.get("device_index")
+ stage_id = stage.get("stage")
+ if (type(device) is int and type(replica) is int and type(stage_id) is int and
+ 0 <= replica < 16 and 0 <= stage_id < 16 and replica_map.get(device) == replica):
+ replica_stages.setdefault(device, []).append((replica, stage_id))
+ lines = []
+ for row, sensor_present in rows[:4]:
+ index = row.get("index")
+ label = f"GPU {number(index)}"
+ local_stages = replica_stages.get(index) or []
+ stage = (f"R{local_stages[0][0]}/S{local_stages[0][1]}" if len(local_stages) == 1 else
+ f"R{number(replica_map[index])}" if index in replica_map else
+ f"S{number(mapped[index])}" if index in mapped else "S--")
+ memory = field(f"{_gib(row.get('mem_used'))}/{_gib(row.get('mem_total'))}G", 13)
+ graph = (_spark(history.device_util.get(index), glyphs, 6 if compact else 8)
+ if sensor_present else "--")
+ vram_graph = (_spark(history.device_vram.get(index), glyphs, 6)
+ if sensor_present else "--")
+ if compact:
+ lines.append(f"{label:<5} {stage:<5} {memory:<11} {number(row.get('util'), '%'):>4} {graph}")
+ else:
+ lines.append(f"{label:<5} {stage:<5} {field(row.get('name'), 18)} {memory} vram {vram_graph}")
+ lines.append(f" load {number(row.get('util'), '%'):>4} temp {number(row.get('temp'), 'C'):>4} "
+ f"power {number(row.get('power'), 'W'):>5} {graph}")
+ if len(rows) > 4:
+ lines.append(f"+{len(rows) - 4} {'selected ' if selected else ''}devices; press 5 for all")
+ return lines
+
+
+def _request_lines(snapshot: dict, compact: bool, filter_text: str, *, tall: bool = False) -> list[str]:
+ work = snapshot.get("work") or {}
+ needle = filter_text.lower()
+ live = [row for row in (work.get("requests") or []) if not needle or
+ needle in (safe(row.get("id")) + safe(row.get("state"))).lower()]
+ lines = []
+ limit = 2 if compact else 12 if tall else 4
+ queued = [row for row in live if row.get("state") == "queued"]
+ admitted = [row for row in live if row.get("slot") is None and row.get("state") != "queued"]
+ running = [row for row in live if row.get("slot") is not None]
+ preferred = ((queued[:1] + running[:1]) if compact else
+ (queued[:2] + admitted[:1] + running[:1]))
+ chosen = []
+ seen = set()
+ for row in preferred + live:
+ if id(row) not in seen:
+ chosen.append(row)
+ seen.add(id(row))
+ if len(chosen) == limit:
+ break
+ for row in chosen:
+ wait = _queue_wait(row, snapshot.get("sampled_at"))
+ state = safe(row.get("state"), 9)
+ state_column = field(row.get("state"), 7 if compact else 9)
+ work_label = (f"wait {number(wait, 's', 1)}" if state == "queued" else
+ "awaiting slot" if row.get("slot") is None else
+ f"read {number(row.get('prompt_read'))}" if state == "reading" else
+ f"out {number(row.get('generated'))}")
+ replica = f"r{row['replica']} " if type(row.get("replica")) is int else ""
+ if compact:
+ if state == "queued":
+ lines.append(f"{field(row.get('id'), 9)} {state_column} {work_label}")
+ else:
+ lines.append(f"{field(row.get('id'), 9)} {state_column} "
+ f"{replica}s{number(row.get('slot'))} g{number(row.get('group'))} {work_label}")
+ else:
+ lines.append(f"{field(row.get('id'), 12)} {state_column} "
+ f"{replica}s{number(row.get('slot'))} g{number(row.get('group'))} {work_label}")
+ if len(live) > limit:
+ lines.append(f"+{len(live) - limit} more; press 3 for all")
+ if not lines:
+ slots = [row for row in work.get("slots") or [] if row.get("state") != "idle"]
+ if slots:
+ lines = [f"{('R' + str(row['replica']) + ' ') if type(row.get('replica')) is int else ''}"
+ f"Slot {number(row.get('slot'))} G{number(row.get('group'))} "
+ f"{safe(row.get('state'), 12)} {number(row.get('generated'))} out"
+ for row in slots[:limit]]
+ lines.insert(0, "Request identities unavailable")
+ else:
+ lines = ["No active requests"]
+ return lines
+
+
+def _activity(snapshot: dict, compact: bool, filter_text: str) -> list[str]:
+ activity = snapshot.get("activity") or {}
+ if not activity.get("available"):
+ return ["Request activity unavailable"]
+ notice = activity_continuity_notice(snapshot)
+ needle = filter_text.lower()
+ rows = [row for row in activity.get("events") or [] if isinstance(row, dict) and
+ (not needle or needle in (safe(row.get("event")) + safe(row.get("request_id"))).lower())]
+ if not rows:
+ return ([notice] if notice else []) + ["No matching transitions" if needle else "No recent transitions"]
+ if compact:
+ return ([notice] if notice else []) + [f"{field(row.get('request_id'), 10)} "
+ f"{safe(row.get('event'), 18)}" for row in rows[-(1 if notice else 2):]]
+ return ([notice] if notice else []) + [activity_label(row, 48) for row in rows[-(3 if notice else 4):]]
+
+
+_DIGITS = {
+ "0": (" ███ ", "█ █", "█ █", "█ █", " ███ "),
+ "1": (" █ ", " ██ ", " █ ", " █ ", " ███ "),
+ "2": (" ███ ", "█ █", " █ ", " █ ", "█████"),
+ "3": ("████ ", " █", " ███ ", " █", "████ "),
+ "4": ("█ █", "█ █", "█████", " █", " █"),
+ "5": ("█████", "█ ", "████ ", " █", "████ "),
+ "6": (" ███ ", "█ ", "████ ", "█ █", " ███ "),
+ "7": ("█████", " █", " █ ", " █ ", " █ "),
+ "8": (" ███ ", "█ █", " ███ ", "█ █", " ███ "),
+ "9": (" ███ ", "█ █", " ████", " █", " ███ "),
+ ".": (" ", " ", " ", "██", "██"),
+ ",": (" ", " ", " ", " ██", " █ "),
+ "-": (" ", " ", "█████", " ", " "),
+}
+
+
+def _big_rate(value: Any, color: str, glyphs: str) -> list[Text]:
+ """Legible five-row numerals; the exact value is repeated in plain text."""
+ label = number(value, "", 1) if value is not None else "--"
+ if glyphs == "ascii":
+ return [Text(label + " tok/s", style=f"bold {color}")]
+ if len(label) > 9:
+ return [Text(label + " tok/s", style=f"bold {color}")]
+ return [Text(" ".join(_DIGITS.get(char, (" ",) * 5)[row]
+ for char in label), style=f"bold {color}", no_wrap=True)
+ for row in range(5)]
+
+
+def _meter(value: Any, total: Any, size: int, glyphs: str) -> str:
+ valid = (all(isinstance(item, (int, float)) and not isinstance(item, bool) and
+ math.isfinite(item) for item in (value, total)) and total > 0 and 0 <= value <= total)
+ if not valid:
+ return "[" + ("?" * size) + "]"
+ filled = max(0, min(size, round(value / total * size)))
+ on, off = ("#", ".") if glyphs == "ascii" else ("█", "░")
+ return "[" + on * filled + off * (size - filled) + "]"
+
+
+def _visual_panel(lines: list[Text], title: str, accent: str, color: bool,
+ height: int | None = None) -> Panel:
+ return Panel(Group(*lines), title=Text(title, style=f"bold {accent}" if color else "bold"),
+ border_style="dim" if color else "", box=box.SQUARE, padding=(0, 1),
+ height=height)
+
+
+def _visual_pair(left: Panel, right: Panel, left_ratio: int = 3, right_ratio: int = 4) -> Table:
+ grid = Table.grid(expand=True, padding=(0, 1))
+ grid.add_column(ratio=left_ratio)
+ grid.add_column(ratio=right_ratio)
+ grid.add_row(left, right)
+ return grid
+
+
+def _visual_overview(snapshot: dict, history: MonitorHistory, *, width: int, height: int,
+ header: Panel, footer: Text, live: bool, glyphs: str, color: bool,
+ theme: str, filter_text: str) -> Group:
+ """Wide monitor: rate, cards, context, slot concurrency and live requests."""
+ cyan = ("#087b9a" if theme == "light" else "#22d3ee") if color else "default"
+ green = ("#0c8a60" if theme == "light" else "#34d399") if color else "default"
+ amber = ("#946000" if theme == "light" else "#fbbf24") if color else "default"
+ violet = ("#7842af" if theme == "light" else "#a78bfa") if color else "default"
+ dim = "dim" if color else ""
+ model, work, rates = (snapshot.get("model") or {}, snapshot.get("work") or {},
+ snapshot.get("rates") or {})
+ topology = snapshot.get("topology") or {}
+ slots = complete_slots(work)
+ output = rates.get("aggregate_output_tok_s") if live else None
+ prefill = rates.get("prefill_tok_s") if live else None
+ answer = rates.get("answer_tok_s") if live else None
+ hero = [Text(f"{safe(model.get('id'), 35)} "
+ f"{number(work.get('active'))} active · {number(work.get('queued'))} pre-admit",
+ style=dim, no_wrap=True)]
+ hero.extend(_big_rate(output, cyan, glyphs))
+ hero.append(Text(f"{number(output, '', 1)} tok/s · ALL REQUESTS",
+ style=f"bold {cyan}" if color else "bold"))
+ hero.append(Text(f"PROMPT {number(prefill, '', 1)} tok/s "
+ f"ANSWER {number(answer, '', 1)} tok/s", no_wrap=True))
+ hero.append(Text(_output_trend(history.output_rate if live else (), glyphs, False), style=dim))
+ hero.append(Text(f"Prefill {_rate_spark(history.prefill_rate if live else (), glyphs)} "
+ f"Answer {_rate_spark(history.answer_rate if live else (), glyphs)}", style=dim))
+ while len(hero) < 9:
+ hero.append(Text(""))
+
+ devices = snapshot.get("devices") or []
+ selected = [index for index in topology.get("selected_devices") or [] if type(index) is int and index >= 0]
+ selected = list(dict.fromkeys(selected))
+ reported: dict[int, dict] = {}
+ ambiguous: set[int] = set()
+ for row in devices:
+ index = row.get("index")
+ if type(index) is int and index >= 0:
+ if index in reported:
+ ambiguous.add(index)
+ reported[index] = row
+ indices = selected or list(reported)
+ gpu_lines: list[Text] = []
+ for index in indices[:4]:
+ row = reported.get(index, {}) if index not in ambiguous else {}
+ stage = _device_role(index, topology)
+ util = row.get("util") if live else None
+ used = row.get("mem_used") if live else None
+ total = row.get("mem_total") if live else None
+ gpu_lines.append(Text(f"GPU {index} {stage:<5} {field(row.get('name'), 19)} "
+ f"load {number(util, '%'):>4} "
+ f"{number(row.get('power') if live else None, 'W'):>5} "
+ f"{number(row.get('temp') if live else None, 'C'):>4}", no_wrap=True))
+ gpu_lines.append(Text(f" {_meter(util, 100, 16, glyphs)} "
+ f"VRAM {_meter(used, total, 12, glyphs)} "
+ f"{_gib(used)}/{_gib(total)}G "
+ f"{_spark(history.device_util.get(index) if live else (), glyphs, 6)}",
+ style=green if color else "", no_wrap=True))
+ if not gpu_lines:
+ gpu_lines.append(Text("Per-device sensors unavailable", style=dim))
+ if len(indices) > 4:
+ gpu_lines.append(Text(f"+{len(indices) - 4} selected cards · press 5", style=dim))
+ while len(gpu_lines) < 9:
+ gpu_lines.append(Text(""))
+
+ context = model.get("context")
+ held = [row.get("held_tokens") for row in (slots or []) if live
+ if row.get("state") != "idle" and
+ isinstance(row.get("held_tokens"), (int, float)) and
+ not isinstance(row.get("held_tokens"), bool) and
+ math.isfinite(row["held_tokens"]) and row["held_tokens"] >= 0]
+ # A complete all-idle slot map establishes zero active context. An active
+ # slot with a missing held-token reading still remains unavailable.
+ max_held = (max(held) if held else
+ 0 if live and slots is not None and all(row.get("state") == "idle" for row in slots)
+ else None)
+ context_lines = [Text(f"CAPACITY {number(context)} tokens / slot "
+ f"MAX ACTIVE HELD {number(max_held)}", no_wrap=True),
+ Text(_meter(max_held, context, max(12, min(80, width - 8)), glyphs),
+ style=violet if color else "", no_wrap=True),
+ Text(f"Slots {number(work.get('occupied_slots'))}/{number(work.get('slots_effective'))} "
+ f"occupied · wait {number(work.get('waiting'))} · "
+ f"queue {number(work.get('queued'))} · "
+ f"rows/window {number(_current_batch_value(work, 'effective_rows_window'), '', 1)} "
+ f"processed / {number(_current_batch_value(work, 'batch_active_rows_window'), '', 1)} active",
+ no_wrap=True)]
+ if work.get("replica_batches"):
+ context_lines.append(Text(_replica_batch_line(work, False), style=dim))
+ else:
+ context_lines.append(Text("Held is the largest active slot cache; groups are not GPU lanes.", style=dim))
+
+ slot_lines: list[Text] = []
+ if slots is None:
+ slot_lines.append(Text("Complete slot map unavailable", style=dim))
+ else:
+ grouped: dict[tuple[int | None, int | None], list[dict]] = {}
+ for row in slots:
+ key = (row.get("replica") if type(row.get("replica")) is int else None,
+ row.get("group") if type(row.get("group")) is int else None)
+ grouped.setdefault(key, []).append(row)
+ for (replica, group), rows in sorted(grouped.items(), key=lambda item: (
+ -1 if item[0][0] is None else item[0][0],
+ -1 if item[0][1] is None else item[0][1]))[:10]:
+ label = f"R{replica} " if replica is not None else ""
+ label += f"G{group}" if group is not None else "G--"
+ line = Text(f"{label:<7} ", no_wrap=True)
+ for row in rows[:8]:
+ state = {"reading": "P", "decoding": "D", "idle": "·"}.get(row.get("state"), "?")
+ tint = (amber if state == "P" else green if state == "D" else dim)
+ line.append(f"[{number(row.get('slot')):>2} {state}] ", style=tint if color else "")
+ if len(rows) > 8:
+ line.append(f"+{len(rows) - 8}", style=dim)
+ slot_lines.append(line)
+ if len(grouped) > 10:
+ slot_lines.append(Text(f"+{len(grouped) - 10} groups · press 2", style=dim))
+ slot_lines.insert(0, Text("P prefill D decode · idle | engine slots", style=dim))
+ slot_lines.append(Text(f"{_slot_phases(work, False) or 'Slot phases unavailable'}", style=dim))
+ slot_lines.append(Text(_replica_batch_line(work, False) if work.get("replica_batches") else
+ f"Oldest queue {number(work.get('oldest_queue_s'), 's', 1)} · "
+ f"admission {number(work.get('admission_reserved'))}/"
+ f"{number(work.get('admission_limit'))}", style=dim))
+ active_slots = [row for row in slots or [] if row.get("state") != "idle"]
+ if active_slots:
+ slot_lines.append(Text("ACTIVE CONTEXTS · held / capacity", style=dim))
+ for row in active_slots[:max(1, min(8, height - 32))]:
+ held_tokens = row.get("held_tokens") if live else None
+ slot_lines.append(Text(f"S{number(row.get('slot')):<3} "
+ f"{_meter(held_tokens, context, 10, glyphs)} "
+ f"{number(held_tokens)}/{number(context)} tokens "
+ f"{number(row.get('tok_s') if live else None, '', 1)} t/s",
+ style=green if color else "", no_wrap=True))
+ if len(active_slots) > max(1, min(8, height - 32)):
+ slot_lines.append(Text(f"+{len(active_slots) - max(1, min(8, height - 32))} slots · press 2",
+ style=dim))
+
+ needle = filter_text.lower()
+ requests = [row for row in work.get("requests") or [] if not needle or
+ needle in (safe(row.get("id")) + safe(row.get("state"))).lower()]
+ requests.sort(key=lambda row: (row.get("state") != "queued", row.get("slot") is None,
+ row.get("slot") if type(row.get("slot")) is int else 999))
+ slot_rates = {(row.get("slot"), row.get("request_id")): row.get("tok_s")
+ for row in slots or [] if row.get("request_id") is not None}
+ narrow_requests = width < 138
+ req_lines = [Text("ID STATE SLOT PROMPT OUT t/s 1ST ENGINE" if narrow_requests else
+ "ID STATE ROUTE PROMPT OUT SLOT t/s 1ST ENGINE",
+ style=dim)]
+ limit = max(5, min(15, height - 28))
+ for row in requests[:limit]:
+ route = (f"R{row['replica']}/" if type(row.get("replica")) is int else "")
+ route += (f"S{row['slot']}" if type(row.get("slot")) is int else "--")
+ prompt_read = row.get("prompt_read")
+ prompt_total = row.get("prompt_tokens")
+ prompt_label = (f"{number(prompt_read)}/{number(prompt_total)}" if row.get("state") == "reading" else
+ number(prompt_total))
+ first = number(row.get("first_engine_token_s"), "s", 2)
+ if row.get("state") == "queued":
+ first = f"wait {number(_queue_wait(row, snapshot.get('sampled_at')), 's', 1)}"
+ slot_rate = slot_rates.get((row.get("slot"), row.get("id"))) if live else None
+ state = safe(row.get("state"), 10)
+ tint = amber if state == "reading" else green if state == "decoding" else violet
+ if narrow_requests:
+ request_text = (f"{field(row.get('id'), 10)} {state:<8} {route:<6} "
+ f"{prompt_label:<9} {number(row.get('generated')):>4} "
+ f"{number(slot_rate, '', 1):>5} {first}")
+ else:
+ request_text = (f"{field(row.get('id'), 12)} {state:<10} {route:<9} "
+ f"{prompt_label:<11} {number(row.get('generated')):>4} "
+ f"{number(slot_rate, '', 1):>7} {first}")
+ req_lines.append(Text(request_text, style=tint if color else "", no_wrap=True))
+ if len(requests) > limit:
+ req_lines.append(Text(f"+{len(requests) - limit} more · press 3", style=dim))
+ if not requests:
+ req_lines.append(Text("No active requests" if work.get("requests") is not None else
+ "Request identities unavailable", style=dim))
+ if work.get("requests_omitted"):
+ req_lines.append(Text(f"{number(work.get('requests_omitted'))} additional rows omitted by server", style=dim))
+ lower_rows = max(len(slot_lines), len(req_lines))
+ slot_lines.extend(Text("") for _ in range(lower_rows - len(slot_lines)))
+ req_lines.extend(Text("") for _ in range(lower_rows - len(req_lines)))
+
+ top = _visual_pair(_visual_panel(hero, "THROUGHPUT", cyan, color),
+ _visual_panel(gpu_lines, f"GPUS · {len(indices)} "
+ f"{'selected' if selected else 'reported'}", green, color))
+ middle = _visual_panel(context_lines, "CONTEXT / BATCHING", violet, color)
+ lower_height = max(lower_rows + 2, height - 23)
+ lower = _visual_pair(_visual_panel(slot_lines, "PARALLEL SLOTS", amber, color,
+ height=lower_height),
+ _visual_panel(req_lines, f"REQUESTS · {len(requests)} visible", green, color,
+ height=lower_height), 3, 4)
+ return Group(header, top, middle, lower, footer)
+
+
+def _rate_spark(values: Any, glyphs: str) -> str:
+ samples = list(values or [])[-(16 if glyphs == "braille" else 8):]
+ valid = [value for value in samples if value is not None]
+ if len(valid) < 2 or samples[-1] is None:
+ return "--"
+ low, high = min(valid), max(valid)
+ scaled = [None if value is None else (50 if high == low else 100 * (value - low) / (high - low))
+ for value in samples]
+ return _spark(scaled, glyphs, 8)
+
+
+def _device_role(index: int, topology: dict) -> str:
+ for replica in topology.get("replica_devices") or []:
+ if index in replica.get("devices", []):
+ return f"R{number(replica.get('replica'))}"
+ if topology.get("resolved"):
+ for stage in topology.get("stages") or []:
+ if stage.get("device_index") == index:
+ return f"S{number(stage.get('stage'))}"
+ return ""
+
+
+def render_dashboard(snapshot: dict, *, width: int, height: int, history: MonitorHistory,
+ connection: str = "", connection_state: str = "connected", frozen: bool = False,
+ filter_text: str = "", glyphs: str = "ascii", color: bool = True,
+ theme: str = "dark") -> Group:
+ """Compose the primary one-screen monitor at standard terminal sizes.
+
+ Smaller terminals retain the existing compact text renderer in MonitorApp.
+ """
+ compact = width < 100 or height < 27
+ accent = ("#0c8a60" if theme == "light" else "#34d399") if color else "default"
+ danger = ("#b01a2e" if theme == "light" else "#ff8a98") if color else "default"
+ danger_border = ("#e0283f" if theme == "light" else "#ff5a6e") if color else "default"
+ model, instance = snapshot.get("model") or {}, snapshot.get("instance") or {}
+ work, rates = snapshot.get("work") or {}, snapshot.get("rates") or {}
+ topology = snapshot.get("topology") or {}
+ recent = snapshot.get("recent") or []
+ state, live = _state(snapshot, connection_state, frozen)
+ model_state = ("DRAINING" if instance.get("state") == "draining" else
+ "READY" if model.get("loaded") is True else
+ "NO MODEL LOADED" if model.get("loaded") is False else "UNKNOWN")
+ heading = Text()
+ heading.append("STRATA / MONITOR", style=f"bold {accent}")
+ heading.append(" ")
+ heading.append(state, style=(f"bold {accent}" if state == "LIVE" else
+ "bold yellow" if state in ("SLEEPING", "STALE", "CONNECTING") else
+ f"bold {danger}" if state in ("DISCONNECTED", "AUTH REQUIRED", "INCOMPATIBLE") else
+ "bold"))
+ heading.append(f" {safe(connection, max(0, width - 45))}")
+ blocked = connection_state in ("disconnected", "auth_required", "incompatible")
+ header = Panel(heading, box=box.ROUNDED,
+ border_style=danger_border if blocked else accent, padding=(0, 1))
+
+ if connection_state in ("connecting", "disconnected", "auth_required", "incompatible"):
+ title, message, action = {
+ "connecting": ("CONNECTING", "Waiting for the first Strata telemetry snapshot.",
+ "The monitor will update automatically."),
+ "disconnected": ("CONNECTION LOST", "The Strata server is not responding.",
+ "Retrying automatically; press r to retry now."),
+ "auth_required": ("AUTHORIZATION REQUIRED", "The telemetry credential was rejected.",
+ "Update the saved monitor connection, then press r."),
+ "incompatible": ("INCOMPATIBLE SERVER", "This telemetry schema is unsupported.",
+ "Connect to a compatible Strata server, then press r."),
+ }[connection_state]
+ age = _age(snapshot)
+ last_seen = (f"Last snapshot {number(age, 's', 1)} ago" if age is not None and age >= 0 else
+ "No telemetry snapshot available")
+ lines = Group(Text(title, style=f"bold {danger}" if blocked else f"bold {accent}"),
+ Text(message), Text(action, style="dim"), Text(last_seen, style="dim"))
+ panel = Panel(Align.center(lines, vertical="middle"),
+ title=Text("CONNECTION", style=f"bold {danger}" if blocked else f"bold {accent}"),
+ border_style=danger_border if blocked else "dim", box=box.ROUNDED,
+ height=max(8, height - 4))
+ return Group(header, panel, Text("r Retry q Detach 1-6 Views", style="dim"))
+
+ model_name = safe(model.get("id"), 80)
+ if compact and display_width(model_name) > 19:
+ model_name = safe(model_name, 18) + "…"
+ else:
+ model_name = safe(model_name, 19 if compact else 35)
+ serving = [f"Model {model_name}",
+ (f"State {model_state} {number(work.get('active'))} active" if compact else
+ f"State {model_state} | {number(work.get('active'))} in flight"),
+ (f"Queue {number(work.get('waiting'))} engine {number(work.get('queued'))} pre-admit" if compact else
+ f"Queue {number(work.get('waiting'))} engine / {number(work.get('queued'))} pre-admit")]
+ progress = _prompt_progress(work, compact, glyphs) if live else None
+ if progress:
+ serving.append(progress)
+ telemetry_unavailable = (snapshot.get("quality") or {}).get("telemetry") == "unavailable"
+ answer = number(rates.get('answer_tok_s') if live else None, '', 1)
+ prompt = number(rates.get('prefill_tok_s') if live else None, '', 1)
+ aggregate = number(rates.get('aggregate_output_tok_s') if live else None, ' tok/s', 1)
+ performance = ([f"P {prompt} A {answer} tok/s", f"All {aggregate} server"] if compact else
+ [f"Prompt {prompt} Answer {answer} tok/s", f"Aggregate {aggregate} server"])
+ performance.append(_output_trend(history.output_rate if live else (), glyphs, compact))
+
+ batch = [f"Slots {number(work.get('occupied_slots'))}/{number(work.get('slots_effective'))} "
+ f"req {number(work.get('slots_requested'))} groups {number(work.get('groups'))}",
+ f"Rows/win {number(_current_batch_value(work, 'effective_rows_window'), '', 1)} processed "
+ f"{number(_current_batch_value(work, 'batch_active_rows_window'), '', 1)} active",
+ f"Admit {number(work.get('admission_reserved'))}/{number(work.get('admission_limit'))} "
+ f"oldest {number(work.get('oldest_queue_s'), 's', 1)} "
+ f"reject {number(work.get('admission_rejected'))}"]
+ replica_ids = {row.get("replica") for row in complete_slots(work) or []
+ if type(row.get("replica")) is int}
+ replica_count = max(len(replica_ids), len(topology.get("replica_devices") or []),
+ len(work.get("replica_batches") or []))
+ if replica_count:
+ batch[0] = (f"Slots {number(work.get('occupied_slots'))}/{number(work.get('slots_effective'))} "
+ f"| requested {number(work.get('slots_requested'))} | replicas {replica_count}")
+ batch[1] = _replica_batch_line(work, compact=False)
+ if compact:
+ batch[0] = (f"Slots {number(work.get('occupied_slots'))}/{number(work.get('slots_effective'))} "
+ f"{'replicas ' + str(replica_count) if replica_count else 'groups ' + number(work.get('groups'))}")
+ batch[1] = (_replica_batch_line(work, compact=True) if replica_count else
+ f"Batch rows {number(_current_batch_value(work, 'effective_rows_window'), '', 1)} "
+ f"active {number(_current_batch_value(work, 'batch_active_rows_window'), '', 1)}")
+ batch[2] = (f"Admit {number(work.get('admission_reserved'))}/{number(work.get('admission_limit'))} "
+ f"oldest {number(work.get('oldest_queue_s'), 's', 1)}")
+ phases = _slot_phases(work, compact)
+ if phases:
+ batch.append(phases.replace("Phases ", "") if compact else phases)
+ batch += _groups(work, compact, glyphs)
+ if not compact:
+ stages = (work.get("stage_in_flight") or []) if _current_sample(work, "stage_sample_age_s") else []
+ replica_samples = work.get("replica_stage_samples") or []
+ if replica_samples:
+ for row in replica_samples[:2]:
+ samples = (row.get("stage_in_flight") or []) if _current_sample(row, "stage_sample_age_s") else []
+ batch.append(f"Host span R{row['replica']} " + (" ".join(
+ f"S{number(stage.get('stage'))} {number(stage.get('percent'), '%')}"
+ for stage in samples) + f" age {number(row.get('stage_sample_age_s'), 's', 1)}"
+ if samples else "--"))
+ if len(replica_samples) > 2:
+ batch.append(f"+{len(replica_samples) - 2} replicas; see Engine")
+ else:
+ batch.append(("Host span " + " ".join(f"S{number(row.get('stage'))}/"
+ f"{number(row.get('percent'), '%')}" for row in stages)) if stages else
+ "Stage host span --")
+ if live:
+ if replica_count:
+ trends = [_work_trend(history.replica_batch_rows.get(replica), glyphs,
+ f"R{replica} rows", "/win", 1)
+ for replica in sorted(history.replica_batch_rows)[:2]]
+ else:
+ trends = [_work_trend(history.batch_rows, glyphs, "Rows trend", "/win", 1),
+ _work_trend(history.pre_admit, glyphs, "Pre-admit", " req")]
+ detail_rows = 10 if width >= 100 and height >= 40 else 0
+ used_rows = (3 + 1 + len(serving) + 2 + len(performance) + 2 +
+ len(batch) + 2 + detail_rows)
+ batch.extend([trend for trend in trends if trend][:max(0, height + 1 - used_rows)])
+
+ hardware = _hardware(snapshot, history, glyphs, compact)
+ ram = snapshot.get("ram") or {}
+ if isinstance(ram.get("used"), (int, float)) and isinstance(ram.get("total"), (int, float)):
+ hardware.append(f"RAM {_gib(ram['used'])}/{_gib(ram['total'])} GiB")
+ hardware.append(("Each request stays in one replica" if replica_count else "Groups are not GPU lanes") if compact else
+ ("Per-card sensors; replicas serve independently" if replica_count else
+ "Per-card sensors; requests cross all stages"))
+ requests = _request_lines(snapshot, compact, filter_text, tall=height >= 40)
+ activity = _activity(snapshot, compact, filter_text)
+ age = _age(snapshot)
+ footer = Text((f"1 Over 2 Serve 3 Reqs 4 Engine 5 GPU 6 Logs age {number(age, 's', 1)}"
+ if compact else
+ f"1 Overview 2 Serving 3 Requests 4 Engine 5 Hardware 6 Logs"
+ f" age {number(age, 's', 1)}"), style="dim")
+ if width >= 126 and height >= 34:
+ return _visual_overview(snapshot, history, width=width, height=height,
+ header=header, footer=footer, live=live, glyphs=glyphs,
+ color=color, theme=theme, filter_text=filter_text)
+ left_sections = [(serving, "SERVING"), (performance, "PERFORMANCE"),
+ (batch, "BATCHING / PARALLEL")]
+ if width >= 100 and height >= 40:
+ totals = snapshot.get("totals") or {}
+ left_sections.extend([
+ ([f"Completed {number(totals.get('requests'))} [server lifetime]",
+ f"Prompt {number(totals.get('prompt_tokens'))} tokens",
+ f"Output {number(totals.get('output_tokens'))} tokens"], "SESSION"),
+ ([f"Context {number(model.get('context'))} tokens",
+ f"Topology {safe(topology.get('mode'), 26)}",
+ f"Last engine token {number(recent[0].get('first_engine_token_s') if recent else None, 's', 3)}"],
+ "ENGINE"),
+ ])
+ right_sections = [(hardware, "HARDWARE"), (requests, "REQUESTS"),
+ (activity, "ACTIVITY")]
+ panel_rows = max(sum(len(lines) + 2 for lines, _ in left_sections),
+ sum(len(lines) + 2 for lines, _ in right_sections))
+ # Textual reserves its final row for the read-only message. Keep this
+ # navigation row next to it when a tall terminal has spare space.
+ filler = max(0, min(200, height + 1 - (3 + int(telemetry_unavailable) + panel_rows + 1)))
+ return Group(header, *([Text("Telemetry unavailable; status only", style="yellow" if color else "")]
+ if telemetry_unavailable else []),
+ _columns([_panel(lines, title, accent, color=color) for lines, title in left_sections],
+ [_panel(lines, title, accent, color=color) for lines, title in right_sections]),
+ *[Text(" ") for _ in range(filler)], footer)
diff --git a/strata_cli/detail_dashboard.py b/strata_cli/detail_dashboard.py
new file mode 100644
index 000000000..bdcb965ef
--- /dev/null
+++ b/strata_cli/detail_dashboard.py
@@ -0,0 +1,588 @@
+"""Wide, read-only detail pages for the terminal monitor.
+
+Every value comes from the bounded telemetry snapshot. These pages are a
+presentation layer: they never inspect prompt bodies or query the engine.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from rich import box
+from rich.console import Group
+from rich.panel import Panel
+from rich.text import Text
+
+from strata_cli.client import complete_slots
+from strata_cli.dashboard import (_age, _current_batch_value, _current_sample,
+ _device_role, _gib, _meter, _rate_spark, _spark,
+ _state, _visual_pair, _visual_panel, MonitorHistory)
+from strata_cli.render import (_device_stage, _queue_wait, _recent_detail,
+ _request_detail, _slot_detail, activity_continuity_notice,
+ activity_label, activity_rows, field, number,
+ request_rows, safe)
+
+
+def _palette(color: bool, theme: str) -> dict[str, str]:
+ if not color:
+ return {key: "default" for key in ("cyan", "green", "amber", "violet", "red")}
+ if theme == "light":
+ return {"cyan": "#087b9a", "green": "#0c8a60", "amber": "#946000",
+ "violet": "#7842af", "red": "#b01a2e"}
+ return {"cyan": "#22d3ee", "green": "#34d399", "amber": "#fbbf24",
+ "violet": "#a78bfa", "red": "#ff8a98"}
+
+
+def _txt(value: str, style: str = "") -> Text:
+ return Text(value, style=style, no_wrap=True, overflow="crop")
+
+
+def _panel(lines: list[Text], title: str, accent: str, color: bool, height: int) -> Panel:
+ capacity = max(1, height - 2)
+ if len(lines) > capacity:
+ lines = lines[:capacity - 1] + [_txt("… more rows; use Up/Down or filter", "dim")]
+ return _visual_panel(lines, title, accent, color, height=height)
+
+
+def _window(rows: list[Any], selected: int, capacity: int) -> tuple[int, list[Any]]:
+ start = min(max(0, selected - capacity // 2), max(0, len(rows) - capacity))
+ return start, rows[start:start + capacity]
+
+
+def _route(row: dict) -> str:
+ replica = f"R{row['replica']}/" if type(row.get("replica")) is int else ""
+ slot = f"S{row['slot']}" if type(row.get("slot")) is int else "--"
+ return replica + slot
+
+
+def _request_line(row: dict, snapshot: dict, slots: list[dict] | None,
+ *, selected: bool, live: bool, color: bool, palette: dict[str, str]) -> Text:
+ state = safe(row.get("state"), 10)
+ prompt = (f"{number(row.get('prompt_read'))}/{number(row.get('prompt_tokens'))}"
+ if state == "reading" else number(row.get("prompt_tokens")))
+ rate = next((slot.get("tok_s") for slot in slots or []
+ if slot.get("slot") == row.get("slot") and slot.get("request_id") == row.get("id")), None)
+ wait = number(_queue_wait(row, snapshot.get("sampled_at")), "s", 1)
+ first = number(row.get("first_engine_token_s"), "s", 2)
+ line = (f"{'▸' if selected else ' '} {field(row.get('id'), 12)} {state:<10} "
+ f"{_route(row):<7} {prompt:<11} {number(row.get('generated')):>5} "
+ f"{number(rate if live else None, '', 1):>6} {wait:>5} {first:>6}")
+ tint = (palette["amber"] if state in ("queued", "reading") else
+ palette["green"] if state == "decoding" else palette["violet"])
+ return _txt(line, tint if color else "")
+
+
+def _request_heading() -> Text:
+ return _txt(" ID STATE ROUTE PROMPT OUT SLOT/s WAIT 1ST", "dim")
+
+
+def _device_lines(row: dict, *, selected: bool, topology: dict,
+ history: MonitorHistory, glyphs: str, live: bool,
+ palette: dict[str, str], color: bool) -> list[Text]:
+ index = row.get("index")
+ util = row.get("util") if live else None
+ used = row.get("mem_used") if live else None
+ total = row.get("mem_total") if live else None
+ power = row.get("power") if live else None
+ temp = row.get("temp") if live else None
+ marker = "▸" if selected else " "
+ name = field(row.get("name"), 20)
+ header = _txt(f"{marker} GPU {number(index):<2} {name} {_device_role(index, topology):<4} "
+ f"{number(util, '%'):>4} {number(temp, 'C'):>4} {number(power, 'W'):>5}",
+ palette["green"] if color else "")
+ bars = _txt(f" LOAD {_meter(util, 100, 14, glyphs)} "
+ f"VRAM {_meter(used, total, 12, glyphs)} {_gib(used)}/{_gib(total)}G",
+ palette["green"] if color else "")
+ trend = _txt(f" RECENT {_spark(history.device_util.get(index) if live else (), glyphs, 17)} "
+ f"VRAM {_spark(history.device_vram.get(index) if live else (), glyphs, 15)}",
+ "dim")
+ return [header, bars, trend]
+
+
+def _detail_lines(kind: str, row: dict, snapshot: dict, width: int,
+ live: bool) -> list[Text]:
+ if kind == "device":
+ topology = snapshot.get("topology") or {}
+ lines = [f"GPU {number(row.get('index'))} {safe(row.get('name'), 40)}",
+ f"Load {number(row.get('util') if live else None, '%')} "
+ f"VRAM {_gib(row.get('mem_used') if live else None)}/"
+ f"{_gib(row.get('mem_total') if live else None)} GiB",
+ f"Temp {number(row.get('temp') if live else None, 'C')} "
+ f"Power {number(row.get('power') if live else None, 'W')}",
+ _device_stage(topology, row.get("index"), width)]
+ elif kind == "slot":
+ lines = _slot_detail(row if live else {**row, "tok_s": None}, width)[1:]
+ elif kind == "recent":
+ lines = _recent_detail(row, width)[1:]
+ else:
+ lines = _request_detail(row, snapshot.get("sampled_at"), width)[2:]
+ return [_txt(line) for line in lines]
+
+
+def _serving(snapshot: dict, history: MonitorHistory, *, heights: tuple[int, int, int],
+ selected: int, detail: bool, pane: str, filter_text: str,
+ live: bool, glyphs: str, color: bool, palette: dict[str, str],
+ width: int) -> Group:
+ work, rates = snapshot.get("work") or {}, snapshot.get("rates") or {}
+ topology, devices = snapshot.get("topology") or {}, snapshot.get("devices") or []
+ slots = complete_slots(work)
+ top_h, mid_h, low_h = heights
+ focus = f"PANE {pane.upper()} · Tab: devices / requests / groups"
+ top_left = [_txt(f"{number(work.get('active'))} ACTIVE "
+ f"{number(work.get('occupied_slots'))}/{number(work.get('slots_effective'))} SLOTS "
+ f"{number(work.get('waiting'))} ENGINE WAIT", palette["green"] if color else ""),
+ _txt(f"ALL OUTPUT {number(rates.get('aggregate_output_tok_s') if live else None, ' tok/s', 1)} "
+ f"PROMPT {number(rates.get('prefill_tok_s') if live else None, ' tok/s', 1)}",
+ palette["cyan"] if color else ""),
+ _txt(f"{safe((snapshot.get('model') or {}).get('id'), 35)} · "
+ f"{safe(topology.get('mode'), 25)}", "dim"),
+ _txt(focus, palette["amber"] if color else "")]
+ top_right = [_txt(f"{number(_current_batch_value(work, 'effective_rows_window'), '', 1)} "
+ f"ROWS/WINDOW processed "
+ f"{number(_current_batch_value(work, 'batch_active_rows_window'), '', 1)} active",
+ palette["violet"] if color else ""),
+ _txt(f"{number(work.get('queued'))} PRE-ADMIT "
+ f"{number(work.get('admission_reserved'))}/{number(work.get('admission_limit'))} "
+ f"RESERVED/LIMIT", palette["amber"] if color else ""),
+ _txt(f"Recent rows {_rate_spark(history.batch_rows if live else (), glyphs)} "
+ f"pre-admit {_rate_spark(history.pre_admit if live else (), glyphs)}", "dim"),
+ _txt("Rows/window is an engine sample; queue is before admission.", "dim")]
+ replica_batches = work.get("replica_batches") or []
+ if replica_batches:
+ top_right = [_txt(f"R{number(row.get('replica'))} ROWS/WIN "
+ f"{number(_current_batch_value(row, 'effective_rows_window'), '', 1)} processed / "
+ f"{number(_current_batch_value(row, 'batch_active_rows_window'), '', 1)} active",
+ palette["violet"] if color else "")
+ for row in replica_batches[:2]]
+ top_right.append(_txt(f"{number(work.get('queued'))} PRE-ADMIT "
+ f"{number(work.get('admission_reserved'))}/"
+ f"{number(work.get('admission_limit'))} RESERVED/LIMIT",
+ palette["amber"] if color else ""))
+ top_right.append(_txt("Replica sample windows are independent.", "dim"))
+ requests, _ = request_rows(snapshot, filter_text)
+ request_start, request_shown = _window(requests, selected if pane == "requests" else 0,
+ max(1, mid_h - 5))
+ flow = [_request_heading()]
+ for i, row in enumerate(request_shown, request_start):
+ flow.append(_request_line(row, snapshot, slots, selected=pane == "requests" and i == selected,
+ live=live, color=color, palette=palette))
+ if not requests:
+ flow.append(_txt("Request identities unavailable" if work.get("requests") is None else
+ "No requests match the filter" if filter_text else
+ "No active requests", "dim"))
+ if len(requests) > len(request_shown):
+ flow.append(_txt(f"Showing {request_start + 1}-{request_start + len(request_shown)} "
+ f"of {len(requests)}; use Requests for the full list", "dim"))
+ queue = [_txt(f"PRE-ADMIT {_meter(work.get('queued'), work.get('max_queue'), 20, glyphs)} "
+ f"{number(work.get('queued'))}/{number(work.get('max_queue'))}",
+ palette["amber"] if color else ""),
+ _txt(f"Oldest wait {number(work.get('oldest_queue_s'), 's', 1)} "
+ f"timeout {number(work.get('queue_timeout_s'), 's', 1)}"),
+ _txt(f"Rejected {number(work.get('admission_rejected'))} "
+ f"timed out {number(work.get('queue_timeouts'))} "
+ f"disconnect cancels {number(work.get('client_disconnect_cancels'))}"),
+ _txt("", ""), _txt("ENGINE SLOT FLOW", "dim")]
+ for state, label, shade in (("reading", "PREFILL", palette["amber"]),
+ ("decoding", "DECODE", palette["green"]),
+ ("idle", "IDLE", "dim")):
+ count = sum(row.get("state") == state for row in slots or [])
+ queue.append(_txt(f"{label:<8} {number(count) if slots is not None else '--':>3} "
+ f"{_meter(count if slots is not None else None, len(slots or []), 20, glyphs)}",
+ shade if color else ""))
+ queue.append(_txt("Groups are pipeline batch groups, not GPU assignments.", "dim"))
+ slot_rows = work.get("slots") or []
+ slot_start, slot_shown = _window(slot_rows, selected if pane == "groups" else 0,
+ max(1, low_h - 5))
+ slot_lines = [_txt(" SLOT GROUP STATE REQUEST HELD / CONTEXT SLOT/s", "dim")]
+ context = (snapshot.get("model") or {}).get("context")
+ for i, row in enumerate(slot_shown, slot_start):
+ mark = "▸" if pane == "groups" and i == selected else " "
+ slot_lines.append(_txt(f"{mark} S{number(row.get('slot')):<4} "
+ f"G{number(row.get('group')):<5} {safe(row.get('state'), 10):<11} "
+ f"{field(row.get('request_id'), 12)} "
+ f"{number(row.get('held_tokens')):>6}/{number(context):<7} "
+ f"{number(row.get('tok_s') if live else None, '', 1):>6}",
+ palette["green"] if row.get("state") == "decoding" and color else
+ palette["amber"] if row.get("state") == "reading" and color else "dim"))
+ if not slot_rows:
+ slot_lines.append(_txt("Slot detail unavailable", "dim"))
+ if len(slot_rows) > len(slot_shown):
+ slot_lines.append(_txt(f"Slots {slot_start + 1}-{slot_start + len(slot_shown)} of {len(slot_rows)}", "dim"))
+ device_lines: list[Text] = []
+ device_start, device_shown = _window(devices, selected if pane == "devices" else 0, 4)
+ for i, row in enumerate(device_shown, device_start):
+ index = row.get("index")
+ device_lines.append(_txt(f"{'▸' if pane == 'devices' and i == selected else ' '} GPU "
+ f"{number(index)} {field(row.get('name'), 18)} "
+ f"{_device_role(index, topology):<4} "
+ f"{number(row.get('util') if live else None, '%'):>4} "
+ f"{_gib(row.get('mem_used') if live else None)}/"
+ f"{_gib(row.get('mem_total') if live else None)}G",
+ palette["green"] if color else ""))
+ device_lines.append(_txt(f" {_meter(row.get('util') if live else None, 100, 14, glyphs)} "
+ f"VRAM {_meter(row.get('mem_used') if live else None, row.get('mem_total') if live else None, 13, glyphs)}",
+ palette["green"] if color else ""))
+ if not devices:
+ device_lines.append(_txt("Per-device readings unavailable", "dim"))
+ if len(devices) > 4:
+ device_lines.append(_txt(f"Cards {device_start + 1}-{device_start + len(device_shown)} "
+ f"of {len(devices)} · Hardware shows all", "dim"))
+ if detail:
+ rows = devices if pane == "devices" else requests if pane == "requests" else slot_rows
+ if rows and selected < len(rows):
+ kind = "device" if pane == "devices" else "live" if pane == "requests" else "slot"
+ device_lines.extend(_detail_lines(kind, rows[selected], snapshot, width - 70, live)[-3:])
+ return Group(_visual_pair(_panel(top_left, "SERVING / REQUEST PRESSURE", palette["cyan"], color, top_h),
+ _panel(top_right, "BATCHING / ADMISSION", palette["violet"], color, top_h), 1, 1),
+ _visual_pair(_panel(flow, f"REQUEST FLOW · {len(requests)} visible", palette["cyan"], color, mid_h),
+ _panel(queue, "QUEUE / SLOT PHASES", palette["amber"], color, mid_h), 4, 3),
+ _visual_pair(_panel(slot_lines, "ENGINE SLOTS / CONTEXT", palette["violet"], color, low_h),
+ _panel(device_lines, "GPU FLEET / FOCUS", palette["green"], color, low_h), 4, 3))
+
+
+def _requests(snapshot: dict, *, heights: tuple[int, int, int], selected: int,
+ detail: bool, filter_text: str, live: bool, glyphs: str,
+ color: bool, palette: dict[str, str], width: int) -> Group:
+ work, rates = snapshot.get("work") or {}, snapshot.get("rates") or {}
+ slots = complete_slots(work)
+ active, recent = request_rows(snapshot, filter_text)
+ rows = [("live", row) for row in active] + [("recent", row) for row in recent]
+ top_h, mid_h, low_h = heights
+ top_left = [_txt(f"{len(active)} LIVE {len(recent)} RECENT "
+ f"{number(work.get('queued'))} PRE-ADMIT "
+ f"{number(work.get('waiting'))} ENGINE WAIT",
+ palette["green"] if color else ""),
+ _txt(f"{number(rates.get('aggregate_output_tok_s') if live else None, ' tok/s', 1)} "
+ f"ALL OUTPUT {number(rates.get('answer_tok_s') if live else None, ' tok/s', 1)} "
+ f"ANSWER", palette["cyan"] if color else ""),
+ _txt("IDs and counts only · no prompt or tool text", "dim")]
+ top_right = [_txt(f"Occupied {number(work.get('occupied_slots'))}/"
+ f"{number(work.get('slots_effective'))} slots "
+ f"Context {(number((snapshot.get('model') or {}).get('context')))} / slot",
+ palette["violet"] if color else ""),
+ _txt(f"Oldest queue {number(work.get('oldest_queue_s'), 's', 1)} "
+ f"Last first engine {number(recent[0].get('first_engine_token_s') if recent else None, 's', 2)}"),
+ _txt("Up/Down selects · Enter opens detail · / filters", "dim")]
+ live_start, live_shown = _window(active, selected if selected < len(active) else 0,
+ max(1, mid_h - 5))
+ live_lines = [_request_heading()]
+ for i, row in enumerate(live_shown, live_start):
+ live_lines.append(_request_line(row, snapshot, slots, selected=i == selected,
+ live=live, color=color, palette=palette))
+ if not active:
+ live_lines.append(_txt("No live request summaries" if not filter_text else
+ "No live requests match the filter", "dim"))
+ if len(active) > len(live_shown):
+ live_lines.append(_txt(f"Showing {live_start + 1}-{live_start + len(live_shown)} of {len(active)}", "dim"))
+ recent_lines = [_txt(" ID FINISH IN CACHE OUT TIME FIRST", "dim")]
+ recent_start, recent_shown = _window(recent, max(0, selected - len(active)), max(1, low_h - 4))
+ for i, row in enumerate(recent_shown, recent_start):
+ recent_lines.append(_txt(f"{'▸' if selected == len(active) + i else ' '} "
+ f"{field(row.get('id'), 12)} {safe(row.get('finish'), 10):<11} "
+ f"{number(row.get('prompt_tokens')):>6} "
+ f"{number(row.get('reused')):>5} "
+ f"{number(row.get('output_tokens')):>5} "
+ f"{number(row.get('duration_s'), 's', 1):>6} "
+ f"{number(row.get('first_engine_token_s'), 's', 2):>5}", "dim"))
+ if not recent:
+ recent_lines.append(_txt("No completed request summaries retained", "dim"))
+ if len(recent) > len(recent_shown):
+ recent_lines.append(_txt(f"Showing {recent_start + 1}-{recent_start + len(recent_shown)} of {len(recent)}", "dim"))
+ detail_lines: list[Text] = []
+ if rows:
+ kind, row = rows[min(max(0, selected), len(rows) - 1)]
+ detail_lines.append(_txt(f"{safe(row.get('id'), 28)} · {kind.upper()}",
+ palette["green"] if color else ""))
+ if detail:
+ detail_lines.extend(_detail_lines(kind, row, snapshot, width // 2, live))
+ elif kind == "live":
+ detail_lines.extend([_txt(f"{safe(row.get('state'), 12)} · {_route(row)} · "
+ f"{number(row.get('prompt_tokens'))} prompt tokens"),
+ _txt(f"{number(row.get('generated'))} output · "
+ f"wait {number(_queue_wait(row, snapshot.get('sampled_at')), 's', 1)}")])
+ else:
+ detail_lines.extend([_txt(f"{safe(row.get('finish'), 12)} · "
+ f"{number(row.get('output_tokens'))} output tokens"),
+ _txt(f"Duration {number(row.get('duration_s'), 's', 2)}")])
+ else:
+ detail_lines.append(_txt("Select a request to inspect its redacted telemetry", "dim"))
+ detail_lines.append(_txt("Read only. Request text is never collected.", "dim"))
+ if not detail:
+ detail_lines.append(_txt("Enter expands the selected row", "dim"))
+ return Group(_visual_pair(_panel(top_left, "REQUESTS / CONCURRENCY", palette["cyan"], color, top_h),
+ _panel(top_right, "LATENCY / CONTEXT", palette["amber"], color, top_h), 1, 1),
+ _panel(live_lines, f"IN FLIGHT · {len(active)}", palette["green"], color, mid_h),
+ _visual_pair(_panel(recent_lines, f"RECENTLY FINISHED · {len(recent)}", palette["violet"], color, low_h),
+ _panel(detail_lines, "SELECTED REQUEST", palette["cyan"], color, low_h), 1, 1))
+
+
+def _engine(snapshot: dict, history: MonitorHistory, *, heights: tuple[int, int, int],
+ live: bool, glyphs: str, color: bool, palette: dict[str, str]) -> Group:
+ model, work = snapshot.get("model") or {}, snapshot.get("work") or {}
+ rates, topology = snapshot.get("rates") or {}, snapshot.get("topology") or {}
+ slots = complete_slots(work)
+ top_h, mid_h, low_h = heights
+ top_left = [_txt(f"{safe(topology.get('mode'), 30)} "
+ f"{number(len(topology.get('selected_devices') or []))} SELECTED GPUS",
+ palette["cyan"] if color else ""),
+ _txt(f"{number(work.get('occupied_slots'))}/"
+ f"{number(work.get('slots_effective'))} SLOTS "
+ f"{number(work.get('groups'))} BATCH GROUPS "
+ f"{number(model.get('context'))} CONTEXT", palette["violet"] if color else ""),
+ _txt("Layer mapping is from the engine start log when available.", "dim")]
+ top_right = [_txt(f"ANSWER {number(rates.get('answer_tok_s') if live else None, ' tok/s', 1)} "
+ f"PROMPT {number(rates.get('prefill_tok_s') if live else None, ' tok/s', 1)}",
+ palette["cyan"] if color else ""),
+ _txt(f"ROWS/WIN {number(_current_batch_value(work, 'effective_rows_window'), '', 1)} "
+ f"processed / {number(_current_batch_value(work, 'batch_active_rows_window'), '', 1)} active",
+ palette["amber"] if color else ""),
+ _txt("Host in-flight span is not GPU kernel utilization.", "dim")]
+ stages: list[Text] = []
+ replica_samples = {row.get("replica"): row for row in work.get("replica_stage_samples") or []}
+ if topology.get("replica_stages"):
+ for entry in topology["replica_stages"]:
+ replica = entry.get("replica")
+ sample = replica_samples.get(replica) or {}
+ fresh = _current_sample(sample, "stage_sample_age_s") and live
+ measured = {row.get("stage"): row for row in sample.get("stage_in_flight") or []} if fresh else {}
+ stages.append(_txt(f"R{number(replica)} stage host span · "
+ f"{number(sample.get('stage_sample_span_s') if fresh else None, 's', 1)} window",
+ palette["violet"] if color else ""))
+ for stage in entry.get("stages") or []:
+ value = (measured.get(stage.get("stage")) or {}).get("percent")
+ stages.append(_txt(f" S{number(stage.get('stage')):<2} GPU {number(stage.get('device_index')):<2} "
+ f"L{number(stage.get('layer_start'))}-{number(stage.get('layer_end')):<7} "
+ f"{_meter(value, 100, 16, glyphs)} {number(value, '%')}",
+ palette["violet"] if color else ""))
+ elif topology.get("stages"):
+ fresh = _current_sample(work, "stage_sample_age_s") and live
+ measured = {row.get("stage"): row for row in work.get("stage_in_flight") or []} if fresh else {}
+ for stage in topology["stages"]:
+ value = (measured.get(stage.get("stage")) or {}).get("percent")
+ stages.append(_txt(f"S{number(stage.get('stage')):<2} GPU {number(stage.get('device_index')):<2} "
+ f"LAYERS {number(stage.get('layer_start')):>3}-"
+ f"{number(stage.get('layer_end')):<4} "
+ f"{_meter(value, 100, 18, glyphs)} {number(value, '%'):>4}",
+ palette["violet"] if color else ""))
+ else:
+ stages.append(_txt("Stage/layer mapping unavailable", "dim"))
+ stages.append(_txt("Host poll delay is included; this is not kernel occupancy.", "dim"))
+ batch = [_txt(f"Engine rows/window "
+ f"{number(_current_batch_value(work, 'effective_rows_window'), '', 1)} processed "
+ f"{number(_current_batch_value(work, 'batch_active_rows_window'), '', 1)} active",
+ palette["amber"] if color else ""),
+ _txt(f"Trend {_rate_spark(history.batch_rows if live else (), glyphs)}", "dim"),
+ _txt(f"Sample {number(work.get('batch_sample_windows'))} windows / "
+ f"{number(work.get('batch_sample_span_s'), 's', 1)} "
+ f"age {number(work.get('batch_sample_age_s'), 's', 1)}"),
+ _txt("")]
+ for row in (work.get("replica_batches") or [])[:6]:
+ current = _current_sample(row, "batch_sample_age_s") and live
+ batch.append(_txt(f"R{number(row.get('replica'))} "
+ f"{number(row.get('effective_rows_window') if current else None, '', 1)} "
+ f"processed / {number(row.get('batch_active_rows_window') if current else None, '', 1)} "
+ f"active age {number(row.get('batch_sample_age_s'), 's', 1)}",
+ palette["amber"] if color else ""))
+ batch.extend([_txt(""), _txt(f"{number(work.get('waiting'))} engine waiting · "
+ f"{number(work.get('queued'))} before admission"),
+ _txt("Rows/window counts engine batch work, not requests.", "dim")])
+ context = model.get("context")
+ contexts = [_txt("SLOT STATE HELD / CAPACITY REQUEST", "dim")]
+ if slots is None:
+ contexts.append(_txt("Complete slot map unavailable", "dim"))
+ else:
+ for row in slots[:max(1, low_h - 5)]:
+ held = row.get("held_tokens") if live and row.get("state") != "idle" else 0 if live and row.get("state") == "idle" else None
+ contexts.append(_txt(f"S{number(row.get('slot')):<4} "
+ f"{safe(row.get('state'), 10):<10} "
+ f"{_meter(held, context, 14, glyphs)} "
+ f"{number(held):>6}/{number(context):<7} "
+ f"{field(row.get('request_id'), 12)}",
+ palette["green"] if row.get("state") == "decoding" and color else
+ palette["amber"] if row.get("state") == "reading" and color else "dim"))
+ note = [_txt("MEASUREMENT SOURCES", palette["cyan"] if color else ""),
+ _txt("Layer ranges engine start log"),
+ _txt("Stage in-flight host scheduling sample"),
+ _txt("GPU load device sensor; see Hardware"),
+ _txt("Batch rows engine window; may be unavailable"),
+ _txt("Context held tokens in active slot"),
+ _txt(""),
+ _txt("Pipeline groups are concurrency partitions.", "dim"),
+ _txt("They do not identify GPU assignments.", "dim")]
+ return Group(_visual_pair(_panel(top_left, "ENGINE / TOPOLOGY", palette["cyan"], color, top_h),
+ _panel(top_right, "ENGINE / PERFORMANCE", palette["amber"], color, top_h), 1, 1),
+ _visual_pair(_panel(stages, "STAGES / HOST SPAN", palette["violet"], color, mid_h),
+ _panel(batch, "BATCH WINDOW", palette["amber"], color, mid_h), 1, 1),
+ _visual_pair(_panel(contexts, "SLOT CONTEXTS", palette["green"], color, low_h),
+ _panel(note, "READING THE NUMBERS", palette["cyan"], color, low_h), 4, 3))
+
+
+def _hardware(snapshot: dict, history: MonitorHistory, *, heights: tuple[int, int, int],
+ selected: int, detail: bool, live: bool, glyphs: str,
+ color: bool, palette: dict[str, str], width: int) -> Group:
+ devices, topology = snapshot.get("devices") or [], snapshot.get("topology") or {}
+ ram = snapshot.get("ram") or {}
+ top_h, mid_h, low_h = heights
+ count = len(devices)
+ watts = [row.get("power") for row in devices]
+ total_watts = sum(watts) if watts and all(isinstance(w, (int, float)) and not isinstance(w, bool) for w in watts) else None
+ top_left = [_txt(f"{count} GPU DEVICES "
+ f"{number(total_watts if live else None, ' W', 0)} TOTAL BOARD POWER",
+ palette["green"] if color else ""),
+ _txt(f"{safe(topology.get('mode'), 34)} "
+ f"selected {number(len(topology.get('selected_devices') or []))}", "dim"),
+ _txt("Per-card values come from device sensors.", "dim")]
+ used, total = ram.get("used") if live else None, ram.get("total") if live else None
+ top_right = [_txt(f"HOST RAM {_gib(used)}/{_gib(total)} GiB "
+ f"{_meter(used, total, 20, glyphs)}",
+ palette["violet"] if color else ""),
+ _txt(f"GPU load history {_rate_spark(history.device_util.get(devices[0].get('index')) if devices and live else (), glyphs)}",
+ "dim"),
+ _txt("↑↓ select GPU · Enter placement details", "dim")]
+ # Two cards per column; selection scrolls in four-card pages.
+ page = min(max(0, selected // 4 * 4), max(0, count - 4))
+ shown = devices[page:page + 4]
+ columns: list[list[Text]] = [[], []]
+ for offset, row in enumerate(shown):
+ column = columns[offset // 2]
+ column.extend(_device_lines(row, selected=page + offset == selected,
+ topology=topology, history=history,
+ glyphs=glyphs, live=live, palette=palette,
+ color=color))
+ column.append(_txt(""))
+ if not devices:
+ columns[0].append(_txt("Per-device sensor readings unavailable", "dim"))
+ for column in columns:
+ column.append(_txt(f"Showing GPU {page + 1}-{page + len(shown)} of {count}" if count else
+ "No selected cards reported", "dim"))
+ trends: list[Text] = [_txt("GPU UTILIZATION TREND VRAM TREND", "dim")]
+ for row in devices[:max(1, low_h - 5)]:
+ index = row.get("index")
+ trends.append(_txt(f"GPU {number(index):<3} "
+ f"{_spark(history.device_util.get(index) if live else (), glyphs, 22):<23} "
+ f"{_spark(history.device_vram.get(index) if live else (), glyphs, 18)}",
+ palette["green"] if color else ""))
+ if not devices:
+ trends.append(_txt("History unavailable", "dim"))
+ trends.append(_txt("Gaps in the sparkline mark missing samples.", "dim"))
+ focus: list[Text] = []
+ if devices:
+ row = devices[min(max(0, selected), len(devices) - 1)]
+ selected_lines = _detail_lines("device", row, snapshot, width // 2, live)
+ focus.extend(selected_lines if detail else selected_lines[:3])
+ else:
+ focus.append(_txt("Select a GPU when sensors become available", "dim"))
+ focus.append(_txt("", ""))
+ focus.append(_txt(f"HOST RAM {_gib(used)}/{_gib(total)} GiB"))
+ focus.append(_txt(f"{_meter(used, total, 24, glyphs)}", palette["violet"] if color else ""))
+ focus.append(_txt("Placement follows the resolved engine log when reported.", "dim"))
+ if not detail:
+ focus.append(_txt("Enter expands selection; Tab changes Serving pane.", "dim"))
+ return Group(_visual_pair(_panel(top_left, "HARDWARE / GPU FLEET", palette["green"], color, top_h),
+ _panel(top_right, "HOST MEMORY / NAVIGATION", palette["violet"], color, top_h), 1, 1),
+ _visual_pair(_panel(columns[0], "GPU CARDS / A", palette["green"], color, mid_h),
+ _panel(columns[1], "GPU CARDS / B", palette["green"], color, mid_h), 1, 1),
+ _visual_pair(_panel(trends, "SENSOR HISTORY", palette["cyan"], color, low_h),
+ _panel(focus, "SELECTED DEVICE", palette["violet"], color, low_h), 1, 1))
+
+
+def _logs(snapshot: dict, *, heights: tuple[int, int, int], filter_text: str,
+ color: bool, palette: dict[str, str]) -> Group:
+ activity = snapshot.get("activity") or {}
+ events = activity_rows(snapshot, filter_text)
+ top_h, mid_h, low_h = heights
+ top_left = [_txt(f"{len(events)} VISIBLE EVENTS "
+ f"LAST SEQ {number(activity.get('last_seq'))}",
+ palette["cyan"] if color else ""),
+ _txt("Recent request activity · redacted IDs and lifecycle", "dim"),
+ _txt("This is a recent telemetry ring, not durable server logs.", "dim")]
+ notice = activity_continuity_notice(snapshot)
+ top_right = [_txt("CONTINUITY " + (notice or "No gap reported"),
+ palette["amber"] if notice and color else ""),
+ _txt(f"Server source {safe(snapshot.get('source'), 34)}"),
+ _txt("/ filters by request ID, event, or outcome", "dim")]
+ timeline = [_txt("SEQ TIME REQUEST ID EVENT / OUTCOME", "dim")]
+ if not activity.get("available"):
+ timeline.append(_txt("Request activity unavailable on this server", "dim"))
+ elif not events:
+ timeline.append(_txt("No transitions retained" if not filter_text else
+ "No events match the filter", "dim"))
+ else:
+ for row in events[-max(1, mid_h - 4):]:
+ event = safe(row.get("event"), 16)
+ tint = (palette["red"] if event in ("cancelled", "error", "rejected") else
+ palette["green"] if event in ("finished", "first_token") else
+ palette["amber"] if event in ("queued", "reading") else palette["cyan"])
+ timeline.append(_txt(activity_label(row, 95), tint if color else ""))
+ if len(events) > mid_h - 4:
+ timeline.append(_txt(f"Newest {mid_h - 4} of {len(events)} events shown", "dim"))
+ by_request: dict[str, list[str]] = {}
+ for row in events:
+ ident = safe(row.get("request_id"), 12)
+ by_request.setdefault(ident, []).append(safe(row.get("event"), 12))
+ flow = [_txt("REQUEST ID OBSERVED LIFECYCLE", "dim")]
+ for ident, states in list(by_request.items())[-max(1, low_h - 5):]:
+ flow.append(_txt(f"{ident:<14} {' → '.join(states[-5:])}", palette["cyan"] if color else ""))
+ if not by_request:
+ flow.append(_txt("No request lifecycle available", "dim"))
+ flow.append(_txt("Only events retained in the current ring appear here.", "dim"))
+ limits = [_txt("PRIVACY / RETENTION", palette["violet"] if color else ""),
+ _txt("Request IDs are bounded telemetry identifiers."),
+ _txt("Prompt bodies, output text and tool content are absent."),
+ _txt("The ring may roll over between polls."),
+ _txt("A sequence gap means events were missed."),
+ _txt(""),
+ _txt(f"Newest sequence {number(activity.get('last_seq'))}"),
+ _txt(f"Visible after filter {len(events)}"),
+ _txt("Use strata logs for a one-shot redacted snapshot.", "dim")]
+ return Group(_visual_pair(_panel(top_left, "LOGS / REQUEST ACTIVITY", palette["cyan"], color, top_h),
+ _panel(top_right, "CONTINUITY / SOURCE", palette["amber"], color, top_h), 1, 1),
+ _panel(timeline, "RECENT EVENT TIMELINE", palette["green"], color, mid_h),
+ _visual_pair(_panel(flow, "REQUEST LIFECYCLES", palette["cyan"], color, low_h),
+ _panel(limits, "WHAT THIS VIEW CONTAINS", palette["violet"], color, low_h), 1, 1))
+
+
+def render_detail_dashboard(snapshot: dict, view: str, *, width: int, height: int,
+ history: MonitorHistory, connection: str = "",
+ connection_state: str = "connected", frozen: bool = False,
+ filter_text: str = "", glyphs: str = "ascii",
+ color: bool = True, theme: str = "dark", selected: int = 0,
+ detail: bool = False, serving_pane: str = "devices") -> Group:
+ """Render the five wide pages with the visual Overview's panel language."""
+ palette = _palette(color, theme)
+ state, live = _state(snapshot, connection_state, frozen)
+ active = palette["green"] if state == "LIVE" else palette["amber"] if "STALE" in state else palette["red"]
+ heading = Text()
+ heading.append(f"STRATA / {view.upper()}", style=f"bold {palette['cyan']}")
+ heading.append(" ")
+ heading.append(state, style=f"bold {active}" if color else "bold")
+ heading.append(f" {safe(connection, max(0, width - 48))}")
+ header = Panel(heading, box=box.ROUNDED, border_style=active if color else "",
+ padding=(0, 1))
+ age = _age(snapshot)
+ footer = _txt("1 Overview 2 Serving 3 Requests 4 Engine 5 Hardware 6 Logs "
+ f"Tab pane ↑↓ select Enter detail / filter age {number(age, 's', 1)}", "dim")
+ top_h = 6 if height >= 40 else 5
+ room = max(0, height - 4 - top_h)
+ mid_h = room // 2 + (3 if view in ("serving", "requests", "logs") else 1)
+ low_h = room - mid_h
+ shared = dict(heights=(top_h, mid_h, low_h), live=live, glyphs=glyphs,
+ color=color, palette=palette)
+ if view == "serving":
+ body = _serving(snapshot, history, selected=selected, detail=detail,
+ pane=serving_pane, filter_text=filter_text, width=width, **shared)
+ elif view == "requests":
+ body = _requests(snapshot, selected=selected, detail=detail,
+ filter_text=filter_text, width=width, **{k: v for k, v in shared.items() if k != "heights"},
+ heights=shared["heights"])
+ elif view == "engine":
+ body = _engine(snapshot, history, **shared)
+ elif view == "hardware":
+ body = _hardware(snapshot, history, selected=selected, detail=detail,
+ width=width, **shared)
+ elif view == "logs":
+ body = _logs(snapshot, heights=shared["heights"], filter_text=filter_text,
+ color=color, palette=palette)
+ else:
+ raise ValueError("visual detail view must be serving, requests, engine, hardware or logs")
+ return Group(header, body, footer)
diff --git a/strata_cli/logs.py b/strata_cli/logs.py
new file mode 100644
index 000000000..595645f82
--- /dev/null
+++ b/strata_cli/logs.py
@@ -0,0 +1,151 @@
+"""Read-only, bounded request activity for the source and portable CLI."""
+
+from __future__ import annotations
+
+import json
+import sys
+import time
+from typing import Any
+
+from strata_cli.client import ClientError, Endpoint
+from strata_cli.render import activity_label
+
+
+def _emit(record: dict[str, Any], machine: bool) -> None:
+ if machine:
+ print(json.dumps({"schema_version": 1, **record}, ensure_ascii=False, allow_nan=False), flush=True)
+ elif record["type"] == "activity":
+ print(activity_label(record, 120), flush=True)
+ elif record["type"] == "gap":
+ print(f"Activity #{record['from_seq']}–#{record['to_seq']} is absent from this bounded feed", flush=True)
+ elif record["type"] == "instance_change":
+ print("Serving instance changed; activity sequence restarted", flush=True)
+
+
+def activity_delta(snapshot: dict, instance_id: str | None, cursor: int | None) -> tuple[list[dict], str, int]:
+ """Return new transitions and explicit sequence gaps from one sanitized snapshot."""
+ current_id = (snapshot.get("instance") or {}).get("id")
+ activity = snapshot.get("activity") or {}
+ if not current_id or not activity.get("available"):
+ raise ClientError("request activity is unavailable on this server", 5)
+ latest = activity["last_seq"]
+ if type(latest) is not int:
+ raise ClientError("invalid request activity sequence", 5)
+ rows = activity["events"]
+ changed = instance_id is not None and current_id != instance_id
+ if changed:
+ cursor = None
+ elif cursor is not None and latest < cursor:
+ raise ClientError("request activity sequence moved backwards without an instance change", 5)
+ out: list[dict] = []
+ if changed:
+ out.append({"type": "instance_change", "from_instance_id": instance_id,
+ "instance_id": current_id})
+ next_seq = 1 if cursor is None else cursor + 1
+ for row in rows:
+ seq = row["seq"]
+ if seq < next_seq:
+ continue
+ if seq > next_seq:
+ out.append({"type": "gap", "instance_id": current_id,
+ "from_seq": next_seq, "to_seq": seq - 1})
+ out.append({"type": "activity", "instance_id": current_id, **row})
+ next_seq = seq + 1
+ if latest >= next_seq:
+ out.append({"type": "gap", "instance_id": current_id,
+ "from_seq": next_seq, "to_seq": latest})
+ return out, current_id, latest
+
+
+class ActivityContinuity:
+ """Track gaps seen by one monitor without retaining request history locally."""
+
+ def __init__(self) -> None:
+ self.instance_id: str | None = None
+ self.cursor: int | None = None
+ self.gap: dict[str, int] | None = None
+ self.restarted = False
+ self.regressed = False
+
+ def add(self, snapshot: dict) -> None:
+ instance_id = (snapshot.get("instance") or {}).get("id")
+ activity = snapshot.get("activity") or {}
+ if not isinstance(instance_id, str) or not instance_id or not activity.get("available"):
+ return
+ latest = activity.get("last_seq")
+ if type(latest) is not int:
+ return
+ if self.instance_id is None:
+ # Retention before attach is expected; only report gaps after observation starts.
+ self.instance_id, self.cursor = instance_id, latest
+ return
+ try:
+ events, current_id, cursor = activity_delta(snapshot, self.instance_id, self.cursor)
+ except ClientError:
+ self.regressed = True
+ return
+ if current_id != self.instance_id:
+ self.gap = None
+ self.restarted = True
+ self.regressed = False
+ gaps = [event for event in events if event["type"] == "gap"]
+ if gaps:
+ self.gap = {"from_seq": gaps[-1]["from_seq"], "to_seq": gaps[-1]["to_seq"]}
+ self.instance_id, self.cursor = current_id, cursor
+
+ def status(self) -> dict:
+ return {"gap": dict(self.gap) if self.gap else None,
+ "restarted": self.restarted, "regressed": self.regressed}
+
+
+def run(endpoint: Endpoint, *, follow: bool, output: str, interval: float,
+ quiet: bool = False) -> int:
+ """Display retained transitions, then poll one snapshot at a time if requested."""
+ machine = output != "human"
+ snapshot = endpoint.snapshot()
+ activity = snapshot.get("activity") or {}
+ if not activity.get("available"):
+ raise ClientError("request activity is unavailable on this server", 5)
+ instance_id = (snapshot.get("instance") or {}).get("id")
+ if not follow:
+ record = {"schema_version": 1, "ok": True, "source": "runtime_activity",
+ "instance_id": instance_id, "last_seq": activity["last_seq"],
+ "retained": len(activity["events"]), "events": activity["events"]}
+ if machine:
+ print(json.dumps(record, ensure_ascii=False, allow_nan=False))
+ else:
+ if not quiet:
+ print("Recent request activity (redacted; newest 32 only)")
+ if activity["events"]:
+ for row in activity["events"]:
+ print(activity_label(row, 120))
+ elif not quiet:
+ print("No request transitions retained")
+ return 0
+ if not instance_id:
+ raise ClientError("request activity follow needs a serving instance ID", 5)
+ if not machine and not quiet:
+ print("Following redacted request activity (polling; Ctrl+C to detach)", flush=True)
+ events, current_id, cursor = activity_delta(snapshot, None, None)
+ for event in events:
+ _emit(event, machine)
+ failures = 0
+ while True:
+ try:
+ time.sleep(interval)
+ snapshot = endpoint.snapshot()
+ events, current_id, cursor = activity_delta(snapshot, current_id, cursor)
+ except ClientError as e:
+ if e.exit_code != 3:
+ raise
+ failures += 1
+ if failures >= 3:
+ raise ClientError("request activity connection failed after 3 attempts", 3) from e
+ if failures == 1 and not quiet:
+ print("strata: activity connection lost; retrying", file=sys.stderr)
+ continue
+ if failures and not quiet:
+ print("strata: activity connection restored", file=sys.stderr)
+ failures = 0
+ for event in events:
+ _emit(event, machine)
diff --git a/strata_cli/monitor.py b/strata_cli/monitor.py
new file mode 100644
index 000000000..c4559ba00
--- /dev/null
+++ b/strata_cli/monitor.py
@@ -0,0 +1,494 @@
+"""Optional Textual shell around the read-only terminal renderer."""
+
+from __future__ import annotations
+
+import asyncio
+import math
+import os
+import random
+import sys
+import time
+
+from rich.text import Text
+from textual.app import App, ComposeResult
+from textual.binding import Binding
+from textual.containers import Vertical
+from textual.widgets import Input, Static
+
+from strata_cli.client import ClientError, Endpoint
+from strata_cli.dashboard import MonitorHistory, render_dashboard
+from strata_cli.detail_dashboard import render_detail_dashboard
+from strata_cli.logs import ActivityContinuity
+from strata_cli.render import VIEWS, render_view, request_rows, safe
+
+
+def choose_glyphs(requested: str, encoding: str | None, term: str | None) -> str:
+ """Prefer readable Unicode when the output stream can encode its graph cells."""
+ if requested != "auto":
+ return requested
+ if term == "dumb" or not encoding:
+ return "ascii"
+ try:
+ "▁█░".encode(encoding)
+ except (LookupError, UnicodeEncodeError):
+ return "ascii"
+ return "unicode"
+
+
+def with_aggregate_rate(previous: dict, current: dict) -> dict:
+ """One common interval across all requests; reset on a new server instance."""
+ old_id = (previous.get("instance") or {}).get("id")
+ new_id = (current.get("instance") or {}).get("id")
+ old = (previous.get("rates") or {}).get("output_tokens_server_counter")
+ new = (current.get("rates") or {}).get("output_tokens_server_counter")
+ old_at, new_at = previous.get("sampled_at"), current.get("sampled_at")
+ rates = current.setdefault("rates", {})
+ rates["aggregate_output_tok_s"] = None
+ rates["aggregate_window_s"] = None
+ if not old_id or old_id != new_id or not all(isinstance(v, (int, float)) and
+ not isinstance(v, bool) and math.isfinite(v)
+ for v in (old, new, old_at, new_at)) or old < 0:
+ return current
+ dt = new_at - old_at
+ if 0 < dt <= 30 and new >= old:
+ rates["aggregate_output_tok_s"] = round((new - old) / dt, 1)
+ rates["aggregate_window_s"] = round(dt, 2)
+ return current
+
+
+def _fresh_rate_sample(snapshot: dict) -> bool:
+ sampled = snapshot.get("sampled_at")
+ return (isinstance(sampled, (int, float)) and not isinstance(sampled, bool) and
+ math.isfinite(sampled) and abs(time.time() - sampled) <= 5)
+
+
+class MonitorApp(App):
+ TITLE = "Strata Monitor"
+ CSS = """
+ Screen { background: #0e1113; color: #eef1f3; }
+ #shell { width: 100%; height: 100%; background: #161a1d; padding: 0 1; }
+ #content { width: 100%; height: 1fr; color: #eef1f3; }
+ #filter { height: 3; display: none; border: solid #34d399; }
+ #message { height: 1; color: #8e979f; }
+ """
+ BINDINGS = [
+ Binding(str(i + 1), f"view_{i}", f"{name.title()} view", show=False)
+ for i, name in enumerate(VIEWS)
+ ] + [
+ Binding("q", "quit", "Detach"), Binding("ctrl+c", "quit", "Detach", show=False),
+ Binding("space", "freeze", "Freeze"), Binding("r", "refresh", "Refresh"),
+ Binding("tab", "cycle_serving_pane", "Next pane", priority=True),
+ Binding("shift+tab", "previous_serving_pane", "Previous pane", show=False, priority=True),
+ Binding("t", "theme_cycle", "Theme"), Binding("slash", "filter_open", "Filter"),
+ Binding("escape", "filter_clear", "Clear filter", show=False),
+ Binding("down", "next_row", "Next", show=False),
+ Binding("up", "previous_row", "Previous", show=False),
+ Binding("pagedown", "page_down", "Next page", show=False),
+ Binding("pageup", "page_up", "Previous page", show=False),
+ Binding("home", "first_row", "First row", show=False),
+ Binding("end", "last_row", "Last row", show=False),
+ Binding("left", "previous_view", "Previous view", show=False),
+ Binding("right", "next_view", "Next view", show=False),
+ Binding("enter", "request_detail", "Row detail", show=False),
+ Binding("question_mark", "help", "Help"), Binding("f1", "help", "Help", show=False),
+ ]
+
+ def __init__(self, endpoint: Endpoint, snapshot: dict | None, *, interval: float = 1.0,
+ requests: int = 12, theme: str = "auto", color: str = "auto", glyphs: str = "auto"):
+ super().__init__()
+ self.endpoint = endpoint
+ self.latest = snapshot if snapshot is not None else {"source": "pending"}
+ self.rate_previous = snapshot if snapshot is not None and _fresh_rate_sample(snapshot) else None
+ self.displayed = self.latest
+ self.has_snapshot = snapshot is not None
+ self.displayed_has_snapshot = self.has_snapshot
+ self.connection_state = ("telemetry_unavailable" if self.has_snapshot and
+ (self.latest.get("quality") or {}).get("telemetry") == "unavailable" else
+ "connected" if self.has_snapshot else "connecting")
+ self.interval = interval
+ self.requests = requests
+ self.view = 0
+ self.serving_pane = "devices"
+ self.selected = 0
+ self.selected_identity: tuple[str, str] | None = None
+ self.detail = False
+ self.selection_notice: str | None = None
+ self.frozen = False
+ self.filter_text = ""
+ self.polling = False
+ self.closing = False
+ self.error: str | None = None
+ self.failures = 0
+ self.next_poll_at = 0.0
+ self.next_age_repaint = 0.0
+ self.theme_choice = "terminal" if theme == "auto" else theme
+ self.color_choice = "never" if os.environ.get("NO_COLOR") is not None else color
+ self.glyph_choice = choose_glyphs(glyphs, sys.stdout.encoding, os.environ.get("TERM"))
+ self.history = MonitorHistory()
+ self.activity_continuity = ActivityContinuity()
+ self.displayed_activity_continuity = self.activity_continuity.status()
+ if snapshot is not None:
+ self.history.add(snapshot, self._instance_key(snapshot))
+ self.activity_continuity.add(snapshot)
+ self.displayed_activity_continuity = self.activity_continuity.status()
+
+ def compose(self) -> ComposeResult:
+ with Vertical(id="shell"):
+ yield Static("", id="content", markup=False)
+ yield Input(placeholder="Filter request state, then Enter", max_length=80, id="filter")
+ yield Static("Read only | q detaches without stopping Strata", id="message", markup=False)
+
+ def on_mount(self) -> None:
+ self._apply_theme()
+ self._paint()
+ self.query_one("#filter", Input).disabled = True
+ self.set_focus(None)
+ self.set_interval(self.interval, self._schedule_poll)
+ if not self.has_snapshot:
+ self._schedule_poll(force=True)
+
+ def _apply_theme(self) -> None:
+ bg, panel, fg, mute = {
+ "dark": ("#0e1113", "#161a1d", "#eef1f3", "#8e979f"),
+ "light": ("#f9fafb", "#ffffff", "#221e1f", "#6f6f6f"),
+ "terminal": ("transparent", "transparent", "ansi_default", "ansi_default"),
+ }[self.theme_choice]
+ if self.color_choice == "never":
+ bg, panel, fg, mute = "transparent", "transparent", "ansi_default", "ansi_default"
+ self.screen.styles.background = bg
+ self.query_one("#shell").styles.background = panel
+ self.query_one("#content").styles.color = fg
+ self.query_one("#message").styles.color = mute
+
+ def _paint(self, size=None) -> None:
+ size = self.screen.size if size is None else size
+ snapshot = {**self.displayed, "recent": (self.displayed.get("recent") or [])[:self.requests]}
+ snapshot["activity_continuity"] = self.displayed_activity_continuity
+ snapshot["work"] = {**(self.displayed.get("work") or {}),
+ "requests": ((self.displayed.get("work") or {}).get("requests") or [])[:self.requests]}
+ if self.view == 0 and size.width >= 78 and size.height >= 23:
+ display = render_dashboard(
+ snapshot, width=max(30, size.width - 2), height=max(8, size.height - 2),
+ history=self.history, connection=getattr(self.endpoint, "base_url", getattr(self.endpoint, "root", "")),
+ connection_state=self.connection_state, frozen=self.frozen,
+ filter_text=self.filter_text, glyphs=self.glyph_choice,
+ color=self.color_choice != "never", theme=self.theme_choice)
+ elif self.view != 0 and size.width >= 128 and size.height >= 36 and self.connection_state not in (
+ "connecting", "disconnected", "auth_required", "incompatible"):
+ display = render_detail_dashboard(
+ snapshot, VIEWS[self.view], width=max(30, size.width - 2),
+ height=max(8, size.height - 2), history=self.history,
+ connection=getattr(self.endpoint, "base_url", getattr(self.endpoint, "root", "")),
+ connection_state=self.connection_state, frozen=self.frozen,
+ filter_text=self.filter_text, glyphs=self.glyph_choice,
+ color=self.color_choice != "never", theme=self.theme_choice,
+ selected=self.selected, detail=self.detail, serving_pane=self.serving_pane)
+ else:
+ content = render_view(snapshot, VIEWS[self.view],
+ width=max(30, size.width - 2), height=max(8, size.height - 2),
+ selected=self.selected, frozen=self.frozen,
+ filter_text=self.filter_text, glyphs=self.glyph_choice,
+ connection=getattr(self.endpoint, "base_url", getattr(self.endpoint, "root", "")),
+ serving_pane=self.serving_pane,
+ detail=self.detail, connection_state=self.connection_state)
+ display = Text(content, no_wrap=True, overflow="crop")
+ if self.color_choice != "never":
+ accent = "#0c8a60" if self.theme_choice == "light" else "#34d399"
+ muted = "#6f6f6f" if self.theme_choice == "light" else "#8e979f"
+ offset = 0
+ for line in content.splitlines(keepends=True):
+ stripped = line.strip()
+ if stripped.startswith("STRATA") or stripped.startswith(("REQUEST FLOW", "GPU SENSORS", "Hardware", "Recent requests", "Slots / groups", "Occupied slots by group")):
+ display.stylize(f"bold {accent}", offset, offset + len(line.rstrip("\n")))
+ elif stripped.startswith(("---", "Sample age", "1-6 views", "Read only")):
+ display.stylize(muted, offset, offset + len(line.rstrip("\n")))
+ offset += len(line)
+ display.highlight_regex(r"\[LIVE\]|\[\d [^\]]+\]", f"bold {accent}")
+ display.highlight_regex(r"\[(?:STALE|FROZEN(?:/[^\]]+)?|CONNECTING)\]", "bold yellow")
+ display.highlight_regex(r"\[(?:AUTH REQUIRED|INCOMPATIBLE|DISCONNECTED|NO TELEMETRY)\]", "bold red")
+ display.highlight_regex(r"GPU \d+", f"bold {accent}")
+ self.query_one("#content", Static).update(display)
+ idle_message = ("Read only | q keeps server on" if size.width < 60 else
+ "Read only | q detaches without stopping Strata")
+ msg = self.error or self.selection_notice or ("Connecting to Strata" if self.connection_state == "connecting" else
+ "Telemetry unavailable; status only" if self.connection_state == "telemetry_unavailable" else
+ "Frozen display; collection continues" if self.frozen else
+ idle_message)
+ self.query_one("#message", Static).update(msg)
+
+ def _schedule_poll(self, force: bool = False) -> None:
+ now = time.monotonic()
+ if not self.closing and not self.polling and (force or now >= self.next_poll_at):
+ self.polling = True # claim the cycle before create_task can be called again
+ asyncio.create_task(self._poll())
+ elif not self.closing and self.is_mounted and self.connection_state != "connected" and now >= self.next_age_repaint:
+ self.next_age_repaint = now + 1.0
+ self._paint()
+
+ async def _poll(self) -> None:
+ try:
+ fresh = with_aggregate_rate(self.rate_previous or {},
+ await asyncio.to_thread(self.endpoint.snapshot))
+ self.latest = fresh
+ self.rate_previous = fresh if _fresh_rate_sample(fresh) else None
+ self.activity_continuity.add(fresh)
+ if not self.frozen:
+ self._show_snapshot(fresh)
+ self.has_snapshot = True
+ self.connection_state = ("telemetry_unavailable" if
+ (fresh.get("quality") or {}).get("telemetry") == "unavailable" else
+ "connected")
+ self.error = None
+ self.failures = 0
+ self.next_poll_at = 0.0
+ except ClientError as e:
+ self.rate_previous = None
+ if not self.frozen:
+ self.history.gap()
+ self.error = str(e)
+ self.failures += 1
+ self.connection_state = ("auth_required" if e.exit_code == 4 else
+ "incompatible" if e.exit_code == 5 else
+ "stale" if self.has_snapshot and self.failures < 3 else "disconnected")
+ self.next_poll_at = (float("inf") if e.exit_code in (4, 5) else
+ time.monotonic() + min(30.0, 2.0 ** min(self.failures, 5) *
+ random.uniform(0.8, 1.2)))
+ except Exception:
+ self.rate_previous = None
+ if not self.frozen:
+ self.history.gap()
+ self.error = "Telemetry collection failed"
+ self.failures += 1
+ self.connection_state = "stale" if self.has_snapshot and self.failures < 3 else "disconnected"
+ self.next_poll_at = (time.monotonic() + min(30.0, 2.0 ** min(self.failures, 5) *
+ random.uniform(0.8, 1.2)))
+ finally:
+ self.polling = False
+ if not self.closing and self.is_mounted:
+ self._paint()
+
+ def on_resize(self, event) -> None:
+ self._paint(event.size)
+
+ def action_quit(self) -> None:
+ self.closing = True
+ self.exit()
+
+ def action_freeze(self) -> None:
+ self.frozen = not self.frozen
+ if not self.frozen:
+ self._show_snapshot(self.latest)
+ self._paint()
+
+ @staticmethod
+ def _instance_key(snapshot: dict) -> tuple[str, str] | None:
+ instance = snapshot.get("instance") or {}
+ identity = instance.get("id")
+ if isinstance(identity, str) and identity:
+ return ("id", identity)
+ boot = instance.get("boot_time")
+ if isinstance(boot, (int, float)) and not isinstance(boot, bool):
+ return ("boot", str(boot))
+ return None
+
+ def _show_snapshot(self, fresh: dict) -> None:
+ self.activity_continuity.add(fresh)
+ self.displayed_activity_continuity = self.activity_continuity.status()
+ prior = self._instance_key(self.displayed)
+ current = self._instance_key(fresh)
+ self.displayed = fresh
+ self.history.add(fresh, current)
+ was_displayed = self.displayed_has_snapshot
+ self.displayed_has_snapshot = True
+ if was_displayed and prior != current and (prior is not None or current is not None):
+ self.selected = 0
+ self.selected_identity = None
+ self.detail = False
+ self.selection_notice = "Server instance changed; selection cleared"
+ else:
+ self._restore_selection()
+
+ def action_refresh(self) -> None:
+ self._schedule_poll(force=True)
+
+ def action_cycle_serving_pane(self) -> None:
+ if self.view == 1:
+ panes = ("devices", "requests", "groups")
+ self.serving_pane = panes[(panes.index(self.serving_pane) + 1) % len(panes)]
+ self.selected = 0
+ self.selected_identity = None
+ self.detail = False
+ self.selection_notice = None
+ self._paint()
+
+ def action_previous_serving_pane(self) -> None:
+ if self.view == 1:
+ panes = ("devices", "requests", "groups")
+ self.serving_pane = panes[(panes.index(self.serving_pane) - 1) % len(panes)]
+ self.selected = 0
+ self.selected_identity = None
+ self.detail = False
+ self.selection_notice = None
+ self._paint()
+
+ def action_theme_cycle(self) -> None:
+ choices = ("terminal", "dark", "light")
+ self.theme_choice = choices[(choices.index(self.theme_choice) + 1) % len(choices)]
+ self._apply_theme()
+ self._paint()
+
+ def action_filter_open(self) -> None:
+ field = self.query_one("#filter", Input)
+ field.disabled = False
+ field.styles.display = "block"
+ field.value = self.filter_text
+ field.focus()
+
+ def on_input_changed(self, event: Input.Changed) -> None:
+ cleaned = safe(event.value, 80)
+ if event.value != cleaned:
+ event.input.value = cleaned
+
+ def on_input_submitted(self, event: Input.Submitted) -> None:
+ self.filter_text = safe(event.value, 80)
+ event.input.styles.display = "none"
+ event.input.disabled = True
+ self.set_focus(None)
+ self.selected = 0
+ self.selected_identity = None
+ self.detail = False
+ self.selection_notice = None
+ self._paint()
+
+ def action_filter_clear(self) -> None:
+ self.filter_text = ""
+ self.selected = 0
+ self.selected_identity = None
+ self.detail = False
+ self.selection_notice = None
+ field = self.query_one("#filter", Input)
+ field.styles.display = "none"
+ field.disabled = True
+ self.set_focus(None)
+ self._paint()
+
+ def action_next_row(self) -> None:
+ self._move_row(1)
+
+ def action_previous_row(self) -> None:
+ self._move_row(-1)
+
+ def action_page_down(self) -> None:
+ self._move_row(max(1, self.screen.size.height - 12))
+
+ def action_page_up(self) -> None:
+ self._move_row(-max(1, self.screen.size.height - 12))
+
+ def action_first_row(self) -> None:
+ self._move_row(-self.selected)
+
+ def action_last_row(self) -> None:
+ self._move_row(len(self._selectable_rows()))
+
+ def action_previous_view(self) -> None:
+ self._set_view((self.view - 1) % len(VIEWS))
+
+ def action_next_view(self) -> None:
+ self._set_view((self.view + 1) % len(VIEWS))
+
+ def _move_row(self, amount: int) -> None:
+ rows = self._selectable_rows()
+ if rows:
+ self.selected = min(max(0, self.selected + amount), len(rows) - 1)
+ self._remember_selection()
+ self._paint()
+
+ def action_help(self) -> None:
+ self.error = "1-6/Left/Right views Tab pane Up/Down/PgUp/PgDn/Home/End rows Enter detail Space freeze r refresh t theme q detach"
+ self._paint()
+
+ def action_request_detail(self) -> None:
+ if self._selected_entry() is not None:
+ self.detail = not self.detail
+ self._remember_selection()
+ self._paint()
+
+ def _selectable_rows(self) -> list[tuple[str, dict]]:
+ live, recent = request_rows(self.displayed, self.filter_text, limit=self.requests)
+ if self.view == 1:
+ if self.serving_pane == "requests":
+ return [("live", row) for row in live]
+ if self.serving_pane == "groups":
+ return [("slot", row) for row in (self.displayed.get("work") or {}).get("slots") or []]
+ return [("device", row) for row in self.displayed.get("devices") or []]
+ if self.view == 2:
+ return [("live", row) for row in live] + [("recent", row) for row in recent]
+ if self.view == 4:
+ return [("device", row) for row in self.displayed.get("devices") or []]
+ return []
+
+ def _selected_entry(self) -> tuple[str, dict] | None:
+ rows = self._selectable_rows()
+ return rows[self.selected] if 0 <= self.selected < len(rows) else None
+
+ @staticmethod
+ def _identity(kind: str, row: dict) -> tuple[str, str] | None:
+ key = "index" if kind == "device" else "slot" if kind == "slot" else "id"
+ value = row.get(key)
+ if kind in ("device", "slot"):
+ return (kind, str(value)) if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else None
+ return (kind, value) if isinstance(value, str) and value else None
+
+ def _remember_selection(self) -> None:
+ selected = self._selected_entry()
+ self.selected_identity = self._identity(*selected) if selected is not None else None
+ self.selection_notice = None
+
+ def _restore_selection(self) -> None:
+ rows = self._selectable_rows()
+ if self.selected_identity is None:
+ if self.detail:
+ self.detail = False
+ self.selected = min(self.selected, max(0, len(rows) - 1))
+ return
+ matches = [i for i, (kind, row) in enumerate(rows)
+ if self._identity(kind, row) == self.selected_identity]
+ if not matches and self.view == 2 and self.selected_identity[0] in ("live", "recent"):
+ # A live request can finish between polls. Follow its unique ID into recent history.
+ matches = [i for i, (_, row) in enumerate(rows)
+ if row.get("id") == self.selected_identity[1]]
+ if len(matches) == 1:
+ self.selected = matches[0]
+ self.selected_identity = self._identity(*rows[self.selected])
+ self.selection_notice = None
+ else:
+ self.selected_identity = None
+ self.detail = False
+ self.selection_notice = "No longer retained; select another row"
+ self.selected = min(self.selected, max(0, len(rows) - 1))
+
+ def _set_view(self, index: int) -> None:
+ self.view = index
+ self.selected = 0
+ self.selected_identity = None
+ self.detail = False
+ self.selection_notice = None
+ self._paint()
+
+ def action_view_0(self) -> None:
+ self._set_view(0)
+
+ def action_view_1(self) -> None:
+ self._set_view(1)
+
+ def action_view_2(self) -> None:
+ self._set_view(2)
+
+ def action_view_3(self) -> None:
+ self._set_view(3)
+
+ def action_view_4(self) -> None:
+ self._set_view(4)
+
+ def action_view_5(self) -> None:
+ self._set_view(5)
diff --git a/strata_cli/monitor_commands.py b/strata_cli/monitor_commands.py
new file mode 100644
index 000000000..f11477378
--- /dev/null
+++ b/strata_cli/monitor_commands.py
@@ -0,0 +1,216 @@
+"""Shared status/monitor grammar for the source launcher and portable client.
+
+This module and the one-shot status path use only Python's standard library.
+Textual is imported only when an interactive monitor actually starts.
+"""
+
+from __future__ import annotations
+
+import argparse
+import contextlib
+import io
+import json
+import os
+import sys
+
+from strata_cli.client import ClientError, Endpoint
+from strata_cli import connections
+
+
+def _connection(p: argparse.ArgumentParser) -> None:
+ p.add_argument("--url", help="Strata server root; remote connections require HTTPS")
+ p.add_argument("--connection", metavar="NAME", help="saved read-only connection")
+ p.add_argument("--credential-env", metavar="NAME",
+ help="environment variable containing the server credential")
+ p.add_argument("--timeout", type=float, help="bounded request timeout in seconds (default 3)")
+
+
+def add_status(sp: argparse._SubParsersAction) -> None:
+ status = sp.add_parser("status", help="one read-only telemetry snapshot")
+ _connection(status)
+ status.add_argument("--output", choices=("human", "json"), default="human")
+ status.add_argument("--json", action="store_true", help="alias for --output json")
+ status.add_argument("--quiet", action="store_true", help="suppress human informational output")
+
+
+def add_monitor(sp: argparse._SubParsersAction) -> None:
+ monitor = sp.add_parser("monitor", help="read-only six-view terminal monitor")
+ _connection(monitor)
+ monitor.add_argument("--once", action="store_true", help="print one snapshot without starting the TUI")
+ monitor.add_argument("--output", choices=("human", "json"), default="human")
+ monitor.add_argument("--json", action="store_true", help="alias for --output json with --once")
+ monitor.add_argument("--quiet", action="store_true", help="suppress one-shot human output")
+ monitor.add_argument("--theme", choices=("auto", "dark", "light", "terminal"), default="auto")
+ monitor.add_argument("--color", choices=("auto", "always", "never"), default="auto")
+ monitor.add_argument("--glyphs", choices=("auto", "unicode", "braille", "ascii"), default="auto")
+ monitor.add_argument("--interval", type=float, default=1.0)
+ monitor.add_argument("--requests", type=int, default=12)
+
+
+def add_logs(sp: argparse._SubParsersAction) -> None:
+ logs = sp.add_parser("logs", help="bounded redacted request activity (read only)")
+ _connection(logs)
+ logs.add_argument("--source", choices=("runtime", "harness"), default="runtime")
+ logs.add_argument("--follow", action="store_true", help="poll for new transitions until Ctrl+C")
+ logs.add_argument("--interval", type=float, default=2.0,
+ help="follow poll interval in seconds (0.5–30; default 2)")
+ logs.add_argument("--output", choices=("human", "json", "jsonl"), default="human")
+ logs.add_argument("--json", action="store_true", help="alias for --output json without --follow")
+ logs.add_argument("--quiet", action="store_true", help="suppress human progress text")
+
+
+def add_connections(sp: argparse._SubParsersAction) -> None:
+ connection = sp.add_parser("connection", help="save monitor endpoints without storing credential values")
+ actions = connection.add_subparsers(dest="connection_command", required=True)
+ create = actions.add_parser("create", help="save a named server endpoint")
+ create.add_argument("name")
+ create.add_argument("--url", required=True)
+ create.add_argument("--prefix", default="", help="reverse-proxy path prefix, e.g. /strata")
+ create.add_argument("--credential-env", default="STRATA_TELEMETRY_KEY")
+ show = actions.add_parser("show", help="show a saved connection without its credential")
+ show.add_argument("name")
+ actions.add_parser("list", help="list saved connections")
+ set_command = actions.add_parser("set", help="edit one URL, prefix or credential reference")
+ set_command.add_argument("name")
+ set_command.add_argument("assignment", metavar="KEY=VALUE")
+ set_command.add_argument("--plan", action="store_true")
+ set_command.add_argument("--if-revision", metavar="REVISION")
+ for command in (create, show, actions.choices["list"], set_command):
+ command.add_argument("--output", choices=("human", "json"), default="human")
+ command.add_argument("--json", action="store_true", help="alias for --output json")
+ command.add_argument("--quiet", action="store_true", help="suppress human informational output")
+
+ config = sp.add_parser("config", help="inspect effective client connection settings")
+ config_actions = config.add_subparsers(dest="config_command", required=True)
+ effective = config_actions.add_parser("show", help="show connection and credential origins")
+ effective.add_argument("--effective", action="store_true", help="show resolved settings (default)")
+ _connection(effective)
+ effective.add_argument("--output", choices=("human", "json"), default="human")
+ effective.add_argument("--json", action="store_true", help="alias for --output json")
+ effective.add_argument("--quiet", action="store_true", help="suppress human informational output")
+
+
+def parser() -> argparse.ArgumentParser:
+ ap = argparse.ArgumentParser(prog="strata-monitor", description="Read-only Strata serving client")
+ sp = ap.add_subparsers(dest="command", required=True)
+ add_status(sp)
+ add_monitor(sp)
+ add_logs(sp)
+ add_connections(sp)
+ return ap
+
+
+def _error(message: str, code: int, machine: bool) -> int:
+ if machine:
+ print(json.dumps({"schema_version": 1, "ok": False, "error": {"code": code, "message": message}}))
+ else:
+ print(f"strata: {message}", file=sys.stderr)
+ return code
+
+
+def _local_command(a: argparse.Namespace, machine: bool) -> int:
+ if a.command == "config":
+ resolved = connections.resolve(url=a.url, connection=a.connection,
+ credential_env=a.credential_env, timeout=a.timeout)
+ payload = {"schema_version": 1, "ok": True, "effective": resolved}
+ print(json.dumps(payload if machine else resolved, indent=None if machine else 2,
+ ensure_ascii=False))
+ return 0
+ action = a.connection_command
+ if action == "list":
+ rows = connections.list_connections()
+ payload = {"schema_version": 1, "ok": True, "connections": rows}
+ elif action == "show":
+ value, revision = connections.load(a.name)
+ payload = {"schema_version": 1, "ok": True, "connection": value, "revision": revision}
+ elif action == "create":
+ value, revision = connections.create(a.name, a.url, prefix=a.prefix,
+ credential_env=a.credential_env)
+ payload = {"schema_version": 1, "ok": True, "connection": value, "revision": revision}
+ else:
+ value, revision = connections.propose(a.name, a.assignment)
+ if a.if_revision is not None and a.if_revision != revision:
+ raise connections.ConnectionError("connection changed since preview; inspect it again", 6)
+ if a.plan:
+ payload = {"schema_version": 1, "ok": True, "connection": value,
+ "revision": revision, "would_save": value != connections.load(a.name)[0]}
+ else:
+ saved, new_revision = connections.save(a.name, value, expected_revision=revision)
+ payload = {"schema_version": 1, "ok": True, "connection": saved,
+ "previous_revision": revision, "revision": new_revision}
+ print(json.dumps(payload if machine else {k: v for k, v in payload.items() if k not in ("schema_version", "ok")},
+ indent=None if machine else 2, ensure_ascii=False))
+ return 0
+
+
+def run(a: argparse.Namespace) -> int:
+ machine = a.output in ("json", "jsonl") or getattr(a, "json", False)
+ quiet = bool(getattr(a, "quiet", False) and not machine)
+ try:
+ if a.command in ("connection", "config"):
+ if quiet:
+ with contextlib.redirect_stdout(io.StringIO()):
+ return _local_command(a, machine)
+ return _local_command(a, machine)
+ if a.command == "logs":
+ if not 0.5 <= a.interval <= 30:
+ return _error("--interval must be 0.5–30 seconds", 2, machine)
+ if a.json:
+ if a.follow or a.output == "jsonl":
+ return _error("--json is one-shot only; use --follow --output jsonl", 2, machine)
+ a.output = "json"
+ if a.follow and a.output == "json":
+ return _error("--follow requires human or jsonl output", 2, machine)
+ if not a.follow and a.output == "jsonl":
+ return _error("jsonl output requires --follow", 2, machine)
+ if a.source == "harness":
+ return _error("shared local harness activity is unavailable; use --source runtime", 5, machine)
+ if a.command == "monitor" and (a.interval < 0.5 or a.interval > 30 or not 1 <= a.requests <= 50):
+ return _error("--interval must be 0.5–30 seconds and --requests must be 1–50", 2, machine)
+ if a.command == "monitor" and (a.json or a.output == "json") and not a.once:
+ return _error("JSON monitor output requires --once; interactive monitor uses a terminal", 2, machine)
+ if a.command == "monitor" and not a.once and not sys.stdout.isatty():
+ return _error("interactive monitor needs a terminal; use --once or strata status --json", 2, machine)
+ resolved = connections.resolve(url=a.url, connection=a.connection,
+ credential_env=a.credential_env, timeout=a.timeout)
+ endpoint = Endpoint(resolved["url"], os.environ.get(resolved["credential_env"]),
+ resolved["timeout_s"], resolved["prefix"])
+ if a.command == "logs":
+ from strata_cli.logs import run as run_logs
+ return run_logs(endpoint, follow=a.follow, output=a.output, interval=a.interval, quiet=quiet)
+ if machine or a.command == "status" or a.once:
+ snapshot = endpoint.snapshot()
+ if machine:
+ print(json.dumps({"schema_version": 1, "ok": True, "snapshot": snapshot},
+ ensure_ascii=False, allow_nan=False))
+ return 0
+ if a.command == "status" or a.once:
+ from strata_cli.render import render_view
+ if not quiet:
+ print(render_view(snapshot, "overview", width=80, height=24))
+ return 0
+ try:
+ from strata_cli.monitor import MonitorApp
+ except ImportError:
+ return _error("monitor component missing; install the optional terminal UI dependency", 5, machine)
+ MonitorApp(endpoint, None, interval=a.interval, requests=a.requests,
+ theme=a.theme, color=a.color, glyphs=a.glyphs).run()
+ return 0
+ except ClientError as e:
+ return _error(str(e), e.exit_code, machine)
+ except connections.ConnectionError as e:
+ return _error(str(e), e.exit_code, machine)
+ except ValueError as e:
+ return _error(str(e), 2, machine)
+ except BrokenPipeError:
+ return 0
+ except OSError as e:
+ return _error(f"local file operation failed ({type(e).__name__})", 6, machine)
+ except KeyboardInterrupt:
+ if a.command == "logs" and a.follow:
+ return 0
+ return _error("interrupted; operation completion may be unknown", 130, machine)
+
+
+def main(argv: list[str] | None = None) -> int:
+ return run(parser().parse_args(argv))
diff --git a/strata_cli/render.py b/strata_cli/render.py
new file mode 100644
index 000000000..6663d46ef
--- /dev/null
+++ b/strata_cli/render.py
@@ -0,0 +1,738 @@
+"""Width-aware, color-free monitor content. The UI applies presentation styles."""
+
+from __future__ import annotations
+
+import math
+import time
+import unicodedata
+from typing import Any
+
+from strata_cli.client import complete_slots
+
+
+VIEWS = ("overview", "serving", "requests", "engine", "hardware", "logs")
+
+
+def activity_continuity_notice(snapshot: dict) -> str | None:
+ """Label missing transitions observed by this monitor, separate from server events."""
+ state = snapshot.get("activity_continuity") or {}
+ if not isinstance(state, dict):
+ return None
+ if state.get("regressed") is True:
+ return "Activity sequence reset without an instance change"
+ gap = state.get("gap") or {}
+ if not isinstance(gap, dict):
+ return None
+ start, end = gap.get("from_seq"), gap.get("to_seq")
+ if type(start) is int and type(end) is int and 0 < start <= end:
+ return f"Missed activity #{start}-{end} (retention gap)"
+ if state.get("restarted") is True:
+ return "Serving restarted; activity sequence reset"
+ return None
+
+
+def group_occupancy(work: dict) -> dict[int, tuple[int, int]] | None:
+ """Do not publish exact group counts from truncated or ambiguous slots."""
+ slots = complete_slots(work)
+ if slots is None:
+ return None
+ groups: dict[int, tuple[int, int]] = {}
+ reported_count = work.get("groups")
+ for row in slots:
+ group = row.get("group")
+ if (not isinstance(group, int) or isinstance(group, bool) or group < 0 or
+ isinstance(reported_count, int) and not isinstance(reported_count, bool) and
+ reported_count > 0 and group >= reported_count):
+ return None
+ busy, total = groups.get(group, (0, 0))
+ groups[group] = (busy + (row["state"] != "idle"), total + 1)
+ return groups
+
+
+def _emoji(char: str) -> bool:
+ code = ord(char)
+ return 0x1F000 <= code <= 0x1FAFF or 0x2600 <= code <= 0x27BF
+
+
+def _regional_indicator(char: str) -> bool:
+ return 0x1F1E6 <= ord(char) <= 0x1F1FF
+
+
+def _clusters(value: Any):
+ """Yield printable clusters without terminal controls or bidi formatters."""
+ current = ""
+ join_emoji = False
+ for char in unicodedata.normalize("NFC", str(value) if value is not None else "--"):
+ category = unicodedata.category(char)
+ if char == "\u200d":
+ if current and any(_emoji(piece) for piece in current):
+ current += char
+ join_emoji = True
+ continue
+ if not char.isprintable() or category in ("Cf", "Cc", "Cs"):
+ continue
+ mark = category in ("Mn", "Mc", "Me") or 0x1F3FB <= ord(char) <= 0x1F3FF
+ if mark:
+ if current:
+ current += char
+ continue
+ if join_emoji:
+ join_emoji = False
+ if _emoji(char):
+ current += char
+ continue
+ yield current.rstrip("\u200d")
+ current = char
+ continue
+ if _regional_indicator(char) and len(current) == 1 and _regional_indicator(current):
+ current += char
+ continue
+ if current:
+ yield current
+ current = char
+ if current:
+ yield current.rstrip("\u200d")
+
+
+def _cluster_width(cluster: str) -> int:
+ if "\u200d" in cluster or "\ufe0f" in cluster:
+ return 2
+ if len(cluster) == 2 and all(_regional_indicator(char) for char in cluster):
+ return 2
+ width = 0
+ for char in cluster:
+ if unicodedata.category(char) in ("Mn", "Mc", "Me") or 0x1F3FB <= ord(char) <= 0x1F3FF:
+ continue
+ width += 2 if unicodedata.east_asian_width(char) in ("W", "F") or \
+ 0x1F000 <= ord(char) <= 0x1FAFF else 1
+ return width
+
+
+def display_width(value: str) -> int:
+ return sum(_cluster_width(cluster) for cluster in _clusters(value))
+
+
+def safe(value: Any, width: int = 80) -> str:
+ cells = 0
+ out = []
+ for cluster in _clusters(value):
+ needed = _cluster_width(cluster)
+ if cells + needed > max(0, width):
+ break
+ out.append(cluster)
+ cells += needed
+ return "".join(out)
+
+
+def field(value: Any, width: int) -> str:
+ text = safe(value, width)
+ return text + " " * max(0, width - display_width(text))
+
+
+def number(value: Any, unit: str = "", digits: int = 0) -> str:
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
+ return "--"
+ return f"{value:,.{digits}f}{unit}" if digits else f"{value:,.0f}{unit}"
+
+
+def _line(text: str, width: int) -> str:
+ return safe(text, width)
+
+
+def _queue_wait(row: dict, sampled_at: Any) -> float | None:
+ queued = row.get("queued_at")
+ if not isinstance(queued, (int, float)) or isinstance(queued, bool) or not math.isfinite(queued):
+ return None
+ admitted = row.get("admitted_at")
+ end = admitted if isinstance(admitted, (int, float)) and not isinstance(admitted, bool) and math.isfinite(admitted) else sampled_at
+ if not isinstance(end, (int, float)) or isinstance(end, bool) or not math.isfinite(end):
+ return None
+ return max(0.0, end - queued)
+
+
+def _request_work(row: dict) -> str:
+ read = row.get("prompt_read")
+ if row.get("state") == "reading":
+ return f"read {number(read)} new" if read is not None else "read --"
+ return f"out {number(row.get('generated'))}"
+
+
+def _replica_prefix(row: dict) -> str:
+ replica = row.get("replica")
+ return f"Replica {replica} " if type(replica) is int and 0 <= replica < 16 else ""
+
+
+def _replica_short(row: dict) -> str:
+ replica = row.get("replica")
+ return f"r{replica} " if type(replica) is int and 0 <= replica < 16 else ""
+
+
+def _request_detail(row: dict, sampled_at: Any, width: int) -> list[str]:
+ """Only fields from the bounded, redacted telemetry contract."""
+ return ["", "REQUEST DETAIL (read only)",
+ _line(f"ID {safe(row.get('id'), 24)} State {safe(row.get('state'), 16)}", width),
+ _line(f"{_replica_prefix(row)}Slot {number(row.get('slot'))} Group {number(row.get('group'))} Queue wait {number(_queue_wait(row, sampled_at), ' s', 1)}", width),
+ _line(f"Prompt {number(row.get('prompt_tokens'))} tokens {_request_work(row)}", width),
+ _line(f"First engine token {number(row.get('first_engine_token_s'), ' s', 3)} [since queue entry] | No prompt text", width)]
+
+
+def _recent_detail(row: dict, width: int) -> list[str]:
+ """Completed-request fields from the bounded telemetry contract."""
+ return ["", "RECENT REQUEST DETAIL (read only)",
+ _line(f"ID {safe(row.get('id'), 24)} Finish {safe(row.get('finish'), 16)}", width),
+ _line(f"Prompt {number(row.get('prompt_tokens'))} Cached {number(row.get('reused'))} Output {number(row.get('output_tokens'))} tokens", width),
+ _line(f"Duration {number(row.get('duration_s'), ' s', 2)} Prompt {number(row.get('prompt_ms'), ' ms', 1)} Decode {number(row.get('decode_ms'), ' ms', 1)}", width),
+ _line(f"First engine token {number(row.get('first_engine_token_s'), ' s', 3)} [since queue entry] | No prompt text", width)]
+
+
+def request_rows(snapshot: dict, filter_text: str = "", *, limit: int | None = None) -> tuple[list[dict], list[dict]]:
+ """One selection order for the interactive shell and all renderer widths."""
+ work = snapshot.get("work") or {}
+ live = (work.get("requests") or [])[:limit]
+ recent = (snapshot.get("recent") or [])[:limit]
+ needle = filter_text.lower()
+ if needle:
+ live = [row for row in live if needle in (safe(row.get("id")) + safe(row.get("state"))).lower()]
+ recent = [row for row in recent if needle in (safe(row.get("id")) + safe(row.get("finish"))).lower()]
+ return live, recent
+
+
+def activity_rows(snapshot: dict, filter_text: str = "") -> list[dict]:
+ rows = (snapshot.get("activity") or {}).get("events") or []
+ needle = filter_text.lower()
+ return [row for row in rows if isinstance(row, dict) and
+ (not needle or needle in (safe(row.get("request_id")) + " " + safe(row.get("event")) +
+ " " + safe(row.get("outcome"))).lower())]
+
+
+def activity_label(row: dict, width: int) -> str:
+ at = row.get("at")
+ try:
+ clock = time.strftime("%H:%M:%S", time.localtime(at)) if isinstance(at, (int, float)) else "--:--:--"
+ except (OverflowError, OSError, ValueError):
+ clock = "--:--:--"
+ event = safe(row.get("event"), 16)
+ outcome = row.get("outcome")
+ label = f"{event} ({safe(outcome, 12)})" if outcome else event
+ return _line(f"#{number(row.get('seq')):<6} {clock} {field(row.get('request_id'), 12)} {label}", width)
+
+
+def _device(row: dict, width: int) -> str:
+ idx = row.get("index")
+ label = f"GPU {idx if idx is not None else '?'}"
+ used, total = row.get("mem_used"), row.get("mem_total")
+ mem = f"{number(used / 2**30 if isinstance(used, (int, float)) else None, '', 1)}/{number(total / 2**30 if isinstance(total, (int, float)) else None, ' GiB', 1)}"
+ if width < 80:
+ return _line(f"{label:<7} {mem:<17} util {number(row.get('util'), '%')}", width)
+ return _line(f"{label:<7} {field(row.get('name'), 18)} {mem:<17} {number(row.get('util'), '%'):>5} {number(row.get('temp'), ' C'):>6} {number(row.get('power'), ' W'):>7}", width)
+
+
+def _device_stage(topology: dict, index: Any, width: int) -> str:
+ if str(topology.get("mode") or "").startswith("replicas"):
+ for row in topology.get("replica_devices") or []:
+ if index in row.get("devices", []):
+ replica = row["replica"]
+ plan = next((entry for entry in topology.get("replica_stages") or []
+ if entry["replica"] == replica), None)
+ assigned = [stage for stage in plan["stages"] if stage.get("device_index") == index] if plan else []
+ if assigned:
+ ranges = ", ".join(f"{stage['stage']}:{stage['layer_start']}-{stage['layer_end']}"
+ for stage in assigned)
+ return _line(f"Replica R{replica} stage/layers {ranges} [engine log]", width)
+ cards = ",".join(str(device) for device in row["devices"])
+ return _line(f"Replica R{replica} [configured cards {cards}; stage map unavailable]", width)
+ return "Replica card assignment unavailable"
+ stages = topology.get("stages") or []
+ if topology.get("resolved") is True and stages:
+ assigned = [row for row in stages if row.get("device_index") == index]
+ if assigned:
+ ranges = ", ".join(f"{number(row.get('stage'))}:{number(row.get('layer_start'))}-{number(row.get('layer_end'))}"
+ for row in assigned)
+ return _line(f"Stage/layers {ranges} [engine log]", width)
+ return "Selected card is not an engine stage"
+ return ("Engine stage ranges reported; card mapping unavailable" if stages else
+ "Stage/layer mapping unavailable")
+
+
+def _batch_window(work: dict, width: int) -> str:
+ replica_batches = work.get("replica_batches") or []
+ if replica_batches:
+ shown = sorted(replica_batches, key=lambda row: row["replica"])[:2]
+ parts = [f"R{row['replica']} {number(row.get('effective_rows_window'), '', 1)}/"
+ f"{number(row.get('batch_active_rows_window'), '', 1)}"
+ + (f" age {number(row.get('batch_sample_age_s'), 's', 1)}" if width >= 80 else "")
+ for row in shown]
+ extra = max(0, len(replica_batches) - len(shown))
+ return _line("Batch rows/window processed/active " + " ".join(parts)
+ + (f" +{extra} replicas" if extra else ""), width)
+ rows = work.get("effective_rows_window")
+ if not isinstance(rows, (int, float)):
+ return _line("Batch rows/window --" if width < 60 else
+ "Batch rows/window -- [no engine batch sample]", width)
+ active = work.get("batch_active_rows_window")
+ if width < 60:
+ return _line(f"Batch {number(rows, '', 1)} processed / {number(active, '', 1)} active", width)
+ windows = work.get("batch_sample_windows")
+ span = work.get("batch_sample_span_s")
+ age = work.get("batch_sample_age_s")
+ return _line(f"Batch rows/window {number(rows, '', 1)} processed / {number(active, '', 1)} active "
+ f"[{number(windows)} windows/{number(span, 's', 1)}, {number(age, 's', 1)} old]", width)
+
+
+def _stage_in_flight(work: dict, width: int) -> str:
+ replica_samples = work.get("replica_stage_samples") or []
+ if replica_samples:
+ parts = []
+ for row in replica_samples[:2]:
+ stages = row.get("stage_in_flight") or []
+ values = " ".join(f"S{stage['stage']} {number(stage['percent'], '%', 0)}"
+ for stage in stages)
+ parts.append(f"R{row['replica']} {values or '--'}")
+ extra = max(0, len(replica_samples) - 2)
+ return _line("Replica host span " + " ".join(parts)
+ + (f" +{extra} see Engine" if extra else "") + " [not GPU util]", width)
+ stages = work.get("stage_in_flight") or []
+ if not stages:
+ return _line("Stage in-flight -- [no pipeline sample]", width)
+ values = " ".join(f"S{row['stage']} {number(row['percent'], '%', 0)}" for row in stages)
+ if width < 60:
+ compact = "/".join(number(row["percent"], "", 0) for row in stages)
+ return _line(f"Stages {compact}% in-flight [host]", width)
+ span, age = work.get("stage_sample_span_s"), work.get("stage_sample_age_s")
+ return _line(f"Stage in-flight {values} [host, {number(span, 's', 1)}, {number(age, 's', 1)} old]", width)
+
+
+def _device_detail(row: dict, topology: dict, width: int) -> list[str]:
+ used, total = row.get("mem_used"), row.get("mem_total")
+ used_gib = used / 2**30 if isinstance(used, (int, float)) else None
+ total_gib = total / 2**30 if isinstance(total, (int, float)) else None
+ return ["DEVICE DETAIL (read only)",
+ _line(f"GPU {number(row.get('index'))} {safe(row.get('name'), 30)}", width),
+ _line(f"VRAM {number(used_gib, ' GiB', 1)} / {number(total_gib, ' GiB', 1)} Util {number(row.get('util'), '%')}", width),
+ _line(f"Temperature {number(row.get('temp'), ' C')} Power {number(row.get('power'), ' W')}", width),
+ _line(f"Placement {safe(topology.get('mode'), 24)}; split {safe(topology.get('configured_split'), 24)}", width),
+ _device_stage(topology, row.get("index"), width)]
+
+
+def _slot_detail(row: dict, width: int) -> list[str]:
+ return ["", "SLOT DETAIL (read only)",
+ _line(f"{_replica_prefix(row)}Slot {number(row.get('slot'))} Group {number(row.get('group'))} State {safe(row.get('state'), 16)}", width),
+ _line(f"Request {safe(row.get('request_id'), 24)} Held {number(row.get('held_tokens'))} tokens", width),
+ _line(f"Prompt {number(row.get('prompt_tokens'))} New read {number(row.get('prompt_read'))} Output {number(row.get('generated'))}", width),
+ _line(f"Elapsed {number(row.get('elapsed_s'), ' s', 1)} Slot rate {number(row.get('tok_s'), ' tok/s', 1)}", width),
+ "Group is a pipeline batch group, not a GPU assignment"]
+
+
+def _row_window(rows: list[dict], selected: int, capacity: int) -> tuple[int, int, int]:
+ index = min(max(0, selected), max(0, len(rows) - 1))
+ start = min(max(0, index - capacity // 2), max(0, len(rows) - capacity))
+ return index, start, min(start + capacity, len(rows))
+
+
+def _wide_serving(lines: list[str], snapshot: dict, width: int, height: int,
+ filter_text: str, selected: int) -> str:
+ work, rates = snapshot.get("work") or {}, snapshot.get("rates") or {}
+ topology, devices = snapshot.get("topology") or {}, snapshot.get("devices") or []
+ recent = snapshot.get("recent") or []
+ lines += [f"Topology {safe(topology.get('mode'))} | Requested {number(work.get('slots_requested'))} / effective {number(work.get('slots_effective'))} slots | Groups {number(work.get('groups'))}",
+ f"Outside slots {number(work.get('outside_slots'))} Total output {number(rates.get('aggregate_output_tok_s'), ' tok/s', 1)} [common sample] Disconnect cancels {number(work.get('client_disconnect_cancels'))}",
+ f"Admission {number(work.get('admission_reserved'))}/{number(work.get('admission_limit'))} reserved/limit Queue cap {number(work.get('max_queue'))} Rejected {number(work.get('admission_rejected'))} Timed out {number(work.get('queue_timeouts'))}",
+ f"Wait limit {number(work.get('queue_timeout_s'), 's', 1)} Oldest wait {number(work.get('oldest_queue_s'), 's', 1)}",
+ f"First engine token {number(recent[0].get('first_engine_token_s') if recent else None, ' s', 3)} [last completed, since queue entry]",
+ _batch_window(work, width),
+ _stage_in_flight(work, width),
+ "-" * min(width, 110)]
+ left_width = max(56, width - 47)
+ left = ["REQUEST FLOW (no-slot first; wait = queue time)"]
+ # When height is scarce, preserve pressure outside the batch window; slot rows remain in the Groups pane.
+ all_requests = work.get("requests") or []
+ requests = sorted((row for row in all_requests if not filter_text or
+ filter_text.lower() in (safe(row.get("id")) + safe(row.get("state"))).lower()),
+ key=lambda row: row.get("slot") is not None)
+ if requests:
+ for row in requests:
+ wait = _queue_wait(row, snapshot.get("sampled_at"))
+ left.append(_line(f"{field(row.get('id'), 12)} {_replica_short(row)}s{number(row.get('slot')):<2} g{number(row.get('group')):<2} {field(row.get('state'), 9)} wait {number(wait, 's', 1):<6} {_request_work(row)}", left_width))
+ elif all_requests:
+ left.append("No matching request summaries")
+ else:
+ left.append("Request identity unavailable; showing engine slots")
+ for row in work.get("slots") or []:
+ left.append(_line(f"{_replica_short(row)}slot {number(row.get('slot')):<2} group {number(row.get('group')):<2} {field(row.get('state'), 10)} in {number(row.get('prompt_tokens')):<7} {_request_work(row)}", left_width))
+ # Reserve space for group occupancy, mapping provenance and the footer at standard 30-row terminals.
+ count = min(max(len(left), len(devices) + 1), max(1, height - len(lines) - 8))
+ right = ["GPU SENSORS (per card)"]
+ if devices:
+ capacity = max(1, count - 1)
+ _, start, end = _row_window(devices, selected, capacity)
+ if start:
+ right[0] = f"GPU SENSORS ({start + 1}-{end}/{len(devices)})"
+ for i in range(start, end):
+ row = devices[i]
+ used, total = row.get("mem_used"), row.get("mem_total")
+ memory = f"{number(used / 2**30 if isinstance(used, (int, float)) else None, '', 1)}/{number(total / 2**30 if isinstance(total, (int, float)) else None, '', 1)}G"
+ right.append(_line(f"{'>' if i == selected else ' '} GPU {number(row.get('index')):<2} {field(row.get('name'), 8)} {memory:<11} {number(row.get('util'), '%'):>4} {number(row.get('temp'), 'C'):>4} {number(row.get('power'), 'W'):>5}", width-left_width-2))
+ else:
+ right.append("Per-device sensors unavailable")
+ lines += [f"{field(left[i] if i < len(left) else '', left_width)} {_line(right[i] if i < len(right) else '', width-left_width-2)}".rstrip()
+ for i in range(count)]
+ if len(left) > count:
+ lines.append(f"+{len(left) - count} more requests; use Requests view")
+ groups = group_occupancy(work)
+ lines += ["", ("Occupied slots by group " +
+ " ".join(f"G{g} {busy}/{total}" for g, (busy, total) in sorted(groups.items()))
+ if groups is not None else "Occupied slots by group -- (slot report incomplete)")]
+ if topology.get("resolved") is True:
+ ranges = " ".join(f"GPU {number(row.get('device_index'))}: {number(row.get('layer_start'))}-{number(row.get('layer_end'))}"
+ for row in topology.get("stages") or [])
+ lines += [_line(f"Engine stage layers [start log] {ranges}", width)]
+ elif any(entry.get("stages") for entry in topology.get("replica_stages") or []):
+ ranges = " ".join(
+ f"R{entry['replica']} GPU {number(stage.get('device_index'))}: "
+ f"{number(stage.get('layer_start'))}-{number(stage.get('layer_end'))}"
+ for entry in topology["replica_stages"] for stage in entry["stages"])
+ lines += [_line(f"Replica stage layers [start log] {ranges}", width)]
+ elif topology.get("stages"):
+ lines += ["Engine stage ranges reported; card mapping unavailable"]
+ else:
+ lines += ["Stage/layer mapping unavailable; groups are not GPU assignments"]
+ age = time.time() - snapshot["sampled_at"] if isinstance(snapshot.get("sampled_at"), (int, float)) else None
+ lines += ["", f"Sample age {number(age, ' s', 1)} | Source {safe(snapshot.get('source'))}",
+ "1-6 views / filter Space freeze r refresh t theme ? help q quit"]
+ return "\n".join(_line(x, width) for x in lines[:height])
+
+
+def render_view(snapshot: dict, view: str, width: int = 80, height: int = 24,
+ selected: int = 0, frozen: bool = False, filter_text: str = "",
+ glyphs: str = "ascii", connection: str = "", serving_pane: str = "devices",
+ detail: bool = False, connection_state: str | None = None) -> str:
+ """Render the six views with explicit unavailable markers and no fake rates."""
+ width, height = max(width, 30), max(height, 8)
+ tiny = width < 60 or height < 14
+ view = view if view in VIEWS else "overview"
+ model = snapshot.get("model") or {}
+ instance = snapshot.get("instance") or {}
+ model_state = ("DRAINING" if instance.get("state") == "draining" else
+ "READY" if model.get("loaded") is True else
+ "NO MODEL LOADED" if model.get("loaded") is False else "UNKNOWN")
+ work = snapshot.get("work") or {}
+ rates = snapshot.get("rates") or {}
+ topology = snapshot.get("topology") or {}
+ devices = snapshot.get("devices") or []
+ recent = snapshot.get("recent") or []
+ totals = snapshot.get("totals") or {}
+ sampled = snapshot.get("sampled_at")
+ age = time.time() - sampled if isinstance(sampled, (int, float)) else None
+ if (snapshot.get("quality") or {}).get("telemetry") == "unavailable":
+ connection_state = "telemetry_unavailable" if connection_state in (None, "connected") else connection_state
+ if connection_state is None:
+ marker = "[FROZEN]" if frozen else ("[STALE]" if age is not None and age > 5 else "[LIVE]")
+ else:
+ labels = {"connecting": "CONNECTING", "connected": "LIVE", "stale": "STALE",
+ "auth_required": "AUTH REQUIRED", "incompatible": "INCOMPATIBLE",
+ "disconnected": "DISCONNECTED", "telemetry_unavailable": "NO TELEMETRY"}
+ state = connection_state if connection_state in labels else "stale"
+ if state == "connected" and (age is None or age > 5 or age < -5):
+ state = "stale"
+ if state != "connected":
+ rates = {**rates, "answer_tok_s": None, "prefill_tok_s": None,
+ "aggregate_output_tok_s": None, "answer_window_s": None,
+ "aggregate_window_s": None}
+ snapshot = {**snapshot, "rates": rates}
+ if frozen:
+ short = {"connecting": "CONNECT", "connected": "", "stale": "STALE",
+ "auth_required": "AUTH", "incompatible": "SCHEMA",
+ "disconnected": "OFFLINE", "telemetry_unavailable": "NO METRICS"}[state]
+ marker = f"[FROZEN/{short}]" if short else "[FROZEN]"
+ else:
+ marker = f"[{labels[state]}]"
+ lines = [f"STRATA {view.title():<10} {safe(connection, max(0, width - 42))} {marker}"]
+ if width >= 60 and height >= 16:
+ if width < 80:
+ labels = ("Over", "Serve", "Reqs", "Engine", "GPU", "Logs")
+ nav = " ".join(f"[{i + 1}]{label}" if VIEWS[i] == view else f"{i + 1}{label}"
+ for i, label in enumerate(labels)) + " q quit"
+ else:
+ nav = " ".join(f"[{i + 1} {name.title()}]" if name == view else f"{i + 1} {name.title()}"
+ for i, name in enumerate(VIEWS))
+ lines += [_line(nav, width), "-" * min(width, 100)]
+ else:
+ lines += [f"1-6 views q quit ? help", "-" * min(width, 100)]
+ if connection_state in ("connecting", "disconnected", "auth_required", "incompatible"):
+ title, message, action = {
+ "connecting": ("CONNECTING", "Waiting for the first telemetry snapshot.",
+ "The monitor will update automatically."),
+ "disconnected": ("CONNECTION LOST", "Strata is not responding.",
+ "Retrying automatically; press r now."),
+ "auth_required": ("AUTHORIZATION REQUIRED", "The telemetry credential was rejected.",
+ "Update the saved connection; press r."),
+ "incompatible": ("INCOMPATIBLE SERVER", "This telemetry schema is unsupported.",
+ "Connect to a compatible server; press r."),
+ }[connection_state]
+ last_seen = (f"Last snapshot {number(age, ' s', 1)} ago" if age is not None and age >= 0
+ else "No telemetry snapshot available")
+ lines += [title, message, action, last_seen]
+ if tiny:
+ lines = lines[:height - 1] + ["More: strata status --json"]
+ return "\n".join(_line(line, width) for line in lines[:height])
+ if connection_state is not None and (state != "connected" or frozen):
+ lines.append(f"Sample age {number(age, ' s', 1)} | Source {safe(snapshot.get('source'))}")
+ if (snapshot.get("quality") or {}).get("telemetry") == "unavailable":
+ lines.append("Telemetry unavailable; status only")
+ if width < 70 or height < 20:
+ lines += [_line(f"Model {safe(model.get('id'), width-17)} {model_state}", width),
+ f"In flight {number(work.get('active'))} Slots {number(work.get('occupied_slots'))}/{number(work.get('slots_effective'))}",
+ f"Engine waiting {number(work.get('waiting'))} Pre-admit {number(work.get('queued'))}"]
+ if not tiny:
+ lines.append(f"Answer {number(rates.get('answer_tok_s'), ' tok/s', 1)} GPUs {len(devices) or '--'}")
+ if view == "requests":
+ live, done = request_rows(snapshot, filter_text)
+ rows = [("LIVE", row) for row in live] + [("DONE", row) for row in done]
+ if rows:
+ index = min(max(0, selected), len(rows) - 1)
+ kind, row = rows[index]
+ label = row.get("id") or (f"#{index - len(live) + 1}" if kind == "DONE" else None)
+ lines.append(f"{index + 1}/{len(rows)} {kind} {safe(label, 12)}")
+ if kind == "DONE":
+ lines += [f"{safe(row.get('finish'), 10)} out {number(row.get('output_tokens'))} {number(row.get('duration_s'), ' s', 1)}"]
+ if detail:
+ lines += [f"Prompt {number(row.get('prompt_tokens'))} cached {number(row.get('reused'))}",
+ f"Engine first {number(row.get('first_engine_token_s'), ' s', 2)}"]
+ else:
+ lines += [f"slot {number(row.get('slot'))} group {number(row.get('group'))} {_request_work(row)}"]
+ if detail:
+ lines += [f"Prompt {number(row.get('prompt_tokens'))} tokens",
+ f"Wait {number(_queue_wait(row, sampled), ' s', 1)} Engine first {number(row.get('first_engine_token_s'), ' s', 2)}"]
+ else:
+ lines += ["No request summaries"]
+ elif view == "serving":
+ optional = [_batch_window(work, width), _stage_in_flight(work, width)]
+ if not tiny:
+ lines += optional
+ live, _ = request_rows(snapshot, filter_text)
+ rows = (work.get("slots") or []) if serving_pane == "groups" else \
+ devices if serving_pane == "devices" else live
+ if rows:
+ index = min(max(0, selected), len(rows) - 1)
+ row = rows[index]
+ lines.append(f"{serving_pane.title()} {index + 1}/{len(rows)}")
+ if serving_pane == "devices":
+ lines.append(_device(row, width))
+ if detail:
+ lines += [f"VRAM {number(row.get('mem_used') / 2**30 if isinstance(row.get('mem_used'), (int, float)) else None, ' GiB', 1)}",
+ f"Util {number(row.get('util'), '%')} Temp {number(row.get('temp'), ' C')} Power {number(row.get('power'), ' W')}",
+ _device_stage(topology, row.get("index"), width)]
+ else:
+ lines += [f"{safe(row.get('id') or row.get('request_id'), 12)} {safe(row.get('state'), 10)}",
+ f"slot {number(row.get('slot'))} group {number(row.get('group'))} {_request_work(row)}"]
+ if detail and serving_pane == "requests":
+ lines += [f"Prompt {number(row.get('prompt_tokens'))} tokens",
+ f"Wait {number(_queue_wait(row, sampled), ' s', 1)} Engine first {number(row.get('first_engine_token_s'), ' s', 2)}"]
+ elif detail and serving_pane == "groups":
+ lines += [f"Held {number(row.get('held_tokens'))} Read {number(row.get('prompt_read'))} Out {number(row.get('generated'))}",
+ f"Elapsed {number(row.get('elapsed_s'), ' s', 1)} Rate {number(row.get('tok_s'), ' tok/s', 1)}"]
+ else:
+ lines += [f"{serving_pane.title()} unavailable"]
+ if tiny:
+ lines += optional
+ elif view == "hardware":
+ if devices:
+ index = min(max(0, selected), len(devices) - 1)
+ row = devices[index]
+ lines += [f"Device {index + 1}/{len(devices)}", _device(row, width)]
+ if detail:
+ lines += [f"Temp {number(row.get('temp'), ' C')} Power {number(row.get('power'), ' W')}",
+ _device_stage(topology, row.get("index"), width)]
+ else:
+ lines.append("Per-device sensors unavailable")
+ elif view == "engine":
+ lines += [_batch_window(work, width), _stage_in_flight(work, width)]
+ elif view == "logs":
+ activity = snapshot.get("activity") or {}
+ if not activity.get("available"):
+ lines += ["Request activity unavailable on this server"]
+ else:
+ events = activity_rows(snapshot, filter_text)
+ lines += ["Recent request activity (redacted)"]
+ notice = activity_continuity_notice(snapshot)
+ if notice:
+ lines.append(notice)
+ lines += [activity_label(row, width) for row in events[-max(1, height - len(lines) - 1):]] \
+ if events else ["No request transitions retained"]
+ else:
+ if not tiny:
+ lines += ["More: strata status --json"]
+ if tiny:
+ lines = lines[:height - 1] + ["More: strata status --json"]
+ return "\n".join(_line(x, width) for x in lines[:height])
+ lines += [f"Model {safe(model.get('id'), max(10, width-30))} {model_state}",
+ f"In flight {number(work.get('active'))} Slots occupied {number(work.get('occupied_slots'))}/{number(work.get('slots_effective'))} Engine waiting {number(work.get('waiting'))} Pre-admit {number(work.get('queued'))}"]
+ if view == "serving" and width >= 100 and height >= 24 and serving_pane == "devices" and not detail:
+ return _wide_serving(lines, snapshot, width, height, filter_text, selected)
+ if view == "overview":
+ lines += [f"Answer speed {number(rates.get('answer_tok_s'), ' tok/s', 1)} [engine, {number(rates.get('answer_window_s'), ' s', 1)} window]",
+ f"Prompt reading {number(rates.get('prefill_tok_s'), ' tok/s', 1)} [reported mean]",
+ f"First engine token {number(recent[0].get('first_engine_token_s') if recent else None, ' s', 3)} [last completed, since queue entry]",
+ f"Completed {number(totals.get('requests'))} [server lifetime]",
+ "", "Hardware"]
+ lines += [_device(d, width) for d in devices[:4]] or ["Per-device readings unavailable"]
+ lines += ["", "Recent requests (finished; identities unavailable in legacy telemetry)"]
+ for i, r in enumerate(recent[:max(1, height-len(lines)-3)]):
+ lines.append(_line(f"#{i+1:<3} {field(r.get('finish'), 13)} in {number(r.get('prompt_tokens')):<8} out {number(r.get('output_tokens')):<8} {number(r.get('duration_s'), ' s', 1)}", width))
+ elif view == "serving":
+ lines += [f"Topology {safe(topology.get('mode'))} Devices {number(len(devices))} Groups {number(work.get('groups'))}",
+ f"Slots requested {number(work.get('slots_requested'))} / effective {number(work.get('slots_effective'))}",
+ f"Admission {number(work.get('admission_reserved'))}/{number(work.get('admission_limit'))} Cap {number(work.get('max_queue'))} Rejected {number(work.get('admission_rejected'))}",
+ f"Wait limit {number(work.get('queue_timeout_s'), 's', 1)} Timed out {number(work.get('queue_timeouts'))} Oldest {number(work.get('oldest_queue_s'), 's', 1)}",
+ f"Disconnect cancels {number(work.get('client_disconnect_cancels'))} Output {number(rates.get('aggregate_output_tok_s'), ' tok/s', 1)} [common sample]",
+ _batch_window(work, width)]
+ if work.get("stage_in_flight") or work.get("replica_stage_samples"):
+ lines.append(_stage_in_flight(work, width))
+ lines.append(f"Pane: {serving_pane.title()} Tab switches Devices / Requests / Groups")
+ if not detail and serving_pane == "requests":
+ lines.insert(-1, f"First engine token {number(recent[0].get('first_engine_token_s') if recent else None, ' s', 3)} [last completed, since queue entry]")
+ if not work.get("stage_in_flight") and not (detail and serving_pane == "requests"):
+ lines.append("")
+ if serving_pane == "requests":
+ rows = [r for r in (work.get("requests") or []) if not filter_text or
+ filter_text.lower() in (safe(r.get("id")) + safe(r.get("state"))).lower()]
+ capacity = max(1, height - len(lines) - (10 if detail and rows else 4))
+ start = min(max(0, selected - capacity // 2), max(0, len(rows) - capacity))
+ lines += [f"Requests {start + 1 if rows else 0}-{min(start + capacity, len(rows))} of {len(rows)} (Up/Down scroll; wait is queue time)"]
+ for i, row in enumerate(rows[start:start + capacity], start):
+ wait = _queue_wait(row, sampled)
+ cursor = ">" if i == selected else " "
+ lines.append(_line(f"{cursor}{field(row.get('id'), 12)} {_replica_short(row)}s{number(row.get('slot')):<3} g{number(row.get('group')):<3} {field(row.get('state'), 9)} wait {number(wait, ' s', 1):<8} {_request_work(row)}", width))
+ if not rows:
+ lines.append("Request correlation unavailable")
+ elif detail:
+ lines += _request_detail(rows[min(selected, len(rows) - 1)], sampled, width)
+ elif serving_pane == "groups":
+ rows = work.get("slots") or []
+ capacity = max(1, height - len(lines) - (10 if detail else 4))
+ start = min(max(0, selected - capacity // 2), max(0, len(rows) - capacity))
+ scope = "replica / pipeline group" if str(topology.get("mode") or "").startswith("replicas") else "pipeline group"
+ lines += [f"Slot / {scope} {start + 1 if rows else 0}-{min(start + capacity, len(rows))} of {len(rows)} (occupancy is not rows/window)"]
+ for i, row in enumerate(rows[start:start + capacity], start):
+ cursor = ">" if i == selected else " "
+ lines.append(_line(f"{cursor}{_replica_short(row)}slot {number(row.get('slot')):<3} group {number(row.get('group')):<3} {field(row.get('state'), 11)} req {field(row.get('request_id'), 12)} in {number(row.get('prompt_tokens')):<7} {_request_work(row)} {number(row.get('tok_s'), ' tok/s', 1)}", width))
+ if not rows:
+ lines.append("Slot detail unavailable")
+ elif detail:
+ lines += _slot_detail(rows[min(max(0, selected), len(rows) - 1)], width)
+ else:
+ lines += ["Per-card sensors; each request stays within one replica" if
+ str(topology.get("mode") or "").startswith("replicas") else
+ "Per-card sensors; requests traverse all stages" if topology.get("resolved") is True
+ else "Stage/layer mapping unavailable; groups are not GPU assignments"]
+ if devices:
+ capacity = max(1, height - len(lines) - (11 if detail else 4))
+ index, start, end = _row_window(devices, selected, capacity)
+ lines.append(f"Devices {start + 1}-{end} of {len(devices)} (Up/Down scroll; Enter detail)")
+ for i in range(start, end):
+ lines.append(_line(("> " if i == index else " ") + _device(devices[i], width - 2), width))
+ if detail:
+ lines += _device_detail(devices[index], topology, width)
+ else:
+ lines.append("Per-device readings unavailable")
+ elif view == "requests":
+ active, shown = request_rows(snapshot, filter_text)
+ rows = [("LIVE", row) for row in active] + [("DONE", row) for row in shown]
+ lines += [f"Live {len(active)} / recent {len(shown)} No prompt bodies", ""]
+ if rows:
+ index = min(max(0, selected), len(rows) - 1)
+ capacity = max(1, height - len(lines) - (10 if detail else 4))
+ start = min(max(0, index - capacity // 2), max(0, len(rows) - capacity))
+ lines.append(f"Requests {start + 1}-{min(start + capacity, len(rows))} of {len(rows)} (Up/Down scroll; Enter detail)")
+ for i in range(start, min(start + capacity, len(rows))):
+ kind, row = rows[i]
+ cursor = ">" if i == index else " "
+ if kind == "LIVE":
+ summary = f"{field(row.get('id'), 12)} {field(row.get('state'), 11)} s{number(row.get('slot')):<3} g{number(row.get('group')):<3} in {number(row.get('prompt_tokens')):<7} {_request_work(row)}"
+ else:
+ summary = f"{field(row.get('id') or f'#{i - len(active) + 1}', 12)} {field(row.get('finish'), 11)} in {number(row.get('prompt_tokens')):<7} cached {number(row.get('reused')):<7} out {number(row.get('output_tokens')):<7} {number(row.get('duration_s'), ' s', 1)}"
+ lines.append(_line(f"{cursor} {kind:<4} {summary}", width))
+ if detail:
+ kind, row = rows[index]
+ lines += (_request_detail(row, sampled, width) if kind == "LIVE" else _recent_detail(row, width))
+ else:
+ lines.append("No request summaries")
+ elif view == "engine":
+ lines += [f"Context capacity {number(model.get('context'), ' tokens')}",
+ f"Batch groups {number(work.get('groups'))}",
+ _batch_window(work, width)]
+ if work.get("stage_in_flight") or work.get("replica_stage_samples"):
+ lines.append(_stage_in_flight(work, width))
+ lines += [f"Answer rate {number(rates.get('answer_tok_s'), ' tok/s', 1)} [engine window]",
+ f"Prompt rate {number(rates.get('prefill_tok_s'), ' tok/s', 1)} [engine reported]", ""]
+ if topology.get("replica_stages"):
+ lines.append("Replica layers [engine log]; in-flight [host span]; groups are not GPU assignments")
+ sampled_replicas = {row["replica"]: {stage["stage"]: stage
+ for stage in row.get("stage_in_flight") or []}
+ for row in work.get("replica_stage_samples") or []}
+ sample_meta = {row["replica"]: row for row in work.get("replica_stage_samples") or []}
+ for entry in topology["replica_stages"]:
+ meta = sample_meta.get(entry["replica"], {})
+ if meta.get("stage_in_flight"):
+ lines.append(_line(f"R{entry['replica']} host sample "
+ f"{number(meta.get('stage_sample_span_s'), 's', 1)} span, "
+ f"{number(meta.get('stage_sample_age_s'), 's', 1)} old", width))
+ if not entry["stages"]:
+ lines.append(f"R{entry['replica']} stage ranges unavailable")
+ for stage in entry["stages"]:
+ sample = sampled_replicas.get(entry["replica"], {}).get(stage["stage"])
+ lines.append(_line(f"R{entry['replica']} Stage {number(stage.get('stage'))} "
+ f"Device {number(stage.get('device_index'))} "
+ f"Layers {number(stage.get('layer_start'))}-{number(stage.get('layer_end'))} "
+ f"In-flight {number(sample.get('percent') if sample else None, '%', 0)}", width))
+ elif topology.get("stages"):
+ lines.append("Layer allocation [engine start log]; stage in-flight [host scheduling]")
+ sampled = {row["stage"]: row for row in work.get("stage_in_flight") or []}
+ for stage in topology["stages"]:
+ row = sampled.get(stage.get("stage"))
+ lines.append(_line(f"Stage {number(stage.get('stage'))} Engine GPU {number(stage.get('engine_ordinal'))} Device {number(stage.get('device_index'))} Layers {number(stage.get('layer_start'))}-{number(stage.get('layer_end'))} In-flight {number(row.get('percent') if row else None, '%', 0)}", width))
+ else:
+ lines.append("Stage/layer mapping unavailable")
+ lines.append("In-flight includes host poll delay; GPU kernel occupancy unavailable" if
+ work.get("stage_in_flight") or any(row.get("stage_in_flight") for row in
+ work.get("replica_stage_samples") or [])
+ else "Live stage in-flight and GPU kernel occupancy unavailable")
+ elif view == "hardware":
+ lines += ["Device sensors; missing measurements are shown as --", ""]
+ if devices:
+ capacity = max(1, height - len(lines) - (10 if detail else 6))
+ index, start, end = _row_window(devices, selected, capacity)
+ lines.append(f"Devices {start + 1}-{end} of {len(devices)} (Up/Down scroll; Enter detail)")
+ for i in range(start, end):
+ lines.append(_line(("> " if i == index else " ") + _device(devices[i], width - 2), width))
+ if detail:
+ lines += _device_detail(devices[index], topology, width)
+ else:
+ lines.append("No per-device sensor readings")
+ ram = snapshot.get("ram") or {}
+ used, total = ram.get("used"), ram.get("total")
+ lines += ["", f"RAM {number(used / 2**30 if isinstance(used, (int, float)) else None, ' GiB', 1)} / {number(total / 2**30 if isinstance(total, (int, float)) else None, ' GiB', 1)}"]
+ else:
+ activity = snapshot.get("activity") or {}
+ lines += ["Recent request activity (redacted; no prompt or tool content)", ""]
+ if not activity.get("available"):
+ lines.append("Request activity unavailable on this server")
+ else:
+ events = activity_rows(snapshot, filter_text)
+ last_seq = activity.get("last_seq")
+ retained = len(activity.get("events") or [])
+ older = " | older omitted" if isinstance(last_seq, int) and last_seq > retained else ""
+ lines.append(f"Recent {len(events)}/{retained} retained | sequence {number(last_seq)}{older}")
+ notice = activity_continuity_notice(snapshot)
+ if notice:
+ lines.append(notice)
+ if events:
+ capacity = max(1, height - len(lines) - 4)
+ lines += [activity_label(row, width) for row in events[-capacity:]]
+ else:
+ lines.append("No matching request transitions" if filter_text else "No request transitions retained")
+ if not detail:
+ lines.append("")
+ lines += [f"Sample age {number(age, ' s', 1)} Source {safe(snapshot.get('source'))}",
+ "1-6 views / filter Space freeze r refresh t theme ? help q quit"]
+ return "\n".join(_line(x, width) for x in lines[:height])
diff --git a/strata_control/__init__.py b/strata_control/__init__.py
new file mode 100644
index 000000000..a105e3f28
--- /dev/null
+++ b/strata_control/__init__.py
@@ -0,0 +1 @@
+"""Local operator contracts shared by terminal and future Desktop clients."""
diff --git a/strata_control/benchmarking.py b/strata_control/benchmarking.py
new file mode 100644
index 000000000..a63dbdfc0
--- /dev/null
+++ b/strata_control/benchmarking.py
@@ -0,0 +1,408 @@
+"""Reviewed Desktop launch of the same serving benchmark used by the CLI."""
+
+from __future__ import annotations
+
+import hashlib
+import errno
+import os
+import re
+import stat
+import time
+from contextlib import contextmanager
+from pathlib import Path
+
+from strata_cli import bench
+from strata_cli.cli import _launch_plan, _source
+from strata_cli.client import ClientError, Endpoint
+from strata_control import journal, profiles, runtime
+from strata_control.profiles import ProfileError
+
+
+def _lease_file(profile: str, *, create: bool) -> Path | None:
+ if not profiles.PROFILE_ID.fullmatch(profile):
+ raise ProfileError("benchmark lease needs a saved profile")
+ directory = profiles.profile_dir()
+ if create:
+ directory.mkdir(mode=0o700, parents=True, exist_ok=True)
+ elif not directory.exists():
+ return None
+ details = directory.lstat()
+ if not stat.S_ISDIR(details.st_mode) or (os.name == "posix" and
+ (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)):
+ raise ProfileError("benchmark lease directory must be owner-only", 5)
+ return directory / f".bench-{profile}.lock"
+
+
+def _lease_descriptor(path: Path, *, create: bool) -> int:
+ flags = os.O_RDWR | (os.O_CREAT if create else 0)
+ if hasattr(os, "O_NOFOLLOW"):
+ flags |= os.O_NOFOLLOW
+ descriptor = os.open(path, flags, 0o600)
+ details = os.fstat(descriptor)
+ if not stat.S_ISREG(details.st_mode) or details.st_nlink != 1 or details.st_size > 65 or (os.name == "posix" and
+ (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)):
+ os.close(descriptor)
+ raise ProfileError("benchmark lease file must be owner-only", 5)
+ return descriptor
+
+
+def _lock(descriptor: int, *, initialize: bool = False) -> None:
+ if initialize and os.fstat(descriptor).st_size == 0:
+ os.lseek(descriptor, 0, os.SEEK_SET)
+ os.write(descriptor, b"0")
+ if os.name == "nt":
+ import msvcrt
+ os.lseek(descriptor, 0, os.SEEK_SET)
+ msvcrt.locking(descriptor, msvcrt.LK_NBLCK, 1)
+ else:
+ import fcntl
+ fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
+
+
+def _unlock(descriptor: int) -> None:
+ if os.name == "nt":
+ import msvcrt
+ os.lseek(descriptor, 0, os.SEEK_SET)
+ msvcrt.locking(descriptor, msvcrt.LK_UNLCK, 1)
+ else:
+ import fcntl
+ fcntl.flock(descriptor, fcntl.LOCK_UN)
+
+
+def _path_digest(path: Path) -> bytes:
+ return hashlib.sha256(os.fsencode(os.path.abspath(path))).hexdigest().encode("ascii")
+
+
+@contextmanager
+def benchmark_lease(profile: str, path: Path | None = None):
+ """Refuse overlapping local runs for one saved profile across host processes."""
+ target = _lease_file(profile, create=True)
+ descriptor = _lease_descriptor(target, create=True)
+ try:
+ try:
+ _lock(descriptor, initialize=True)
+ except OSError:
+ raise ProfileError("another benchmark is running for this saved profile", 6) from None
+ try:
+ marker = _path_digest(path) if path is not None else b"x" * 64
+ os.lseek(descriptor, 1, os.SEEK_SET)
+ if os.write(descriptor, marker) != len(marker):
+ raise ProfileError("cannot record benchmark lease identity", 5)
+ os.fsync(descriptor)
+ yield
+ finally:
+ _unlock(descriptor)
+ finally:
+ os.close(descriptor)
+
+
+def benchmark_activity(profile: str, path: Path) -> str:
+ """Check the exact saved run's lease, without using PID files or stale timestamps."""
+ target = _lease_file(profile, create=False)
+ if target is None:
+ return "untracked"
+ try:
+ descriptor = _lease_descriptor(target, create=False)
+ except FileNotFoundError:
+ return "untracked"
+ try:
+ if os.name == "nt" and os.fstat(descriptor).st_size == 0:
+ return "untracked"
+ try:
+ _lock(descriptor)
+ except OSError as exc:
+ if exc.errno not in (errno.EAGAIN, errno.EACCES) and getattr(exc, "winerror", None) != 33:
+ raise ProfileError("cannot inspect benchmark lease", 5) from None
+ os.lseek(descriptor, 1, os.SEEK_SET)
+ recorded = os.read(descriptor, 65)
+ if recorded == _path_digest(path):
+ return "active"
+ return "other_active" if re.fullmatch(rb"[0-9a-f]{64}", recorded) else "untracked"
+ else:
+ try:
+ os.lseek(descriptor, 1, os.SEEK_SET)
+ recorded = os.read(descriptor, 65)
+ return "ended" if recorded == _path_digest(path) else "untracked"
+ finally:
+ _unlock(descriptor)
+ finally:
+ os.close(descriptor)
+
+
+def request_cancel(profile: str, path: Path) -> dict:
+ """Request cancellation only for the exact active owner-local benchmark."""
+ directory = path.parent if path.name in ("results.json", "progress.json") else path
+ details = directory.lstat()
+ if not stat.S_ISDIR(details.st_mode) or (os.name == "posix" and
+ (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)):
+ raise ProfileError("benchmark output directory must be owner-only", 5)
+ if benchmark_activity(profile, directory) != "active":
+ raise ProfileError("the exact benchmark run is not active", 6)
+ if bench.progress(directory)["state"] != "running":
+ raise ProfileError("benchmark already saved its final report", 6)
+ marker = directory / "cancel.request"
+ try:
+ descriptor = os.open(marker, os.O_WRONLY | os.O_CREAT | os.O_EXCL |
+ getattr(os, "O_NOFOLLOW", 0), 0o600)
+ except FileExistsError:
+ details = marker.lstat()
+ if not stat.S_ISREG(details.st_mode) or details.st_nlink != 1 or details.st_size != 1 or (os.name == "posix" and
+ (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)):
+ raise ProfileError("benchmark cancellation marker is invalid", 5)
+ else:
+ try:
+ os.write(descriptor, b"1")
+ os.fsync(descriptor)
+ finally:
+ os.close(descriptor)
+ current = bench.progress(directory)
+ if current["state"] == "report_saved":
+ raise ProfileError("benchmark already saved its final report", 6)
+ return {"ok": True, "path": str(directory / "results.json"),
+ "state": "cancelled" if current["state"] == "cancelled" else "cancel_requested"}
+
+
+def cancel_requested(directory: Path) -> bool:
+ """Read the private marker without treating a stale marker as process liveness."""
+ marker = directory / "cancel.request"
+ try:
+ details = marker.lstat()
+ except FileNotFoundError:
+ return False
+ if not stat.S_ISREG(details.st_mode) or details.st_nlink != 1 or details.st_size != 1 or (os.name == "posix" and
+ (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)):
+ raise ProfileError("benchmark cancellation marker is invalid", 5)
+ return True
+
+
+def _settings(profile: str, params: dict) -> tuple[dict, dict, Endpoint, Endpoint, Path]:
+ suite, concurrency, repeat = params["suite"], params["concurrency"], params["repeat"]
+ timeout, condition = params["request_timeout"], params["condition"]
+ if suite not in bench.SUITES:
+ raise ProfileError("unknown serving benchmark suite")
+ maximum = 64 if suite == "parallel-overload-v1" else 16
+ if (type(concurrency) is not int or not 1 <= concurrency <= maximum or
+ type(repeat) is not int or not 1 <= repeat <= 5 or
+ type(timeout) not in (int, float) or not 1 <= timeout <= 600):
+ raise ProfileError("benchmark workload settings are outside supported bounds")
+ if condition is not None and (not isinstance(condition, str) or
+ not re.fullmatch(r"[a-z][a-z0-9_-]{0,39}", condition)):
+ raise ProfileError("benchmark condition must be a lowercase name up to 40 characters")
+ phase_count = sum(1 if kind in ("warmup", "recovery", "cancel_active",
+ "cancel_queued", "cancel_prefill") else repeat
+ for kind in bench.SUITES[suite])
+ if phase_count * (timeout + 30) > 1700:
+ raise ProfileError("benchmark workload exceeds the Desktop job limit; reduce timeout or repeats")
+ path = Path(params["path"])
+ if path.exists() or path.is_symlink():
+ raise ProfileError("benchmark output directory already exists", 2)
+ if not path.parent.is_dir():
+ raise ProfileError("benchmark output parent directory does not exist", 2)
+ source, saved, revision, cfg = _source(profile)
+ if saved is None or revision is None:
+ raise ProfileError("Desktop benchmark requires a saved profile")
+ launch, _ = _launch_plan(profile)
+ host = launch["effective"]["host"]
+ host = "127.0.0.1" if host in ("0.0.0.0", "::") else host
+ authority = f"[{host}]" if ":" in host and not host.startswith("[") else host
+ url = f"http://{authority}:{launch['effective']['port']}"
+ key = os.environ.get("STRATA_API_KEY")
+ endpoint = Endpoint(url, key, timeout=10)
+ telemetry = Endpoint(url, os.environ.get("STRATA_TELEMETRY_KEY") or key, timeout=3)
+ identity = {"profile": profile, "revision": revision, "source_config": str(source),
+ "source_sha256": hashlib.sha256(source.read_bytes()).hexdigest(),
+ "model_name": cfg.get("model_name"), "gpu": cfg.get("gpu")}
+ return launch, identity, endpoint, telemetry, path
+
+
+def plan(profile: str, params: dict) -> dict:
+ launch, identity, endpoint, telemetry, path = _settings(profile, params)
+ try:
+ snapshot = telemetry.snapshot()
+ except ClientError as exc:
+ raise ProfileError("benchmark telemetry is unavailable: " + str(exc), 5) from None
+ match = bench._managed_match(identity, endpoint.root, snapshot)
+ if not match["matched"]:
+ raise ProfileError("managed benchmark preflight failed: " + match["reason"], 5)
+ owner = runtime.status(profile)
+ owner_id = owner.get("owner_id")
+ if (owner.get("state") != "ready" or owner.get("instance_id") != match["instance_id"] or
+ owner.get("profile_revision") != identity["revision"] or
+ not isinstance(owner_id, str) or
+ not re.fullmatch(r"[0-9a-f]{32}", owner_id)):
+ raise ProfileError("benchmark owner identity is unavailable", 5)
+ if (snapshot.get("model") or {}).get("loaded") is not True:
+ raise ProfileError("benchmark needs a loaded model", 5)
+ work = snapshot.get("work") or {}
+ suite, count, repeat = params["suite"], params["concurrency"], params["repeat"]
+ if suite == "parallel-overload-v1":
+ limit, deadline = work.get("admission_limit"), work.get("queue_timeout_s")
+ if (type(limit) is not int or limit < 1 or type(deadline) not in (int, float) or
+ deadline <= 0 or count <= limit):
+ raise ProfileError("overload benchmark needs configured admission and concurrency above its limit", 5)
+ if suite in ("parallel-cancel-v1", "parallel-prefill-cancel-v1"):
+ slots = work.get("slots_effective")
+ if (type(slots) is not int or not 1 <= slots <= 16 or
+ type(work.get("client_disconnect_cancels")) is not int):
+ raise ProfileError("cancellation benchmark needs 1..16 slots and disconnect telemetry", 5)
+ if suite == "parallel-cancel-v1" and (count < slots or
+ type(work.get("max_queue")) is not int or work["max_queue"] < 1 or
+ type(work.get("queue_timeout_s")) not in (int, float) or
+ work["queue_timeout_s"] < 2):
+ raise ProfileError("cancellation benchmark needs a queue, two-second timeout and all slots", 5)
+ if suite == "parallel-prefill-cancel-v1" and (slots < 2 or count < 2):
+ raise ProfileError("prefill cancellation needs at least two slots and clients", 5)
+ requests = {"serving-smoke": 1 + repeat * (2 + count),
+ "parallel-mixed-v1": 1 + repeat * (2 + 2 * count),
+ "parallel-overload-v1": 2 + repeat * count,
+ "parallel-cancel-v1": (work.get("slots_effective") or 0) + 4,
+ "parallel-prefill-cancel-v1": 4}[suite]
+ return {"profile": profile, "profile_revision": identity["revision"],
+ "source_sha256": identity["source_sha256"], "owner_id": owner_id,
+ "instance_id": match["instance_id"], "endpoint": endpoint.root,
+ "model_id": (snapshot.get("model") or {}).get("id"),
+ "suite": suite, "concurrency": count, "repeat": repeat,
+ "request_timeout": params["request_timeout"], "condition": params["condition"],
+ "path": str(path), "phases": list(bench.SUITES[suite]),
+ "planned_requests": requests, "managed_match": True,
+ "api_credential_env": "STRATA_API_KEY", "telemetry_credential_env": "STRATA_TELEMETRY_KEY"}
+
+
+def create_job(profile: str, params: dict) -> dict:
+ """Save a bounded receipt before the Desktop launches its benchmark worker."""
+ job_id = params["job_id"]
+ intent = {key: value for key, value in params.items() if key != "job_id"}
+ _settings(profile, intent)
+ if benchmark_activity(profile, Path(intent["path"])) in ("active", "other_active"):
+ raise ProfileError("another benchmark is running for this saved profile", 6)
+ record = journal.begin_direct(profile, "bench.run", intent["if_profile_revision"], intent,
+ operation_id=job_id)
+ return {"ok": True, "job_id": record["operation_id"],
+ "path": str(Path(intent["path"]) / "results.json")}
+
+
+def _job_record(profile: str, job_id: str) -> dict:
+ if not isinstance(job_id, str) or not journal.ID.fullmatch(job_id):
+ raise ProfileError("benchmark job ID must be a 32-character hex value", 2)
+ record = journal.load(profile, job_id)
+ if record.get("kind") != "bench.run" or record.get("origin") != "direct":
+ raise ProfileError("benchmark job ID does not identify a benchmark", 5)
+ return record
+
+
+def _receipt_result(path: Path, report: dict) -> dict:
+ return {"ok": True, "report_path": str(path / "results.json"),
+ "run_id": report["run_id"], "instance_id": report["instance_id"],
+ "successful": report["successful"], "cancelled": report.get("cancelled", False)}
+
+
+def _report_matches_job(report: dict, intent: dict, profile: str) -> bool:
+ identity = report.get("profile_identity") or {}
+ return (isinstance(identity, dict) and
+ report.get("suite") == intent["suite"] and
+ report.get("condition") == intent["condition"] and
+ report.get("instance_id") == intent["if_instance_id"] and
+ report.get("planned_phases") == bench._planned_phase_kinds(intent["suite"], intent["repeat"]) and
+ identity.get("profile") == profile and
+ identity.get("revision") == intent["if_profile_revision"] and
+ identity.get("source_sha256") == intent["if_source_sha256"])
+
+
+def job_status(profile: str, job_id: str) -> dict:
+ """Recover a Desktop job from its journal, exact lease and private report."""
+ record = _job_record(profile, job_id)
+ directory = Path(record["intent"]["path"])
+ path = directory / "results.json"
+ if directory.exists() or directory.is_symlink():
+ details = directory.lstat()
+ if not stat.S_ISDIR(details.st_mode) or (os.name == "posix" and
+ (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)):
+ raise ProfileError("benchmark output directory must be owner-only", 5)
+ activity = benchmark_activity(profile, directory)
+ try:
+ phase = bench.progress(directory)
+ except ProfileError:
+ phase = None
+ report = None
+ if phase is not None and phase["state"] in ("report_saved", "cancelled"):
+ candidate = bench.load(directory)
+ if _report_matches_job(candidate, record["intent"], profile):
+ report = candidate
+ else:
+ phase = None
+ if report is not None and record["state"] == "running":
+ try:
+ journal.finish(profile, job_id, "succeeded", _receipt_result(directory, report))
+ except ProfileError:
+ pass # The benchmark worker may have finished the same receipt.
+ record = _job_record(profile, job_id)
+ if report is not None:
+ state = "cancelled" if report.get("cancelled") else "completed"
+ result = {"ok": True, "path": str(path), "successful": report["successful"],
+ "cancelled": report.get("cancelled", False), "run_id": report["run_id"],
+ "instance_id": report["instance_id"], "suite": report["suite"]}
+ elif record["state"] == "succeeded" and isinstance(record.get("result"), dict):
+ saved = record["result"]
+ state = "cancelled" if saved.get("cancelled") else "completed"
+ result = {"ok": True, "path": str(path), "successful": saved.get("successful"),
+ "cancelled": saved.get("cancelled"), "run_id": saved.get("run_id"),
+ "instance_id": saved.get("instance_id"), "suite": record["intent"]["suite"]}
+ else:
+ result = None
+ state = ("failed" if record["state"] == "failed" else
+ "running" if activity == "active" else "completion_unknown")
+ if (state == "completion_unknown" and record["state"] == "running" and phase is None and
+ time.time() - record["started_at"] < 10):
+ state = "launching"
+ return {"ok": True, "job": {"job_id": job_id, "state": state,
+ "started_at": round(record["started_at"] * 1000),
+ "finished_at": round(record["finished_at"] * 1000) if record["finished_at"] is not None else None,
+ "path": str(path), "result": result,
+ "error": ("Benchmark failed before a complete report was saved." if state == "failed" else
+ "Benchmark completion needs inspection at the saved path."
+ if state == "completion_unknown" else None),
+ "outcome": "report_recovered" if report is not None and record["state"] != "succeeded"
+ else "owner_journal", "progress": phase,
+ "activity": activity, "cancel_requested": cancel_requested(directory) if directory.exists() else False}}
+
+
+def run(profile: str, params: dict) -> dict:
+ job_id = params.get("job_id")
+ if job_id is not None:
+ record = _job_record(profile, job_id)
+ if record["state"] != "running" or record["intent"] != {key: value for key, value in params.items()
+ if key != "job_id"}:
+ raise ProfileError("benchmark job no longer matches its reviewed request", 6)
+ try:
+ with benchmark_lease(profile, Path(params["path"])):
+ planned = plan(profile, params)
+ for key in ("profile_revision", "source_sha256", "owner_id", "instance_id"):
+ if planned[key] != params["if_" + key]:
+ raise ProfileError("benchmark target changed after review; review again", 6)
+ _, identity, endpoint, telemetry, path = _settings(profile, params)
+ try:
+ report = bench.run(endpoint, telemetry, path, suite=params["suite"],
+ concurrency=params["concurrency"], repeat=params["repeat"],
+ request_timeout=params["request_timeout"], condition=params["condition"],
+ profile_identity=identity, require_managed_match=True)
+ except ClientError as exc:
+ raise ProfileError("benchmark connection failed: " + str(exc), exc.exit_code) from None
+ if job_id is not None:
+ saved_result = _receipt_result(path, report)
+ try:
+ journal.finish(profile, job_id, "succeeded", saved_result)
+ except ProfileError:
+ # A concurrent recovery read may have reconciled this final report.
+ recorded = _job_record(profile, job_id)
+ if recorded["state"] != "succeeded" or recorded["result"] != saved_result:
+ raise
+ return {"ok": True, "path": str(path / "results.json"),
+ "successful": report["successful"], "summary": bench.summary(report)}
+ except BaseException as exc:
+ if job_id is not None and _job_record(profile, job_id)["state"] == "running":
+ unknown = isinstance(exc, (KeyboardInterrupt, SystemExit)) or \
+ (isinstance(exc, ProfileError) and exc.exit_code == 8)
+ journal.finish(profile, job_id, "completion_unknown" if unknown else "failed",
+ {"error_type": type(exc).__name__,
+ "exit_code": exc.exit_code if isinstance(exc, ProfileError) else 130 if unknown else 6})
+ raise
diff --git a/strata_control/calibration.py b/strata_control/calibration.py
new file mode 100644
index 000000000..8ab08f3ec
--- /dev/null
+++ b/strata_control/calibration.py
@@ -0,0 +1,704 @@
+"""Explicit measure, review and apply steps around Strata's existing calibration.
+
+The current suite measures decode speed. It is not a four-GPU serving benchmark.
+Its report binds a candidate to the run config, engine binary and observed local
+hardware; applying it is a separate operation with a backup and smoke generation.
+"""
+
+from __future__ import annotations
+
+import copy
+import hashlib
+import json
+import math
+import os
+import re
+import socket
+import stat
+import tempfile
+import threading
+import time
+import uuid
+from contextlib import contextmanager
+from pathlib import Path
+
+from strata_control import profiles
+from strata_control.doctor import inspect as inspect_components
+from strata_control.profiles import ProfileError
+
+
+SUITE = "legacy-decode-v1"
+MAX_REPORT_BYTES = 2 * 1024 * 1024
+MAX_APPLICATION_BYTES = 8 * 1024
+MAX_AGE_SECONDS = 30 * 24 * 3600
+ALLOWED_SETTINGS = {"--pcie-frac", "--spec-min-p", "--pool-workers",
+ "--adapt-every", "--adapt-swaps", "--adapt-decay"}
+
+
+def _digest(path: Path) -> str:
+ result = hashlib.sha256()
+ with path.open("rb") as stream:
+ for block in iter(lambda: stream.read(1024 * 1024), b""):
+ result.update(block)
+ return result.hexdigest()
+
+
+def _target(ref: str) -> tuple[Path, dict | None, str | None, dict]:
+ path, profile, revision = profiles.resolve(ref)
+ return path, profile, revision, profiles.read_run_config(path)
+
+
+def preview(ref: str) -> dict:
+ """Inspect a proposed decode sweep without starting the engine or writing files."""
+ path, profile, revision, cfg = _target(ref)
+ components = inspect_components(path, profile_id=profile["id"] if profile else None)
+ source_bytes = path.read_bytes()
+ if json.loads(source_bytes.decode("utf-8-sig")) != cfg:
+ raise ProfileError("run config changed during calibration preview; retry", 6)
+ return {"profile": profile["id"] if profile else None, "profile_revision": revision,
+ "source_config": str(path), "source_sha256": hashlib.sha256(source_bytes).hexdigest(),
+ "model_name": cfg.get("model_name"), "backend": cfg.get("backend") or "unverified",
+ "devices_selected": cfg.get("gpu"), "tool": "tools/calibrate.py",
+ "estimated_minutes": [15, 30], "requires_exclusive_engine": True,
+ "settings_measured": ["--pcie-frac", "--spec-min-p", "--pool-workers",
+ "--adapt-every", "--adapt-swaps", "--adapt-decay"],
+ "component_preflight": components, "hardware_identity": "unverified_until_measurement",
+ "would_start_engine": False, "would_write_config": False}
+
+
+def _resolved(raw: str, cfg: dict, path: Path) -> Path:
+ value = Path(raw).expanduser()
+ if value.is_absolute():
+ return value
+ cwd = cfg.get("cwd")
+ return (Path(cwd) if isinstance(cwd, str) and cwd else path.parent) / value
+
+
+def _runtime_cfg(cfg: dict, profile: dict | None) -> dict:
+ """Apply the saved engine concurrency settings without changing setup's config."""
+ effective = copy.deepcopy(cfg)
+ if profile is None:
+ return effective
+ overrides = profile["overrides"]
+ if "parallel" in overrides:
+ if any(flag in effective["args"] for flag in ("--batch", "--slots")):
+ raise ProfileError("parallel profile override conflicts with engine args")
+ effective["parallel"] = overrides["parallel"]
+ if "batch_groups" in overrides:
+ if "--batch-groups" in effective["args"]:
+ raise ProfileError("batch_groups profile override conflicts with engine args")
+ effective["args"] += ["--batch-groups", str(overrides["batch_groups"])]
+ return effective
+
+
+def _hardware_key(cfg: dict) -> str:
+ import setup
+ return setup.hardware_key(cfg)
+
+
+def _identity(path: Path, cfg: dict, profile: dict | None, revision: str | None) -> dict:
+ import tools.calibrate as cal
+ engine = _resolved(cfg["exe"], cfg, path)
+ components = inspect_components(path, profile_id=profile["id"] if profile else None)
+ if not components["ok"]:
+ raise ProfileError("required engine/model components are missing; run strata doctor --profile first", 5)
+ files = []
+ for item in components["components"]:
+ if item.get("required") and item.get("kind") == "file" and item.get("name") != "engine":
+ file_path = Path(item["path"])
+ try:
+ details = file_path.stat()
+ except OSError:
+ raise ProfileError(f"component changed during calibration: {item['name']}", 5) from None
+ files.append({"name": item["name"], "path": str(file_path),
+ "size": details.st_size, "modified_ns": details.st_mtime_ns})
+ return {"source_sha256": _digest(path), "engine_sha256": _digest(engine),
+ "suite_sha256": _digest(Path(cal.__file__)), "hardware_key": _hardware_key(cfg),
+ "model_name": cfg.get("model_name"), "backend": cfg.get("backend"), "gpu": cfg.get("gpu"),
+ "profile_id": profile["id"] if profile else None, "profile_revision": revision,
+ "required_file_metadata": files, "model_integrity": "metadata_only_unverified"}
+
+
+def _validate_settings(settings: object) -> dict[str, str]:
+ if not isinstance(settings, dict) or set(settings) - ALLOWED_SETTINGS:
+ raise ProfileError("calibration report has unsupported settings", 5)
+ out = {}
+ for flag, raw in settings.items():
+ if not isinstance(raw, str) or len(raw) > 32:
+ raise ProfileError(f"calibration setting {flag} must be a short string", 5)
+ try:
+ number = float(raw)
+ except ValueError:
+ raise ProfileError(f"calibration setting {flag} must be numeric", 5) from None
+ if not number == number or number in (float("inf"), float("-inf")):
+ raise ProfileError(f"calibration setting {flag} must be finite", 5)
+ if flag in ("--pcie-frac", "--spec-min-p", "--adapt-decay"):
+ if not 0 <= number <= 1:
+ raise ProfileError(f"calibration setting {flag} must be in 0..1", 5)
+ else:
+ if not raw.isdecimal() or not 1 <= int(raw) <= 8192:
+ raise ProfileError(f"calibration setting {flag} must be a positive whole number", 5)
+ out[flag] = raw
+ return out
+
+
+def _port_active(cfg: dict) -> bool:
+ port = cfg.get("port", 8095)
+ if type(port) is not int or not 1 <= port <= 65535:
+ return False
+ host = cfg.get("host") or "127.0.0.1"
+ address = "127.0.0.1" if host in ("0.0.0.0", "::", "localhost") else host
+ try:
+ with socket.create_connection((address, port), timeout=0.2):
+ return True
+ except OSError:
+ return False
+
+
+def _exclusive_preflight(cfg: dict, profile: dict | None = None) -> None:
+ endpoints = [cfg]
+ overrides = profile["overrides"] if profile else {}
+ if "host" in overrides or "port" in overrides:
+ endpoints.append({**cfg, **{key: overrides[key] for key in ("host", "port") if key in overrides}})
+ if any(_port_active(endpoint) for endpoint in endpoints):
+ raise ProfileError("a server is listening on this profile's port; stop it before calibration", 6)
+
+
+@contextmanager
+def _managed_exclusive():
+ """Keep new owner hosts out for the full calibration engine action."""
+ if os.name != "posix":
+ yield
+ return
+ from strata_control import runtime
+ lease = runtime.acquire_activity_lease(shared=False)
+ try:
+ active = runtime.active_managed_instances()
+ if active:
+ raise ProfileError("stop managed Strata runtime instances before calibration: " +
+ ", ".join(item["profile"] for item in active), 6)
+ yield
+ finally:
+ os.close(lease)
+
+
+def _write_new(path: Path, payload: bytes) -> None:
+ if not path.parent.is_dir():
+ raise ProfileError("report output directory does not exist", 5)
+ descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ try:
+ with os.fdopen(descriptor, "wb") as stream:
+ stream.write(payload)
+ stream.flush()
+ os.fsync(stream.fileno())
+ except BaseException:
+ path.unlink(missing_ok=True)
+ raise
+
+
+def _report_bytes(report: dict) -> bytes:
+ try:
+ payload = (json.dumps(report, ensure_ascii=False, sort_keys=True, indent=2, allow_nan=False) + "\n").encode("utf-8")
+ except (TypeError, ValueError):
+ raise ProfileError("calibration returned an invalid report", 6) from None
+ if len(payload) > MAX_REPORT_BYTES:
+ raise ProfileError("calibration report exceeds 2 MiB", 6)
+ return payload
+
+
+def _body_sha256(report: dict) -> str:
+ body = {key: value for key, value in report.items() if key != "body_sha256"}
+ try:
+ encoded = json.dumps(body, ensure_ascii=False, sort_keys=True, separators=(",", ":"),
+ allow_nan=False).encode("utf-8")
+ except (TypeError, ValueError):
+ raise ProfileError("calibration report has invalid values", 5) from None
+ return hashlib.sha256(encoded).hexdigest()
+
+
+def _lock_name(path: Path) -> str:
+ return "cal" + hashlib.sha256(str(path.resolve()).encode("utf-8")).hexdigest()[:24]
+
+
+def measure(ref: str, output: Path, *, exclusive_ack: bool = False, say=print, runner=None,
+ expected_profile_revision: str | None = None,
+ expected_source_sha256: str | None = None, job_id: str | None = None,
+ progress=None, cancel_event=None) -> dict:
+ """Run the existing decode sweep, leaving the run config unchanged."""
+ if not exclusive_ack:
+ raise ProfileError("calibration measure requires an exclusive-access acknowledgement")
+ path, profile, revision, cfg = _target(ref)
+ with profiles._lock(_lock_name(path)), _managed_exclusive():
+ current_path, profile, revision, cfg = _target(ref)
+ if current_path != path or (expected_profile_revision is not None and
+ revision != expected_profile_revision) or \
+ (expected_source_sha256 is not None and
+ _digest(current_path) != expected_source_sha256):
+ raise ProfileError("calibration source changed after review; review again", 6)
+ return _measure_locked(ref, path, profile, revision, cfg, output, say=say, runner=runner,
+ job_id=job_id, progress=progress, cancel_event=cancel_event)
+
+
+def _measure_locked(ref: str, path: Path, profile: dict | None, revision: str | None, cfg: dict,
+ output: Path, *, say, runner, job_id: str | None = None,
+ progress=None, cancel_event=None) -> dict:
+ _exclusive_preflight(cfg, profile)
+ if output.exists() or output.is_symlink():
+ raise ProfileError("calibration report path already exists", 2)
+ identity = _identity(path, cfg, profile, revision)
+ from tools import calibrate as cal
+ execute = runner or cal.run
+ runner_cfg = _runtime_cfg(cfg, profile)
+ runner_cfg["exe"] = str(_resolved(cfg["exe"], cfg, path))
+ runner_cfg["tokenizer"] = str(_resolved(cfg["tokenizer"], cfg, path))
+ try:
+ if cancel_event is not None and cancel_event.is_set():
+ raise cal.CalibrationCancelled("calibration cancelled")
+ result = (execute(runner_cfg, say=say) if progress is None and cancel_event is None else
+ execute(runner_cfg, say=say, progress=progress, cancel_event=cancel_event))
+ except cal.CalibrationCancelled:
+ raise ProfileError("calibration cancelled by operator; config unchanged", 130) from None
+ except (KeyboardInterrupt, SystemExit):
+ raise
+ except Exception as exc:
+ raise ProfileError(f"calibration measurement failed ({type(exc).__name__}); config unchanged", 6) from None
+ if not isinstance(result, dict) or not isinstance(result.get("report"), dict):
+ raise ProfileError("calibration returned no measurement report", 6)
+ settings = _validate_settings(result.get("settings"))
+ try:
+ end_path, end_profile, end_revision, end_cfg = _target(ref)
+ unchanged = path == end_path and identity == _identity(end_path, end_cfg, end_profile, end_revision)
+ except ProfileError:
+ unchanged = False
+ report = {"schema_version": 1, "kind": "strata.engine.calibration", "suite": SUITE,
+ "report_id": uuid.uuid4().hex, "created_at": time.time(), "source_config": str(path),
+ "identity": identity, "applicable": unchanged, "settings": settings,
+ "measurements": result["report"]}
+ if job_id is not None:
+ if not re.fullmatch(r"[0-9a-f]{32}", job_id):
+ raise ProfileError("calibration job ID is invalid", 5)
+ report["operation_id"] = job_id
+ report["body_sha256"] = _body_sha256(report)
+ if progress is not None:
+ progress("saving_report", 0, 1)
+ _write_new(output, _report_bytes(report))
+ if progress is not None:
+ progress("saving_report", 1, 1)
+ return report
+
+
+def load_report(path: Path) -> dict:
+ try:
+ if not stat.S_ISREG(path.lstat().st_mode) or path.stat().st_size > MAX_REPORT_BYTES:
+ raise ProfileError("calibration report must be a regular file under 2 MiB", 5)
+ report = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, UnicodeError, ValueError) as exc:
+ if isinstance(exc, ProfileError):
+ raise
+ raise ProfileError(f"cannot read calibration report ({type(exc).__name__})", 5) from None
+ if not isinstance(report, dict) or type(report.get("schema_version")) is not int or \
+ report["schema_version"] != 1 or \
+ report.get("kind") != "strata.engine.calibration" or report.get("suite") != SUITE or \
+ not isinstance(report.get("identity"), dict) or not isinstance(report.get("measurements"), dict) or \
+ not isinstance(report.get("source_config"), str) or \
+ type(report.get("created_at")) not in (int, float) or \
+ not math.isfinite(report["created_at"]) or \
+ not re.fullmatch(r"[0-9a-f]{32}", str(report.get("report_id", ""))):
+ raise ProfileError("unsupported calibration report", 5)
+ _validate_settings(report.get("settings"))
+ if report.get("body_sha256") != _body_sha256(report):
+ raise ProfileError("calibration report contents changed after measurement", 5)
+ return report
+
+
+def review(ref: str, report_path: Path) -> dict:
+ path, profile, revision, cfg = _target(ref)
+ report = load_report(report_path)
+ from tools import calibrate as cal
+ reasons = []
+ if report["source_config"] != str(path):
+ reasons.append("source_config_mismatch")
+ if report.get("applicable") is not True:
+ reasons.append("measurement_became_stale")
+ age = time.time() - report["created_at"]
+ if age < -300 or age > MAX_AGE_SECONDS:
+ reasons.append("report_expired")
+ try:
+ now = _identity(path, cfg, profile, revision)
+ if now != report["identity"]:
+ reasons.append("source_engine_model_or_hardware_changed")
+ except ProfileError as exc:
+ reasons.append(f"identity_unavailable:{exc.exit_code}")
+ after = cal.apply(cfg["args"], report["settings"])
+ return {"schema_version": 1, "report_id": report.get("report_id"), "profile": profile["id"] if profile else None,
+ "source_config": str(path), "applicable": not reasons, "reasons": reasons,
+ "settings": report["settings"], "before_args": cfg["args"], "after_args": after,
+ "measurements": report["measurements"], "model_integrity": "metadata_only_unverified"}
+
+
+def _smoke(cfg: dict, source_path: Path) -> int:
+ """Start the candidate and require at least one generated token before writing it."""
+ import strata_tokenizer as st
+ from serve.server import StrataEngine, child_env, engine_args
+ from tools import calibrate as cal
+ tokdir = _resolved(cfg["tokenizer"], cfg, source_path)
+ vocab = json.loads((tokdir / "vocab.json").read_text(encoding="utf-8"))
+ tokens = [None] * len(vocab)
+ for token, index in vocab.items():
+ tokens[index] = token
+ tok = st.Tokenizer(tokens, (tokdir / "merges.txt").read_text(encoding="utf-8").split("\n"),
+ json.loads((tokdir / "token_type.json").read_text(encoding="utf-8")))
+ engine = StrataEngine(str(_resolved(cfg["exe"], cfg, source_path)), engine_args(cfg),
+ cwd=cfg.get("cwd"), log=cfg.get("log"), env=child_env(cfg))
+ try:
+ ids = cal.chat_ids(tok, "Say OK.")
+ count = sum(token is not None for token in engine.generate(ids, 16, {"temperature": 0}, threading.Event()))
+ if count < 1:
+ raise ProfileError("candidate engine produced no tokens in smoke generation", 6)
+ return count
+ finally:
+ cal.close(engine)
+
+
+def _replace_bytes(path: Path, payload: bytes) -> None:
+ descriptor, temp = tempfile.mkstemp(prefix=f".{path.name}-", suffix=".tmp", dir=path.parent)
+ try:
+ with os.fdopen(descriptor, "wb") as stream:
+ stream.write(payload)
+ stream.flush()
+ os.fsync(stream.fileno())
+ os.replace(temp, path)
+ finally:
+ if os.path.exists(temp):
+ os.unlink(temp)
+
+
+def _settings_candidate(hardware_key: str, result: dict) -> tuple[Path, bytes | None, bytes]:
+ """Prepare setup's remembered calibration without accepting a corrupt store."""
+ import setup
+ target = setup.settings_path()
+ try:
+ previous = target.read_bytes()
+ settings = json.loads(previous.decode("utf-8"))
+ if not isinstance(settings, dict):
+ raise ValueError
+ except FileNotFoundError:
+ previous, settings = None, {}
+ except (OSError, UnicodeError, ValueError):
+ raise ProfileError("setup settings could not be read safely; config unchanged", 5) from None
+ if previous is not None and len(previous) > MAX_REPORT_BYTES:
+ raise ProfileError("setup settings exceed the calibration rollback size limit; config unchanged", 5)
+ cal = settings.get("calibration")
+ if cal is None:
+ cal = {}
+ settings["calibration"] = cal
+ if not isinstance(cal, dict):
+ raise ProfileError("setup calibration store is invalid; config unchanged", 5)
+ cal[hardware_key] = {"settings": result["settings"], "tok_s": result["measurements"].get("tok_s"),
+ "date": time.strftime("%Y-%m-%d")}
+ try:
+ proposed = (json.dumps(settings, indent=1, ensure_ascii=False, allow_nan=False) + "\n").encode("utf-8")
+ except (TypeError, ValueError):
+ raise ProfileError("setup settings cannot be serialized; config unchanged", 5) from None
+ if len(proposed) > MAX_REPORT_BYTES:
+ raise ProfileError("updated setup settings exceed the calibration rollback size limit; config unchanged", 5)
+ return target, previous, proposed
+
+
+def _backup_directory(path: Path, *, create: bool = False) -> Path:
+ directory = path.parent / ".strata-calibration-backups"
+ try:
+ if create:
+ directory.mkdir(mode=0o700, exist_ok=True)
+ details = directory.lstat()
+ except FileNotFoundError:
+ raise ProfileError("calibration backup directory is missing", 5) from None
+ except OSError as exc:
+ raise ProfileError(f"cannot access calibration backup directory ({type(exc).__name__})", 5) from None
+ if not stat.S_ISDIR(details.st_mode) or (os.name == "posix" and
+ (details.st_uid != os.getuid() or
+ stat.S_IMODE(details.st_mode) & 0o077)):
+ raise ProfileError("calibration backup directory must be owner-only and not a symlink", 5)
+ return directory
+
+
+def _application_paths(path: Path, report_id: str, *, create: bool = False) -> tuple[Path, Path, Path]:
+ directory = _backup_directory(path, create=create)
+ return (directory / f"{path.stem}-{report_id}.json",
+ directory / f"settings-{report_id}.json",
+ directory / f"{path.stem}-{report_id}.apply.json")
+
+
+def _sha256(payload: bytes | None) -> str | None:
+ return hashlib.sha256(payload).hexdigest() if payload is not None else None
+
+
+def _load_application(path: Path, report: dict) -> dict:
+ backup, settings_backup, manifest = _application_paths(path, report["report_id"])
+ try:
+ details = manifest.lstat()
+ if not stat.S_ISREG(details.st_mode) or details.st_size > MAX_APPLICATION_BYTES or \
+ (os.name == "posix" and (details.st_uid != os.getuid() or
+ stat.S_IMODE(details.st_mode) & 0o077)):
+ raise ProfileError("calibration application record is not an owner-only regular file", 5)
+ data = json.loads(manifest.read_text(encoding="utf-8"))
+ except FileNotFoundError:
+ raise ProfileError("calibration application record was not found", 5) from None
+ except (OSError, ValueError, UnicodeError) as exc:
+ if isinstance(exc, ProfileError):
+ raise
+ raise ProfileError(f"cannot read calibration application record ({type(exc).__name__})", 5) from None
+ expected_keys = {"schema_version", "kind", "report_id", "report_body_sha256", "source_config",
+ "profile_revision", "before_config_sha256", "after_config_sha256",
+ "settings_path", "before_settings_sha256", "after_settings_sha256"}
+ if not isinstance(data, dict) or set(data) != expected_keys or \
+ type(data.get("schema_version")) is not int or data["schema_version"] != 1 or \
+ data.get("kind") != "strata.engine.calibration.application" or \
+ data.get("report_id") != report["report_id"] or \
+ data.get("report_body_sha256") != report["body_sha256"] or \
+ data.get("source_config") != str(path) or \
+ data.get("profile_revision") != report["identity"].get("profile_revision") or \
+ not isinstance(data.get("settings_path"), str) or \
+ not Path(data["settings_path"]).is_absolute() or \
+ not (data.get("before_settings_sha256") is None or
+ isinstance(data["before_settings_sha256"], str) and
+ re.fullmatch(r"[0-9a-f]{64}", data["before_settings_sha256"])) or \
+ not isinstance(data.get("after_settings_sha256"), str) or \
+ not re.fullmatch(r"[0-9a-f]{64}", data["after_settings_sha256"]) or \
+ not all(isinstance(data.get(key), str) and re.fullmatch(r"[0-9a-f]{64}", data[key])
+ for key in ("before_config_sha256", "after_config_sha256")) or \
+ data["before_config_sha256"] != report["identity"].get("source_sha256"):
+ raise ProfileError("calibration application record has an unsupported shape", 5)
+ try:
+ import setup
+ if data["settings_path"] != str(setup.settings_path()):
+ raise ProfileError("setup settings path changed since calibration apply", 5)
+ except (OSError, ValueError):
+ raise ProfileError("setup settings path is unavailable", 5) from None
+ return {**data, "backup": backup, "settings_backup": settings_backup, "manifest": manifest}
+
+
+def apply_result(ref: str, report_path: Path, *, exclusive_ack: bool = False, smoke=None,
+ expected_report_sha256: str | None = None) -> dict:
+ """Apply a reviewed result after a candidate smoke test; retain prior config."""
+ if not exclusive_ack:
+ raise ProfileError("calibration apply requires an exclusive-access acknowledgement")
+ path, profile, revision, cfg = _target(ref)
+ with profiles._lock(_lock_name(path)), _managed_exclusive():
+ return _apply_locked(ref, path, profile, revision, cfg, report_path, smoke=smoke,
+ expected_report_sha256=expected_report_sha256)
+
+
+def _apply_locked(ref: str, path: Path, profile: dict | None, revision: str | None, cfg: dict,
+ report_path: Path, *, smoke, expected_report_sha256: str | None) -> dict:
+ _exclusive_preflight(cfg, profile)
+ if expected_report_sha256 is not None and \
+ load_report(report_path)["body_sha256"] != expected_report_sha256:
+ raise ProfileError("calibration report changed after review; review again", 6)
+ preview = review(ref, report_path)
+ if not preview["applicable"]:
+ raise ProfileError("calibration report is stale: " + ", ".join(preview["reasons"]), 6)
+ report = load_report(report_path)
+ if expected_report_sha256 is not None and report["body_sha256"] != expected_report_sha256:
+ raise ProfileError("calibration report changed after review; review again", 6)
+ settings_path, previous_settings, new_settings = _settings_candidate(report["identity"]["hardware_key"], report)
+ source = path.read_bytes()
+ if hashlib.sha256(source).hexdigest() != report["identity"]["source_sha256"]:
+ raise ProfileError("run config changed before calibration apply", 6)
+ candidate = copy.deepcopy(cfg)
+ candidate["args"] = preview["after_args"]
+ smoke_candidate = _runtime_cfg(candidate, profile)
+ candidate_bytes = (json.dumps(candidate, indent=1, ensure_ascii=False) + "\n").encode("utf-8")
+ if len(source) > MAX_REPORT_BYTES or len(candidate_bytes) > MAX_REPORT_BYTES:
+ raise ProfileError("run config exceeds the calibration rollback size limit; config unchanged", 5)
+ try:
+ token_count = smoke(smoke_candidate) if smoke else _smoke(smoke_candidate, path)
+ except ProfileError:
+ raise
+ except Exception as exc:
+ raise ProfileError(f"candidate smoke generation failed ({type(exc).__name__}); config unchanged", 6) from None
+ if type(token_count) is not int or token_count < 1:
+ raise ProfileError("candidate smoke generation produced no tokens; config unchanged", 6)
+ if path.read_bytes() != source:
+ raise ProfileError("run config changed during smoke generation; config unchanged", 6)
+ end_path, end_profile, end_revision, end_cfg = _target(ref)
+ if end_path != path or _identity(end_path, end_cfg, end_profile, end_revision) != report["identity"]:
+ raise ProfileError("engine, model or hardware changed during smoke generation; config unchanged", 6)
+ settings_path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
+ current_settings = settings_path.read_bytes() if settings_path.exists() else None
+ if current_settings != previous_settings:
+ raise ProfileError("setup settings changed during calibration; config unchanged", 6)
+ backup, settings_backup_path, manifest = _application_paths(path, report["report_id"], create=True)
+ if any(item.exists() or item.is_symlink() for item in (backup, settings_backup_path, manifest)):
+ raise ProfileError("calibration result already has application records; measure again", 6)
+ application = {"schema_version": 1, "kind": "strata.engine.calibration.application",
+ "report_id": report["report_id"], "report_body_sha256": report["body_sha256"],
+ "source_config": str(path), "profile_revision": revision,
+ "before_config_sha256": _sha256(source), "after_config_sha256": _sha256(candidate_bytes),
+ "settings_path": str(settings_path),
+ "before_settings_sha256": _sha256(previous_settings),
+ "after_settings_sha256": _sha256(new_settings)}
+ settings_backup = settings_backup_path if previous_settings is not None else None
+ written = []
+ try:
+ _write_new(backup, source)
+ written.append(backup)
+ if settings_backup is not None:
+ _write_new(settings_backup, previous_settings)
+ written.append(settings_backup)
+ _write_new(manifest, _report_bytes(application))
+ written.append(manifest)
+ except (OSError, ProfileError) as exc:
+ for item in written:
+ item.unlink(missing_ok=True)
+ raise ProfileError(f"cannot save calibration rollback evidence ({type(exc).__name__}); config unchanged", 6) from None
+ try:
+ if candidate_bytes != source:
+ _replace_bytes(path, candidate_bytes)
+ _replace_bytes(settings_path, new_settings)
+ except Exception as exc:
+ # Restore both stores if either write failed; backups remain for manual recovery.
+ failed = False
+ try:
+ _replace_bytes(path, source)
+ except OSError:
+ failed = True
+ try:
+ if previous_settings is None:
+ settings_path.unlink(missing_ok=True)
+ else:
+ _replace_bytes(settings_path, previous_settings)
+ except OSError:
+ failed = True
+ if failed:
+ raise ProfileError(f"calibration apply failed ({type(exc).__name__}); restore from {backup}", 6) from None
+ raise ProfileError(f"calibration apply failed ({type(exc).__name__}); config restored", 6) from None
+ return {"changed": candidate_bytes != source, "report_id": report.get("report_id"), "source_config": str(path),
+ "backup": str(backup), "settings_backup": str(settings_backup) if settings_backup else None,
+ "application_record": str(manifest),
+ "previous_sha256": hashlib.sha256(source).hexdigest(),
+ "current_sha256": hashlib.sha256(candidate_bytes).hexdigest(), "smoke_output_tokens": token_count,
+ "setup_settings_persisted": True}
+
+
+def _saved_bytes(path: Path, *, required: bool = True, owner_only: bool = False) -> bytes | None:
+ try:
+ details = path.lstat()
+ except FileNotFoundError:
+ if not required:
+ return None
+ raise ProfileError("calibration rollback file is missing", 5) from None
+ if not stat.S_ISREG(details.st_mode) or details.st_size > MAX_REPORT_BYTES or \
+ (owner_only and os.name == "posix" and
+ (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)):
+ raise ProfileError("calibration rollback file must be a regular owner-only file under 2 MiB", 5)
+ try:
+ return path.read_bytes()
+ except OSError as exc:
+ raise ProfileError(f"cannot read calibration rollback file ({type(exc).__name__})", 5) from None
+
+
+def review_rollback(ref: str, report_path: Path) -> dict:
+ """Preview an exact rollback without touching engine or settings."""
+ path, profile, revision, cfg = _target(ref)
+ report = load_report(report_path)
+ application = _load_application(path, report)
+ reasons: list[str] = []
+ if report["source_config"] != str(path):
+ reasons.append("source_config_mismatch")
+ before_config = _saved_bytes(application["backup"], owner_only=True)
+ if _sha256(before_config) != application["before_config_sha256"]:
+ reasons.append("config_backup_changed")
+ settings_backup = _saved_bytes(application["settings_backup"], required=False, owner_only=True)
+ if _sha256(settings_backup) != application["before_settings_sha256"]:
+ reasons.append("settings_backup_changed")
+ current_config = _saved_bytes(path)
+ if _sha256(current_config) != application["after_config_sha256"]:
+ reasons.append("run_config_changed_after_apply")
+ current_settings = _saved_bytes(Path(application["settings_path"]), required=False)
+ if _sha256(current_settings) != application["after_settings_sha256"]:
+ reasons.append("setup_settings_changed_after_apply")
+ try:
+ identity = _identity(path, cfg, profile, revision)
+ expected = {**report["identity"], "source_sha256": application["after_config_sha256"]}
+ if identity != expected:
+ reasons.append("engine_model_hardware_or_profile_changed")
+ except ProfileError as exc:
+ reasons.append(f"identity_unavailable:{exc.exit_code}")
+ if _port_active(cfg):
+ reasons.append("profile_port_is_active")
+ return {"schema_version": 1, "report_id": report["report_id"],
+ "profile": profile["id"] if profile else None, "source_config": str(path),
+ "applicable": not reasons, "reasons": reasons,
+ "config_would_change": application["before_config_sha256"] != application["after_config_sha256"],
+ "setup_settings_would_be_removed": application["before_settings_sha256"] is None,
+ "backup": str(application["backup"]), "application_record": str(application["manifest"]),
+ "model_integrity": "metadata_only_unverified"}
+
+
+def rollback_result(ref: str, report_path: Path, *, exclusive_ack: bool = False, smoke=None,
+ expected_report_sha256: str | None = None) -> dict:
+ """Smoke-test and restore the prior config/settings only if the applied state is still exact."""
+ if not exclusive_ack:
+ raise ProfileError("calibration rollback requires an exclusive-access acknowledgement")
+ path, profile, revision, cfg = _target(ref)
+ with profiles._lock(_lock_name(path)), _managed_exclusive():
+ _exclusive_preflight(cfg, profile)
+ if expected_report_sha256 is not None and \
+ load_report(report_path)["body_sha256"] != expected_report_sha256:
+ raise ProfileError("calibration report changed after review; review again", 6)
+ preview = review_rollback(ref, report_path)
+ if not preview["applicable"]:
+ raise ProfileError("calibration rollback is stale: " + ", ".join(preview["reasons"]), 6)
+ report = load_report(report_path)
+ if expected_report_sha256 is not None and report["body_sha256"] != expected_report_sha256:
+ raise ProfileError("calibration report changed after review; review again", 6)
+ application = _load_application(path, report)
+ before_config = _saved_bytes(application["backup"], owner_only=True)
+ before_settings = _saved_bytes(application["settings_backup"], required=False, owner_only=True)
+ current_config = _saved_bytes(path)
+ settings_path = Path(application["settings_path"])
+ current_settings = _saved_bytes(settings_path, required=False)
+ candidate = profiles.read_run_config(application["backup"])
+ smoke_candidate = _runtime_cfg(candidate, profile)
+ try:
+ token_count = smoke(smoke_candidate) if smoke else _smoke(smoke_candidate, path)
+ except ProfileError:
+ raise
+ except Exception as exc:
+ raise ProfileError(f"rollback smoke generation failed ({type(exc).__name__}); config unchanged", 6) from None
+ if type(token_count) is not int or token_count < 1:
+ raise ProfileError("rollback smoke generation produced no tokens; config unchanged", 6)
+ repeated = review_rollback(ref, report_path)
+ if not repeated["applicable"] or _saved_bytes(path) != current_config or \
+ _saved_bytes(settings_path, required=False) != current_settings:
+ raise ProfileError("config or setup settings changed during rollback smoke; config unchanged", 6)
+ try:
+ if before_config != current_config:
+ _replace_bytes(path, before_config)
+ if before_settings is None:
+ settings_path.unlink(missing_ok=True)
+ elif before_settings != current_settings:
+ _replace_bytes(settings_path, before_settings)
+ except Exception as exc:
+ failed = False
+ try:
+ _replace_bytes(path, current_config)
+ except OSError:
+ failed = True
+ try:
+ if current_settings is None:
+ settings_path.unlink(missing_ok=True)
+ else:
+ _replace_bytes(settings_path, current_settings)
+ except OSError:
+ failed = True
+ if failed:
+ raise ProfileError(f"calibration rollback failed ({type(exc).__name__}); "
+ f"manual recovery may be needed from {application['backup']}", 6) from None
+ raise ProfileError(f"calibration rollback failed ({type(exc).__name__}); applied state restored", 6) from None
+ return {"changed": before_config != current_config or before_settings != current_settings,
+ "report_id": report["report_id"], "source_config": str(path),
+ "restored_config_sha256": _sha256(before_config),
+ "setup_settings_removed": before_settings is None,
+ "smoke_output_tokens": token_count, "backup": str(application["backup"])}
diff --git a/strata_control/calibration_jobs.py b/strata_control/calibration_jobs.py
new file mode 100644
index 000000000..31153bce8
--- /dev/null
+++ b/strata_control/calibration_jobs.py
@@ -0,0 +1,399 @@
+"""Owner-local receipts for reviewed Desktop calibration operations."""
+
+from __future__ import annotations
+
+import errno
+import json
+import math
+import os
+import stat
+import threading
+import time
+from contextlib import contextmanager
+from pathlib import Path
+
+from strata_control import calibration, journal, profiles
+from strata_control.profiles import ProfileError
+
+
+KINDS = {"measure": "engine.calibrate.measure", "apply": "engine.calibrate.apply",
+ "rollback": "engine.calibrate.rollback"}
+STAGES = frozenset({"preflight", "loading", "pcie_share", "draft_floor", "confirmation",
+ "cpu_workers", "expert_tier", "saving_report"})
+
+
+def _directory(profile: str) -> Path:
+ return journal._directory(profile, create=True)
+
+
+def _lease_path(profile: str) -> Path:
+ return _directory(profile) / ".calibration-worker.lock"
+
+
+def _open_lease(profile: str, *, create: bool) -> int | None:
+ flags = os.O_RDWR | (os.O_CREAT if create else 0) | getattr(os, "O_NOFOLLOW", 0)
+ try:
+ descriptor = os.open(_lease_path(profile), flags, 0o600)
+ except FileNotFoundError:
+ return None
+ details = os.fstat(descriptor)
+ if not stat.S_ISREG(details.st_mode) or details.st_nlink != 1 or details.st_size > 32 or \
+ (os.name == "posix" and
+ (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)):
+ os.close(descriptor)
+ raise ProfileError("calibration worker lease must be owner-only", 5)
+ return descriptor
+
+
+def _try_lock(descriptor: int) -> None:
+ if os.name == "nt":
+ import msvcrt
+ os.lseek(descriptor, 0, os.SEEK_SET)
+ msvcrt.locking(descriptor, msvcrt.LK_NBLCK, 1)
+ else:
+ import fcntl
+ fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
+
+
+def _unlock(descriptor: int) -> None:
+ if os.name == "nt":
+ import msvcrt
+ os.lseek(descriptor, 0, os.SEEK_SET)
+ msvcrt.locking(descriptor, msvcrt.LK_UNLCK, 1)
+ else:
+ import fcntl
+ fcntl.flock(descriptor, fcntl.LOCK_UN)
+
+
+@contextmanager
+def _worker_lease(profile: str, job_id: str):
+ descriptor = _open_lease(profile, create=True)
+ if descriptor is None:
+ raise ProfileError("calibration worker lease directory is unavailable", 5)
+ try:
+ try:
+ _try_lock(descriptor)
+ except OSError as exc:
+ if exc.errno in (errno.EAGAIN, errno.EACCES) or getattr(exc, "winerror", None) == 33:
+ raise ProfileError("another calibration worker is running for this profile", 6) from None
+ raise
+ try:
+ os.ftruncate(descriptor, 0)
+ os.lseek(descriptor, 0, os.SEEK_SET)
+ if os.write(descriptor, job_id.encode("ascii")) != 32:
+ raise ProfileError("cannot record calibration worker identity", 5)
+ os.fsync(descriptor)
+ yield
+ finally:
+ _unlock(descriptor)
+ finally:
+ os.close(descriptor)
+
+
+def _activity(profile: str, job_id: str) -> str:
+ descriptor = _open_lease(profile, create=False)
+ if descriptor is None:
+ return "untracked"
+ try:
+ try:
+ _try_lock(descriptor)
+ except OSError as exc:
+ if exc.errno not in (errno.EAGAIN, errno.EACCES) and getattr(exc, "winerror", None) != 33:
+ raise
+ os.lseek(descriptor, 0, os.SEEK_SET)
+ marker = os.read(descriptor, 32)
+ return "active" if marker == job_id.encode("ascii") else "other_active"
+ else:
+ try:
+ os.lseek(descriptor, 0, os.SEEK_SET)
+ return "ended" if os.read(descriptor, 32) == job_id.encode("ascii") else "untracked"
+ finally:
+ _unlock(descriptor)
+ finally:
+ os.close(descriptor)
+
+
+def _cancel_path(profile: str, job_id: str) -> Path:
+ return _directory(profile) / f"{job_id}.cancel"
+
+
+def _cancel_requested(profile: str, job_id: str) -> bool:
+ path = _cancel_path(profile, job_id)
+ try:
+ details = path.lstat()
+ except FileNotFoundError:
+ return False
+ if not stat.S_ISREG(details.st_mode) or details.st_nlink != 1 or details.st_size != 1 or \
+ (os.name == "posix" and
+ (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)):
+ raise ProfileError("calibration cancellation marker is invalid", 5)
+ descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
+ try:
+ current = os.fstat(descriptor)
+ if current.st_ino != details.st_ino or os.read(descriptor, 2) != b"1":
+ raise ProfileError("calibration cancellation marker changed", 5)
+ finally:
+ os.close(descriptor)
+ return True
+
+
+@contextmanager
+def _cancel_watcher(profile: str, job_id: str):
+ requested = threading.Event()
+ stop = threading.Event()
+
+ def watch():
+ while not stop.wait(0.2):
+ try:
+ if _cancel_requested(profile, job_id):
+ requested.set()
+ return
+ except (OSError, ProfileError):
+ requested.set() # Invalid private state stops the measurement safely.
+ return
+
+ thread = threading.Thread(target=watch, name="strata-calibration-cancel", daemon=True)
+ thread.start()
+ try:
+ yield requested
+ finally:
+ stop.set()
+ thread.join(timeout=1)
+
+
+def _progress_path(profile: str, job_id: str) -> Path:
+ return _directory(profile) / f"{job_id}.progress.json"
+
+
+def _save_progress(profile: str, job_id: str, stage: str, completed: int, total: int) -> None:
+ if stage not in STAGES or type(completed) is not int or type(total) is not int or \
+ not 0 <= completed <= total <= 1000:
+ raise ProfileError("calibration progress is invalid", 5)
+ value = {"schema_version": 1, "job_id": job_id, "stage": stage,
+ "completed": completed, "total": total, "updated_at": time.time()}
+ profiles._atomic(_progress_path(profile, job_id),
+ (json.dumps(value, sort_keys=True, allow_nan=False) + "\n").encode("utf-8"))
+
+
+def _load_progress(profile: str, job_id: str) -> dict | None:
+ path = _progress_path(profile, job_id)
+ try:
+ details = path.lstat()
+ except FileNotFoundError:
+ return None
+ if not stat.S_ISREG(details.st_mode) or details.st_nlink != 1 or details.st_size > 1024 or \
+ (os.name == "posix" and
+ (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)):
+ raise ProfileError("calibration progress file must be owner-only", 5)
+ try:
+ value = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, UnicodeError, ValueError):
+ raise ProfileError("calibration progress file is invalid", 5) from None
+ if not isinstance(value, dict) or set(value) != {"schema_version", "job_id", "stage",
+ "completed", "total", "updated_at"} or \
+ value["schema_version"] != 1 or value["job_id"] != job_id or \
+ value["stage"] not in STAGES or type(value["completed"]) is not int or \
+ type(value["total"]) is not int or not 0 <= value["completed"] <= value["total"] <= 1000 or \
+ type(value["updated_at"]) not in (int, float) or not math.isfinite(value["updated_at"]):
+ raise ProfileError("calibration progress file is invalid", 5)
+ return value
+
+
+def _intent(params: dict) -> dict:
+ return {"report_path": params["path"], "exclusive_ack": True,
+ "if_source_sha256": params["if_source_sha256"],
+ "if_report_sha256": params.get("if_report_sha256")}
+
+
+def create(profile: str, action: str, params: dict) -> dict:
+ """Create a receipt after management has checked every reviewed precondition."""
+ if action not in KINDS or not isinstance(params.get("job_id"), str) or \
+ not journal.ID.fullmatch(params["job_id"]):
+ raise ProfileError("calibration job ID or action is invalid", 2)
+ if _activity(profile, params["job_id"]) in ("active", "other_active"):
+ raise ProfileError("another calibration worker is running for this profile", 6)
+ record = journal.begin_direct(profile, KINDS[action], params["if_profile_revision"],
+ _intent(params), operation_id=params["job_id"])
+ return {"ok": True, "job_id": record["operation_id"], "action": action,
+ "path": record["intent"]["report_path"]}
+
+
+def _record(profile: str, job_id: str) -> dict:
+ if not isinstance(job_id, str) or not journal.ID.fullmatch(job_id):
+ raise ProfileError("calibration job ID must be a 32-character hex value", 2)
+ record = journal.load(profile, job_id)
+ if record.get("kind") not in KINDS.values() or record.get("origin") != "direct" or \
+ "if_source_sha256" not in record["intent"]:
+ raise ProfileError("calibration job ID does not identify a Desktop calibration", 5)
+ return record
+
+
+def run(profile: str, action: str, params: dict, work) -> tuple[str, dict]:
+ job_id = params["job_id"]
+ record = _record(profile, job_id)
+ if record["state"] != "running" or record["kind"] != KINDS[action] or \
+ record["profile_revision"] != params["if_profile_revision"] or \
+ record["intent"] != _intent(params):
+ raise ProfileError("calibration job no longer matches its reviewed request", 6)
+ with _worker_lease(profile, job_id):
+ return _run_owned(profile, action, job_id, work)
+
+
+def _run_owned(profile: str, action: str, job_id: str, work) -> tuple[str, dict]:
+ try:
+ result = work()
+ saved = journal.compact_direct_result(KINDS[action], result)
+ try:
+ journal.finish(profile, job_id, "succeeded", saved)
+ except ProfileError:
+ # A recovery read can reconcile a completed measurement first.
+ current = _record(profile, job_id)
+ if current["state"] != "succeeded" or current["result"] != saved:
+ raise
+ return job_id, result
+ except BaseException as exc:
+ if _record(profile, job_id)["state"] == "running":
+ unknown = isinstance(exc, (KeyboardInterrupt, SystemExit)) or \
+ (isinstance(exc, ProfileError) and exc.exit_code == 8)
+ cancelled = (action == "measure" and isinstance(exc, ProfileError) and
+ exc.exit_code == 130)
+ journal.finish(profile, job_id, "completion_unknown" if unknown else "failed",
+ {"error_type": type(exc).__name__,
+ "cancelled": cancelled,
+ "exit_code": exc.exit_code if isinstance(exc, ProfileError) else
+ 130 if unknown else 6})
+ raise
+
+
+def execute(profile: str, action: str, params: dict) -> dict:
+ """Run every preflight inside the receipt, including stale review rejection."""
+ from strata_control import management
+
+ def work() -> dict:
+ if action == "measure":
+ try:
+ _save_progress(profile, params["job_id"], "preflight", 0, 1)
+ except (OSError, ProfileError):
+ pass # Progress is supplementary; the reviewed action still runs.
+ revision, digest = management._calibration_expected_source(profile, params)
+ if management._boolean(params["exclusive_ack"], "exclusive_ack") is not True:
+ raise ProfileError("calibration requires exclusive-access acknowledgement")
+ path = management._local_report_path(params["path"], "calibration report path")
+ if action == "measure":
+ with _cancel_watcher(profile, params["job_id"]) as cancel_event:
+ def progress(stage: str, completed: int, total: int):
+ try:
+ _save_progress(profile, params["job_id"], stage, completed, total)
+ except (OSError, ProfileError):
+ pass
+
+ progress("preflight", 1, 1)
+ report = calibration.measure(profile, path, exclusive_ack=True, say=lambda _: None,
+ expected_profile_revision=revision,
+ expected_source_sha256=digest, job_id=params["job_id"],
+ progress=progress, cancel_event=cancel_event)
+ return {"ok": True, "report_path": str(path), "report": report}
+ _, report = management._calibration_report(profile, str(path), "calibration report path")
+ expected = management._optional_revision(params["if_report_sha256"], "if_report_sha256")
+ if expected is None or report["body_sha256"] != expected:
+ raise ProfileError("calibration report changed after review; review again", 6)
+ if action == "apply":
+ return {"ok": True, "application": calibration.apply_result(
+ profile, path, exclusive_ack=True, expected_report_sha256=expected)}
+ return {"ok": True, "rollback": calibration.rollback_result(
+ profile, path, exclusive_ack=True, expected_report_sha256=expected)}
+
+ operation_id, outcome = run(profile, action, params, work)
+ if action == "measure":
+ report = outcome["report"]
+ return {"ok": True, "operation_id": operation_id, "path": params["path"],
+ "report_id": report["report_id"], "applicable": report["applicable"],
+ "settings": report["settings"]}
+ return {"ok": True, "operation_id": operation_id,
+ "application" if action == "apply" else "rollback":
+ outcome["application" if action == "apply" else "rollback"]}
+
+
+def cancel(profile: str, job_id: str) -> dict:
+ """Request a stop only for the exact active measurement worker."""
+ status(profile, job_id) # Reconcile a finished report before accepting a new request.
+ record = _record(profile, job_id)
+ if record["kind"] != KINDS["measure"]:
+ raise ProfileError("only calibration measurement can be cancelled", 6)
+ if record["state"] != "running" or _activity(profile, job_id) != "active":
+ raise ProfileError("the exact calibration measurement is not active", 6)
+ path = _cancel_path(profile, job_id)
+ try:
+ descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL |
+ getattr(os, "O_NOFOLLOW", 0), 0o600)
+ except FileExistsError:
+ _cancel_requested(profile, job_id)
+ else:
+ try:
+ os.write(descriptor, b"1")
+ os.fsync(descriptor)
+ finally:
+ os.close(descriptor)
+ return {"ok": True, "job_id": job_id, "state": "cancel_requested"}
+
+
+def status(profile: str, job_id: str) -> dict:
+ """Report a bounded receipt; only an exact report may recover measurement success."""
+ record = _record(profile, job_id)
+ action = next(name for name, kind in KINDS.items() if kind == record["kind"])
+ path = Path(record["intent"]["report_path"])
+ report = None
+ recovered = False
+ if action == "measure" and record["state"] in ("running", "succeeded"):
+ try:
+ candidate = calibration.load_report(path)
+ identity = candidate["identity"]
+ if (candidate.get("operation_id") == job_id and
+ type(candidate.get("applicable")) is bool and
+ identity.get("profile_id") == profile and
+ identity.get("profile_revision") == record["profile_revision"] and
+ identity.get("source_sha256") == record["intent"]["if_source_sha256"]):
+ report = candidate
+ except (ProfileError, OSError):
+ pass
+ if report is not None and record["state"] == "running":
+ try:
+ journal.finish(profile, job_id, "succeeded",
+ {"ok": True, "report_path": str(path),
+ "report_id": report["report_id"],
+ "applicable": report["applicable"]})
+ recovered = True
+ except ProfileError:
+ pass
+ record = _record(profile, job_id)
+ result = None
+ if record["state"] == "succeeded":
+ saved = record["result"]
+ result = {"ok": True, "action": action, "operation_id": job_id,
+ "report_id": saved.get("report_id")}
+ if action == "measure":
+ result.update(path=str(path), applicable=saved.get("applicable"),
+ settings=report["settings"] if report is not None else {})
+ else:
+ result.update(changed=saved.get("changed"))
+ if action == "apply":
+ result["application_record"] = saved.get("application_record")
+ else:
+ result["setup_settings_removed"] = saved.get("setup_settings_removed")
+ activity = _activity(profile, job_id)
+ progress = _load_progress(profile, job_id) if action == "measure" else None
+ cancel_requested = _cancel_requested(profile, job_id) if action == "measure" else False
+ state = record["state"]
+ if state == "running":
+ state = "running" if activity == "active" else \
+ "launching" if time.time() - record["started_at"] < 10 else "completion_unknown"
+ elif state == "failed" and record["result"].get("cancelled") is True:
+ state = "cancelled"
+ return {"ok": True, "job": {"job_id": job_id, "action": action, "state": state,
+ "started_at": round(record["started_at"] * 1000),
+ "finished_at": round(record["finished_at"] * 1000) if record["finished_at"] is not None else None,
+ "result": result,
+ "error": "Calibration failed; inspect the saved operation and report." if state == "failed" else
+ "Calibration completion needs inspection before retrying." if state == "completion_unknown" else None,
+ "outcome": "report_recovered" if recovered else "owner_journal",
+ "activity": activity, "progress": progress, "cancel_requested": cancel_requested}}
diff --git a/strata_control/components.py b/strata_control/components.py
new file mode 100644
index 000000000..483726c1a
--- /dev/null
+++ b/strata_control/components.py
@@ -0,0 +1,722 @@
+"""Independent, versioned components: manifests, safe unpacking, atomic activation, rollback.
+
+The application, the engine, the agent runtime, tuning and prepared data are separate deliverables
+with separate lifecycles, so they are separate *components* here. This module is the machinery they
+share: what a component is, whether it may be used on this machine, how it is verified before it is
+unpacked, how it is unpacked without escaping its directory, how it is cached, and how it is
+activated and rolled back.
+
+The design decisions that matter, and why:
+
+**Verification happens before anything is written.** A manifest names each artifact's SHA-256. An
+artifact whose digest does not match is refused and nothing is extracted — not extracted-then-checked,
+because a compromised archive can do damage during extraction.
+
+**Unpacking cannot escape its destination.** Archive members are validated: no absolute paths, no
+`..` segments, no symlinks or hard links pointing outside, no device or FIFO members, and on Windows
+no drive-relative or UNC paths. Every member's resolved destination is checked to be inside the
+target. This is the one place where a hostile input turns into arbitrary file writes, so it is
+checked rather than trusted, and the checks are tested with the actual attack shapes.
+
+**Installation is by content digest, not by version string.** The cache is keyed on the digest of the
+artifact bytes, so a rebuilt artifact with an unchanged version number is a different cache entry,
+and a compatible application update reuses components rather than re-downloading them.
+
+**Activation is a rename, and the previous target is kept.** A component version becomes active by
+renaming a directory into place, which is atomic within a filesystem; the version it replaced is
+moved aside rather than deleted, so rollback restores it exactly. Nothing is ever deleted on
+activation.
+
+**Interrupted transfers are the normal case, not the exception.** A partial download is kept with a
+digest of what is there, resumed when possible, and only promoted to the cache once complete and
+verified. A crash during activation leaves the store consistent because the rename either happened or
+it did not.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import platform
+import re
+import shutil
+import stat
+import tarfile
+import time
+import zipfile
+from dataclasses import asdict, dataclass, field
+from pathlib import Path, PurePosixPath
+from typing import Any, Iterable, Sequence
+
+SCHEMA_VERSION = 1
+
+#: The OS × backend families the handoff commits to. A component may only be activated where its
+#: family is listed here, so an unqualified combination is refused rather than attempted: the packet
+#: is explicit that Windows SYCL and Intel Macs are not supported rather than merely untested.
+BACKEND_MATRIX: dict[str, tuple[str, ...]] = {
+ "metal": ("macos-arm64",),
+ "cuda": ("windows-x86_64", "linux-x86_64"),
+ "hip": ("windows-x86_64", "linux-x86_64"),
+ "sycl": ("linux-x86_64",),
+ "cpu": ("macos-arm64", "macos-x86_64", "windows-x86_64", "linux-x86_64"),
+}
+
+#: Component kinds, so a manifest cannot claim a role the architecture does not have.
+KINDS = ("application", "runtime", "agent-runtime", "tuning", "engine", "prepared-data")
+
+
+class ComponentError(RuntimeError):
+ """A component could not be used. The message names the reason and nothing was changed."""
+
+ def __init__(self, message: str, code: int = 6) -> None:
+ super().__init__(message)
+ self.code = code
+
+
+class UnsafeArchive(ComponentError):
+ """An archive member would escape the destination. Nothing was extracted."""
+
+
+def host_platform() -> str:
+ """This machine as an `os-arch` key, matching `BACKEND_MATRIX`."""
+ system = {"Darwin": "macos", "Linux": "linux", "Windows": "windows"}.get(platform.system())
+ if system is None:
+ raise ComponentError(f"unsupported operating system: {platform.system()}")
+ machine = platform.machine().lower()
+ arch = {"arm64": "arm64", "aarch64": "arm64",
+ "x86_64": "x86_64", "amd64": "x86_64"}.get(machine, machine)
+ return f"{system}-{arch}"
+
+
+def backend_supported(backend: str, target: str | None = None) -> tuple[bool, str]:
+ """Whether a backend family is committed to on a platform, with the reason if not."""
+ target = target or host_platform()
+ if backend not in BACKEND_MATRIX:
+ return False, f"unknown backend family {backend!r}"
+ platforms = BACKEND_MATRIX[backend]
+ if target in platforms:
+ return True, ""
+ return False, (f"{backend} is not a supported combination on {target}; it is supported on "
+ f"{', '.join(platforms)}. Unsupported combinations are not attempted.")
+
+
+# --------------------------------------------------------------------------- manifests
+
+@dataclass
+class Artifact:
+ """One downloadable file, identified by content."""
+
+ name: str
+ url: str | None
+ sha256: str
+ bytes: int
+ format: str = "tar.gz" # tar.gz | tar.xz | zip | file
+ unpack_to: str | None = None # where inside the component the archive's root lands
+
+ def verify_bytes(self, payload: bytes) -> None:
+ actual = hashlib.sha256(payload).hexdigest()
+ if actual != self.sha256:
+ raise ComponentError(
+ f"the downloaded {self.name} does not match its manifest: expected "
+ f"{self.sha256[:16]}…, got {actual[:16]}…")
+ if self.bytes and len(payload) != self.bytes:
+ raise ComponentError(
+ f"{self.name} is {len(payload)} bytes, the manifest declares {self.bytes}")
+
+ def verify_file(self, path: Path) -> None:
+ digest = hashlib.sha256()
+ size = 0
+ with Path(path).open("rb") as fh:
+ for block in iter(lambda: fh.read(1 << 20), b""):
+ digest.update(block)
+ size += len(block)
+ if digest.hexdigest() != self.sha256:
+ raise ComponentError(
+ f"{path.name} does not match its manifest: expected {self.sha256[:16]}…, "
+ f"got {digest.hexdigest()[:16]}…")
+ if self.bytes and size != self.bytes:
+ raise ComponentError(f"{path.name} is {size} bytes, the manifest declares {self.bytes}")
+
+
+@dataclass
+class Component:
+ """A versioned, independently installable piece of the product."""
+
+ id: str
+ version: str
+ kind: str
+ backend: str | None
+ platforms: tuple[str, ...]
+ artifacts: tuple[Artifact, ...]
+ requires: tuple[str, ...] = ()
+ provides: tuple[str, ...] = ()
+ license: str = ""
+ notes: str = ""
+ #: Where the payload must be on the PATH or on disk once active, relative to the component root.
+ entrypoint: str | None = None
+
+ @property
+ def cache_key(self) -> str:
+ """The identity of this component's bytes, not its version label.
+
+ A rebuilt artifact with the same version is a different key, so a cache hit is a statement
+ about the bytes rather than about a string someone typed.
+ """
+ joined = "|".join(f"{a.name}:{a.sha256}" for a in sorted(self.artifacts, key=lambda a: a.name))
+ return hashlib.sha256(f"{self.id}@{self.version}|{joined}".encode()).hexdigest()
+
+ def to_dict(self) -> dict[str, Any]:
+ data = asdict(self)
+ data["schema_version"] = SCHEMA_VERSION
+ data["cache_key"] = self.cache_key
+ return data
+
+
+def parse_manifest(payload: str | bytes | dict) -> Component:
+ """Read a component manifest, refusing anything that is not one.
+
+ A manifest is the input that decides what gets downloaded and unpacked, so it is parsed strictly:
+ a missing digest or an unknown kind is an error, not a default.
+ """
+ if isinstance(payload, (str, bytes)):
+ try:
+ data = json.loads(payload)
+ except json.JSONDecodeError as e:
+ raise ComponentError(f"the component manifest is not valid JSON: {e}") from None
+ else:
+ data = payload
+ if not isinstance(data, dict):
+ raise ComponentError("the component manifest must be a JSON object")
+ if data.get("schema_version") != SCHEMA_VERSION:
+ raise ComponentError(
+ f"unsupported manifest schema_version {data.get('schema_version')!r}; expected "
+ f"{SCHEMA_VERSION}")
+
+ for required in ("id", "version", "kind", "artifacts"):
+ if not data.get(required):
+ raise ComponentError(f"the component manifest has no {required!r}")
+ if data["kind"] not in KINDS:
+ raise ComponentError(
+ f"unknown component kind {data['kind']!r}; expected one of {', '.join(KINDS)}")
+ if not re.fullmatch(r"[a-z0-9][a-z0-9._-]{0,63}", str(data["id"])):
+ raise ComponentError(f"the component id {data['id']!r} is not a plain lowercase name")
+
+ artifacts: list[Artifact] = []
+ for raw in data["artifacts"]:
+ if not isinstance(raw, dict):
+ raise ComponentError("every artifact must be a JSON object")
+ for required in ("name", "sha256", "bytes"):
+ if raw.get(required) in (None, ""):
+ raise ComponentError(f"an artifact has no {required!r}: {raw.get('name')!r}")
+ digest = str(raw["sha256"]).lower()
+ if not re.fullmatch(r"[0-9a-f]{64}", digest):
+ raise ComponentError(
+ f"an artifact's sha256 is not a 64-character hex digest: {raw['sha256']!r}")
+ try:
+ size = int(raw["bytes"])
+ except (TypeError, ValueError):
+ raise ComponentError(f"an artifact's bytes is not a number: {raw['bytes']!r}") from None
+ if size <= 0:
+ raise ComponentError(f"an artifact declares {size} bytes, which cannot be a real file")
+ # A path-like name would be used as a filename later, so it must not be one.
+ if "/" in str(raw["name"]) or "\\" in str(raw["name"]) or str(raw["name"]) in (".", ".."):
+ raise ComponentError(f"an artifact name is a path, which is not allowed: {raw['name']!r}")
+ artifacts.append(Artifact(
+ name=str(raw["name"]), url=raw.get("url"), sha256=digest, bytes=size,
+ format=str(raw.get("format", "tar.gz")),
+ unpack_to=raw.get("unpack_to")))
+ if not artifacts:
+ raise ComponentError("the component manifest lists no artifacts")
+
+ platforms = data.get("platforms")
+ if platforms is None:
+ raise ComponentError(
+ "the component manifest does not say which platforms it supports; an unstated platform "
+ "would be treated as every platform")
+ if not isinstance(platforms, (list, tuple)) or not platforms:
+ raise ComponentError("the component's platforms must be a non-empty list")
+
+ return Component(
+ id=str(data["id"]), version=str(data["version"]), kind=str(data["kind"]),
+ backend=data.get("backend"), platforms=tuple(str(p) for p in platforms),
+ artifacts=tuple(artifacts), requires=tuple(data.get("requires") or ()),
+ provides=tuple(data.get("provides") or ()), license=str(data.get("license") or ""),
+ notes=str(data.get("notes") or ""), entrypoint=data.get("entrypoint"))
+
+
+def check_compatible(component: Component, *, target: str | None = None,
+ backend: str | None = None) -> list[str]:
+ """Why this component cannot be used here. An empty list means it can.
+
+ Compatibility is a refusal gate, not a warning: activating an engine built for another backend is
+ the failure this exists to prevent, and the packet is explicit that unsupported combinations stay
+ explicitly gated rather than attempted.
+ """
+ target = target or host_platform()
+ reasons: list[str] = []
+ if target not in component.platforms:
+ reasons.append(
+ f"{component.id} {component.version} supports {', '.join(component.platforms)}, not {target}")
+ if component.backend and backend is not None and component.backend != backend:
+ reasons.append(
+ f"{component.id} is built for the {component.backend} backend, not {backend}")
+ if component.backend:
+ supported, why = backend_supported(component.backend, target)
+ if not supported:
+ reasons.append(why)
+ return reasons
+
+
+# --------------------------------------------------------------------------- safe unpacking
+
+def _is_unsafe_member(name: str) -> str | None:
+ """Why an archive member name is unsafe, or None if it is fine.
+
+ The attack shapes are listed explicitly rather than relying on a single normalisation trick,
+ because a name that survives normalisation on one platform can still be absolute on another.
+ """
+ if not name or name in (".", "./"):
+ return "an empty member name"
+ if "\x00" in name:
+ return "a NUL byte in the name"
+ # Windows separators are treated as separators on every platform: an archive built on Windows
+ # must not be able to escape a destination on macOS, and vice versa.
+ normalised = name.replace("\\", "/")
+ if normalised.startswith("/"):
+ return "an absolute path"
+ if re.match(r"^[A-Za-z]:", normalised):
+ return "a drive-letter path"
+ if normalised.startswith("//"):
+ return "a UNC path"
+ parts = PurePosixPath(normalised).parts
+ if any(part == ".." for part in parts):
+ return "a '..' segment"
+ return None
+
+
+def _check_member_within(destination: Path, member_name: str) -> Path:
+ """The member's resolved destination, refusing anything outside `destination`.
+
+ Both the lexical check above and this resolved check are performed: the lexical one catches the
+ obvious shapes, and this one catches a path that is only outside after resolution.
+ """
+ unsafe = _is_unsafe_member(member_name)
+ if unsafe:
+ raise UnsafeArchive(f"the archive contains {unsafe}: {member_name!r}")
+ target = (destination / member_name.replace("\\", "/")).resolve()
+ root = destination.resolve()
+ if target != root and root not in target.parents:
+ raise UnsafeArchive(f"the archive member {member_name!r} would land outside the destination")
+ return target
+
+
+def safe_extract(archive: Path, destination: Path, *, fmt: str | None = None) -> list[str]:
+ """Unpack an archive into `destination`, or refuse without writing.
+
+ Validated before any member is written: every member's name and resolved destination is checked
+ first, so a refusal leaves the destination untouched rather than half-populated.
+ """
+ archive = Path(archive)
+ destination = Path(destination)
+ fmt = fmt or _format_of(archive)
+ members = _members(archive, fmt)
+
+ # Validate everything first: a refusal must not leave a partial extraction behind.
+ for name, kind in members:
+ _check_member_within(destination, name)
+ if kind in ("symlink", "hardlink", "device", "fifo"):
+ # A link inside the archive can point anywhere, including outside; verifying where each
+ # one points is more permissive than this product needs, so links are refused outright.
+ raise UnsafeArchive(
+ f"the archive contains a {kind} member ({name!r}); links are not accepted because a "
+ "link can point outside the destination")
+ if kind == "other":
+ raise UnsafeArchive(f"the archive contains an unsupported member type ({name!r})")
+
+ destination.mkdir(parents=True, exist_ok=True)
+ written: list[str] = []
+ if fmt in ("tar.gz", "tar.xz", "tar.bz2", "tar"):
+ with tarfile.open(archive, _tar_mode(fmt)) as tar:
+ for member in tar.getmembers():
+ target = _check_member_within(destination, member.name)
+ if member.isdir():
+ target.mkdir(parents=True, exist_ok=True)
+ continue
+ target.parent.mkdir(parents=True, exist_ok=True)
+ source = tar.extractfile(member)
+ if source is None:
+ continue
+ with target.open("wb") as out:
+ shutil.copyfileobj(source, out)
+ # Preserve the executable bit, which a bundled runtime or engine needs, and nothing
+ # else: the archive's own permission bits are not trusted for setuid or setgid.
+ mode = member.mode & 0o777
+ if mode:
+ target.chmod(mode | (stat.S_IXUSR if mode & 0o100 else 0))
+ written.append(member.name)
+ elif fmt == "zip":
+ with zipfile.ZipFile(archive) as zf:
+ for info in zf.infolist():
+ target = _check_member_within(destination, info.filename)
+ if info.is_dir():
+ target.mkdir(parents=True, exist_ok=True)
+ continue
+ target.parent.mkdir(parents=True, exist_ok=True)
+ with zf.open(info) as source, target.open("wb") as out:
+ shutil.copyfileobj(source, out)
+ written.append(info.filename)
+ else:
+ raise ComponentError(f"unsupported archive format {fmt!r}")
+ return written
+
+
+def _format_of(archive: Path) -> str:
+ name = archive.name.lower()
+ for suffix, fmt in ((".tar.gz", "tar.gz"), (".tgz", "tar.gz"), (".tar.xz", "tar.xz"),
+ (".txz", "tar.xz"), (".tar.bz2", "tar.bz2"), (".zip", "zip"),
+ (".tar", "tar")):
+ if name.endswith(suffix):
+ return fmt
+ raise ComponentError(f"cannot tell the archive format of {archive.name!r} from its name")
+
+
+def _tar_mode(fmt: str) -> str:
+ return {"tar.gz": "r:gz", "tar.xz": "r:xz", "tar.bz2": "r:bz2", "tar": "r:"}[fmt]
+
+
+def _members(archive: Path, fmt: str) -> list[tuple[str, str]]:
+ """Every member as (name, kind), used for validation before extraction."""
+ out: list[tuple[str, str]] = []
+ if fmt == "zip":
+ with zipfile.ZipFile(archive) as zf:
+ for info in zf.infolist():
+ out.append((info.filename, "dir" if info.is_dir() else "file"))
+ return out
+ with tarfile.open(archive, _tar_mode(fmt)) as tar:
+ for member in tar.getmembers():
+ if member.isdir():
+ kind = "dir"
+ elif member.isfile():
+ kind = "file"
+ elif member.issym():
+ kind = "symlink"
+ elif member.islnk():
+ kind = "hardlink"
+ elif member.ischr() or member.isblk():
+ kind = "device"
+ elif member.isfifo():
+ kind = "fifo"
+ else:
+ kind = "other"
+ out.append((member.name, kind))
+ return out
+
+
+# --------------------------------------------------------------------------- the store
+
+@dataclass
+class InstalledComponent:
+ """A component version present on disk, and whether it is the active one."""
+
+ id: str
+ version: str
+ cache_key: str
+ path: str
+ installed_at: float
+ artifact_sha256: tuple[str, ...] = ()
+ active: bool = False
+
+
+class ComponentStore:
+ """Installed components, a content-addressed cache, and atomic activation with rollback.
+
+ Layout::
+
+ <root>/cache/<cache_key>/ unpacked payload, immutable once complete
+ <root>/active/<component-id> a directory rename-linked to a cached version
+ <root>/previous/<component-id> the version that was active before the last activation
+ <root>/partial/<artifact-name> an interrupted transfer, kept for resume
+ <root>/state.json what is installed and what is active
+ """
+
+ def __init__(self, root: Path) -> None:
+ self.root = Path(root)
+ for part in ("cache", "active", "previous", "partial"):
+ (self.root / part).mkdir(parents=True, exist_ok=True)
+
+ # ------------------------------------------------------------------ state
+
+ @property
+ def state_path(self) -> Path:
+ return self.root / "state.json"
+
+ def state(self) -> dict[str, Any]:
+ if not self.state_path.exists():
+ return {"schema_version": SCHEMA_VERSION, "components": {}}
+ try:
+ data = json.loads(self.state_path.read_text(encoding="utf-8"))
+ except json.JSONDecodeError:
+ # A damaged state file must not make the store unusable; the cache on disk is the truth
+ # about what is present, and the state file is rebuilt from it as things are activated.
+ return {"schema_version": SCHEMA_VERSION, "components": {}}
+ if data.get("schema_version") != SCHEMA_VERSION:
+ return {"schema_version": SCHEMA_VERSION, "components": {}}
+ return data
+
+ def _save_state(self, data: dict[str, Any]) -> None:
+ temp = self.state_path.parent / (self.state_path.name + ".tmp")
+ temp.write_text(json.dumps(data, indent=1, sort_keys=True) + "\n", encoding="utf-8")
+ os.replace(temp, self.state_path)
+
+ # ------------------------------------------------------------------ cache and installation
+
+ def cached(self, component: Component) -> Path | None:
+ """The cached payload for exactly these bytes, if it is complete."""
+ path = self.root / "cache" / component.cache_key
+ marker = path / ".complete"
+ return path if marker.exists() else None
+
+ def install(self, component: Component, *, source: Path | None = None,
+ payloads: dict[str, bytes] | None = None,
+ target: str | None = None, backend: str | None = None) -> Path:
+ """Verify and unpack a component into the cache, reusing it when the bytes are known.
+
+ Every artifact is verified *before* unpacking, so a mismatch writes nothing. A component
+ whose bytes are already cached is not downloaded or unpacked again, which is what makes a
+ compatible application update free of engine re-downloads.
+ """
+ reasons = check_compatible(component, target=target, backend=backend)
+ if reasons:
+ raise ComponentError("; ".join(reasons), 2)
+
+ existing = self.cached(component)
+ if existing is not None and source is None and payloads is None:
+ return existing
+
+ destination = self.root / "cache" / component.cache_key
+ if destination.exists() and (destination / ".complete").exists():
+ return destination
+
+ # A staging directory named for the cache key, so a crash leaves an incomplete directory that
+ # is never mistaken for a complete one (the `.complete` marker is written last).
+ staging = self.root / "cache" / f".{component.cache_key}.partial"
+ if staging.exists():
+ shutil.rmtree(staging, ignore_errors=True)
+ staging.mkdir(parents=True)
+
+ try:
+ for artifact in component.artifacts:
+ data = self._obtain(artifact, source=source, payloads=payloads)
+ artifact.verify_bytes(data)
+ into = staging / (artifact.unpack_to or "")
+ into.mkdir(parents=True, exist_ok=True)
+ if artifact.format in ("tar.gz", "tar.xz", "tar.bz2", "tar", "zip"):
+ temp_archive = staging / f".{artifact.name}.archive"
+ temp_archive.write_bytes(data)
+ try:
+ safe_extract(temp_archive, into, fmt=artifact.format)
+ finally:
+ temp_archive.unlink(missing_ok=True)
+ else:
+ (into / artifact.name).write_bytes(data)
+ if artifact.name.endswith((".sh", ".bin")):
+ (into / artifact.name).chmod(0o755)
+ (staging / ".complete").write_text(
+ json.dumps({"cache_key": component.cache_key, "id": component.id,
+ "version": component.version, "installed_at": time.time()},
+ indent=1) + "\n", encoding="utf-8")
+ if destination.exists():
+ shutil.rmtree(destination, ignore_errors=True)
+ os.replace(staging, destination)
+ except BaseException:
+ # Leave nothing that looks complete.
+ shutil.rmtree(staging, ignore_errors=True)
+ raise
+
+ state = self.state()
+ state["components"].setdefault(component.id, {})["installed"] = (
+ state["components"].get(component.id, {}).get("installed") or {})
+ state["components"][component.id]["installed"][component.version] = asdict(InstalledComponent(
+ id=component.id, version=component.version, cache_key=component.cache_key,
+ path=str(destination), installed_at=time.time(),
+ artifact_sha256=tuple(a.sha256 for a in component.artifacts)))
+ self._save_state(state)
+ return destination
+
+ def _obtain(self, artifact: Artifact, *, source: Path | None,
+ payloads: dict[str, bytes] | None) -> bytes:
+ """The artifact's bytes, from memory, from disk, or from its URL."""
+ if payloads and artifact.name in payloads:
+ return payloads[artifact.name]
+ if source is not None:
+ candidate = Path(source)
+ if candidate.is_dir():
+ candidate = candidate / artifact.name
+ if not candidate.exists():
+ raise ComponentError(f"the artifact {artifact.name} is not at {candidate}")
+ return candidate.read_bytes()
+ if artifact.url:
+ return self._fetch(artifact)
+ raise ComponentError(
+ f"{artifact.name} has no url and no local source was given, so it cannot be obtained")
+
+ def _fetch(self, artifact: Artifact) -> bytes:
+ """Download with resume, keeping partial bytes for a later attempt.
+
+ A single interrupted transfer is the normal case on a real connection, so the partial bytes
+ are kept under `partial/` and a ranged request picks up where it stopped. The result is
+ verified by the caller before anything is unpacked.
+ """
+ import urllib.error
+ import urllib.request
+ partial = self.root / "partial" / artifact.name
+ have = partial.stat().st_size if partial.exists() else 0
+ if have > artifact.bytes:
+ partial.unlink() # a stale file from a different artifact
+ have = 0
+ headers = {"Range": f"bytes={have}-"} if have else {}
+ request = urllib.request.Request(artifact.url, headers=headers)
+ mode = "ab" if have else "wb"
+ try:
+ with urllib.request.urlopen(request, timeout=120) as response:
+ if have and response.status != 206:
+ # The server ignored the range, so start again rather than appending to a prefix
+ # and producing a corrupt file that would fail verification much later.
+ have, mode = 0, "wb"
+ with partial.open(mode) as out:
+ while True:
+ block = response.read(1 << 20)
+ if not block:
+ break
+ out.write(block)
+ except (urllib.error.URLError, OSError) as e:
+ raise ComponentError(
+ f"the download of {artifact.name} was interrupted after "
+ f"{partial.stat().st_size if partial.exists() else 0} of {artifact.bytes} bytes; "
+ f"the partial file is kept and a later attempt resumes it ({e})") from e
+ data = partial.read_bytes()
+ if len(data) != artifact.bytes:
+ raise ComponentError(
+ f"the download of {artifact.name} is {len(data)} bytes but the manifest declares "
+ f"{artifact.bytes}; the partial file is kept so a later attempt can resume it")
+ partial.unlink(missing_ok=True)
+ return data
+
+ # ------------------------------------------------------------------ activation and rollback
+
+ def active_path(self, component_id: str) -> Path:
+ return self.root / "active" / component_id
+
+ def activate(self, component: Component, *, target: str | None = None,
+ backend: str | None = None) -> dict[str, Any]:
+ """Make a cached version active, moving the previous one aside.
+
+ The move is a rename, so it either happens or it does not. The version being replaced is
+ moved to `previous/` rather than deleted, which is what makes `rollback` exact.
+ """
+ reasons = check_compatible(component, target=target, backend=backend)
+ if reasons:
+ raise ComponentError("; ".join(reasons), 2)
+ source = self.cached(component)
+ if source is None:
+ raise ComponentError(
+ f"{component.id} {component.version} is not installed; install it before activating")
+ active = self.active_path(component.id)
+ previous = self.root / "previous" / component.id
+
+ moved_aside: str | None = None
+ if active.exists():
+ if previous.exists():
+ shutil.rmtree(previous, ignore_errors=True)
+ os.replace(active, previous)
+ moved_aside = str(previous)
+
+ # Record what is being displaced BEFORE the activation, so a crash between the two leaves a
+ # rollback record that points at the previous version rather than at the new one.
+ state = self.state()
+ entry = state["components"].setdefault(component.id, {})
+ displaced = dict(entry.get("active") or {})
+ if moved_aside and displaced:
+ entry["rollback"] = {"version": displaced.get("version"),
+ "cache_key": displaced.get("cache_key"), "path": moved_aside}
+ self._save_state(state)
+
+ # The cache is never consumed: an application update that reuses an installed engine depends
+ # on the cached payload still being there, so the active directory is a copy. The copy goes
+ # in beside the target and is renamed into place, so the active path is never half-populated.
+ active.parent.mkdir(parents=True, exist_ok=True)
+ incoming = active.parent / f".{component.id}.incoming"
+ if incoming.exists():
+ shutil.rmtree(incoming, ignore_errors=True)
+ shutil.copytree(source, incoming, symlinks=False)
+ os.replace(incoming, active)
+
+ state = self.state()
+ entry = state["components"].setdefault(component.id, {})
+ entry["active"] = {"version": component.version, "cache_key": component.cache_key,
+ "activated_at": time.time(), "from": str(source)}
+ self._save_state(state)
+ return {"id": component.id, "version": component.version, "active": str(active),
+ "moved_aside": moved_aside}
+
+ def rollback(self, component_id: str) -> dict[str, Any]:
+ """Restore the version that was active before the last activation.
+
+ Refuses when there is nothing to restore rather than leaving the component absent, because
+ "rollback succeeded" and "the component is now missing" must not be the same outcome.
+ """
+ previous = self.root / "previous" / component_id
+ if not previous.exists():
+ raise ComponentError(
+ f"there is no previous version of {component_id} to restore", 2)
+ active = self.active_path(component_id)
+ if active.exists():
+ abandoned = self.root / "previous" / f"{component_id}.replaced"
+ if abandoned.exists():
+ shutil.rmtree(abandoned, ignore_errors=True)
+ os.replace(active, abandoned)
+ os.replace(previous, active)
+ state = self.state()
+ entry = state["components"].get(component_id, {})
+ restored = entry.get("rollback", {})
+ entry["active"] = {"version": restored.get("version"), "cache_key": restored.get("cache_key"),
+ "activated_at": time.time(), "restored": True}
+ entry.pop("rollback", None)
+ self._save_state(state)
+ return {"id": component_id, "restored": restored.get("version"), "active": str(active)}
+
+ def installed(self, component_id: str) -> list[InstalledComponent]:
+ """Every version of a component present in the cache."""
+ entry = self.state().get("components", {}).get(component_id, {})
+ out: list[InstalledComponent] = []
+ active = (entry.get("active") or {}).get("cache_key")
+ for version, data in (entry.get("installed") or {}).items():
+ out.append(InstalledComponent(
+ id=component_id, version=version, cache_key=data.get("cache_key", ""),
+ path=data.get("path", ""), installed_at=data.get("installed_at", 0.0),
+ artifact_sha256=tuple(data.get("artifact_sha256") or ()),
+ active=data.get("cache_key") == active))
+ return sorted(out, key=lambda c: c.installed_at)
+
+ def prune_cache(self, *, keep: Iterable[str] = ()) -> list[str]:
+ """Delete cached payloads that nothing refers to. Never touches an active or previous one.
+
+ A compatible application update must not download an engine again, so pruning keeps whatever
+ the active and previous versions point at, plus anything the caller names.
+ """
+ keep_keys = set(keep)
+ state = self.state()
+ for entry in state.get("components", {}).values():
+ for key in (entry.get("active") or {}, entry.get("rollback") or {}):
+ if key.get("cache_key"):
+ keep_keys.add(key["cache_key"])
+ removed: list[str] = []
+ cache = self.root / "cache"
+ for path in cache.iterdir() if cache.exists() else []:
+ if not path.is_dir() or path.name.startswith("."):
+ continue
+ if path.name not in keep_keys:
+ shutil.rmtree(path, ignore_errors=True)
+ removed.append(path.name)
+ return removed
diff --git a/strata_control/doctor.py b/strata_control/doctor.py
new file mode 100644
index 000000000..62df27aaf
--- /dev/null
+++ b/strata_control/doctor.py
@@ -0,0 +1,245 @@
+"""Read-only inventory of the components a saved run config needs."""
+
+from __future__ import annotations
+
+import csv
+import io
+import json
+import os
+import re
+import shutil
+import subprocess
+from importlib import metadata, util
+from pathlib import Path
+
+from strata_control.profiles import read_run_config
+
+
+PATH_FLAGS = {
+ "--pack": "directory",
+ "--native": "file",
+ "--ple-gguf": "file",
+ "--expert-profile": "file",
+ "--mtp": "directory",
+ "--control-vector-scaled": "file_with_scale",
+}
+MONITOR_TEXTUAL_VERSION = "8.2.8"
+
+
+def _location(raw: str, cfg: dict, config_path: Path) -> Path:
+ value = Path(raw).expanduser()
+ if value.is_absolute():
+ return value
+ cwd = cfg.get("cwd")
+ return (Path(cwd) if isinstance(cwd, str) and cwd else config_path.parent) / value
+
+
+def _item(name: str, path: Path, kind: str, *, required: bool = True) -> dict:
+ try:
+ if kind == "file":
+ valid = path.is_file() and path.stat().st_size > 0
+ else:
+ valid = path.is_dir()
+ except OSError:
+ valid = False
+ return {"name": name, "status": "ok" if valid else ("missing" if required else "optional_missing"),
+ "path": str(path), "kind": kind, "required": required}
+
+
+def _selected_indices(value: object) -> list[int] | None:
+ if value is None:
+ return None
+ if isinstance(value, str):
+ parts: object = value.split(",")
+ elif isinstance(value, list):
+ parts = value
+ else:
+ parts = [value]
+ if not isinstance(parts, list) or not 1 <= len(parts) <= 64:
+ raise ValueError("GPU selection must contain 1..64 numeric device indices")
+ result = []
+ for part in parts:
+ if type(part) is int and 0 <= part <= 1023:
+ result.append(part)
+ elif isinstance(part, str) and re.fullmatch(r"[0-9]{1,4}", part.strip()) and int(part) <= 1023:
+ result.append(int(part))
+ else:
+ raise ValueError("GPU selection must contain numeric device indices")
+ if len(set(result)) != len(result):
+ raise ValueError("GPU selection repeats a device index")
+ return result
+
+
+def _nvidia_cards() -> tuple[list[dict] | None, str | None]:
+ """One bounded, read-only host query. It does not establish engine compatibility."""
+ tool = shutil.which("nvidia-smi")
+ if tool is None:
+ return None, "nvidia-smi is not installed or is not on PATH"
+ try:
+ result = subprocess.run(
+ [tool, "--query-gpu=index,name,uuid,memory.total,driver_version",
+ "--format=csv,noheader,nounits"], capture_output=True, text=True, timeout=5, check=False,
+ )
+ except (OSError, UnicodeError, subprocess.TimeoutExpired):
+ return None, "nvidia-smi could not complete within five seconds"
+ if result.returncode != 0:
+ return None, "nvidia-smi returned an error"
+ if len(result.stdout) > 65536:
+ return None, "nvidia-smi output exceeded the size limit"
+ cards = []
+ try:
+ for row in csv.reader(io.StringIO(result.stdout)):
+ if len(row) != 5 or len(cards) >= 64:
+ raise ValueError("invalid field count")
+ index_raw, name, uuid, memory_raw, driver = [part.strip() for part in row]
+ if not (re.fullmatch(r"[0-9]{1,4}", index_raw)
+ and re.fullmatch(r"[0-9]{1,9}", memory_raw)
+ and 0 <= int(index_raw) <= 1023 and int(memory_raw) > 0
+ and 1 <= len(name) <= 128 and 1 <= len(uuid) <= 128
+ and 1 <= len(driver) <= 64
+ and all(part.isprintable() for part in (name, uuid, driver))):
+ raise ValueError("invalid card fields")
+ cards.append({"index": int(index_raw), "name": name, "uuid": uuid,
+ "memory_mib": int(memory_raw), "driver_version": driver})
+ except (csv.Error, ValueError):
+ return None, "nvidia-smi returned an unrecognized card list"
+ if not cards or len({card["index"] for card in cards}) != len(cards):
+ return None, "nvidia-smi returned no cards or duplicate device indices"
+ return cards, None
+
+
+def _live_probe(cfg: dict, backend: str) -> tuple[dict, list[dict]]:
+ try:
+ selected = _selected_indices(cfg.get("gpu"))
+ except ValueError as exc:
+ return ({"status": "invalid_selection", "selected_indices": None, "cards": []},
+ [{"code": "GPU_SELECTION_INVALID", "severity": "error", "message": str(exc)}])
+ if backend == "cpu" and selected is None:
+ return {"status": "not_applicable", "selected_indices": None, "cards": []}, []
+ if backend not in ("cuda", "cuda_or_cpu_unverified", "cpu"):
+ return ({"status": "unverified", "selected_indices": selected, "cards": [],
+ "reason": f"{backend} device numbering needs a qualified live probe"},
+ [{"code": "LIVE_GPU_PROBE_UNAVAILABLE", "severity": "error", "message":
+ f"{backend} device/driver verification is not implemented for this command"}])
+ cards, reason = _nvidia_cards()
+ if cards is None:
+ severity = "error" if selected is not None or backend == "cuda" else "warning"
+ return ({"status": "unavailable", "selected_indices": selected, "cards": [], "reason": reason},
+ [{"code": "LIVE_GPU_PROBE_UNAVAILABLE", "severity": severity, "message": reason}])
+ available = {card["index"] for card in cards}
+ missing = [index for index in selected or [] if index not in available]
+ issues = ([{"code": "GPU_NOT_VISIBLE", "severity": "error", "message":
+ "selected NVIDIA device indices are not visible: " + ", ".join(map(str, missing))}]
+ if missing else [])
+ return ({"status": "missing_selected" if missing else ("ok" if selected is not None else "selection_unverified"),
+ "selected_indices": selected, "cards": cards,
+ "scope": "host card inventory only; engine execution, CUDA compatibility and topology unverified"}, issues)
+
+
+def inspect(config_path: Path | None, *, profile_id: str | None = None, live: bool = False) -> dict:
+ report = {"schema_version": 1, "profile": profile_id, "source_config": str(config_path) if config_path else None,
+ "components": [], "issues": [], "backend": None, "devices_selected": None,
+ "live_gpu_probe": None}
+ components: list[dict] = report["components"]
+ if config_path is None:
+ report["issues"].append({"code": "PROFILE_NOT_SELECTED", "severity": "info",
+ "message": "select a run config or saved profile for model-specific checks"})
+ components.append({"name": "terminal_cli", "status": "ok", "kind": "python_module", "required": True})
+ components.append(_monitor_component())
+ if live:
+ report["issues"].append({"code": "PROFILE_NOT_SELECTED_FOR_LIVE_PROBE", "severity": "error",
+ "message": "select a profile to compare its chosen devices with the host"})
+ report["ok"] = not live
+ return report
+
+ cfg = read_run_config(config_path)
+ report["backend"] = cfg.get("backend") or "cuda_or_cpu_unverified"
+ report["devices_selected"] = cfg.get("gpu")
+ exe = _location(cfg["exe"], cfg, config_path)
+ components.append(_item("engine", exe, "file"))
+ if components[-1]["status"] == "ok" and os.name != "nt" and not os.access(exe, os.X_OK):
+ components[-1]["status"] = "invalid"
+ components[-1]["reason"] = "engine file is not executable"
+ build = exe.parent / "BUILD.json"
+ if build.is_file():
+ try:
+ value = json.loads(build.read_text(encoding="utf-8"))
+ if isinstance(value, dict):
+ components[-1]["version"] = value.get("version")
+ except (OSError, ValueError):
+ components[-1]["build_metadata"] = "invalid"
+ else:
+ components[-1]["build_metadata"] = "unavailable"
+
+ tokenizer = _location(cfg["tokenizer"], cfg, config_path)
+ for child in ("vocab.json", "merges.txt", "token_type.json"):
+ components.append(_item(f"tokenizer/{child}", tokenizer / child, "file"))
+
+ args = cfg["args"]
+ for index, arg in enumerate(args):
+ kind = PATH_FLAGS.get(arg)
+ if kind is None:
+ continue
+ if index + 1 >= len(args):
+ components.append({"name": arg, "status": "invalid", "kind": kind,
+ "required": True, "reason": "missing argument value"})
+ continue
+ raw = args[index + 1]
+ if kind == "file_with_scale":
+ candidate, separator, scale = raw.rpartition(":")
+ if separator:
+ try:
+ float(scale)
+ raw = candidate
+ except ValueError:
+ pass
+ kind = "file"
+ components.append(_item(arg.lstrip("-"), _location(raw, cfg, config_path), kind))
+
+ vision = cfg.get("vision")
+ if isinstance(vision, dict):
+ for key in ("exe", "mmproj", "model"):
+ raw = vision.get(key)
+ if isinstance(raw, str) and raw:
+ components.append(_item(f"vision/{key}", _location(raw, cfg, config_path), "file"))
+ else:
+ components.append({"name": f"vision/{key}", "status": "invalid", "kind": "file",
+ "required": True, "reason": "missing path"})
+
+ components.append(_monitor_component())
+ driver_name = "rocminfo" if cfg.get("backend") == "hip" else "nvidia-smi"
+ components.append({"name": "gpu_driver_probe", "status": "unverified", "kind": "external_tool",
+ "required": False, "tool": shutil.which(driver_name),
+ "reason": "device/driver compatibility needs a live probe on the target host"})
+ for item in components:
+ if item["status"] in ("missing", "invalid") and item["required"]:
+ report["issues"].append({"code": "COMPONENT_" + item["status"].upper(), "severity": "error",
+ "component": item["name"], "message": item.get("reason") or "required component unavailable"})
+ if live:
+ report["live_gpu_probe"], live_issues = _live_probe(cfg, report["backend"])
+ report["issues"].extend(live_issues)
+ report["ok"] = not any(issue["severity"] == "error" for issue in report["issues"])
+ report["integrity"] = "unverified_no_manifest_hashes"
+ return report
+
+
+def _monitor_component() -> dict:
+ component = {"name": "monitor_tui", "kind": "python_module", "required": False,
+ "expected_version": MONITOR_TEXTUAL_VERSION}
+ try:
+ found = util.find_spec("textual")
+ except (ImportError, ValueError):
+ found = None
+ if found is None:
+ return {**component, "status": "optional_missing",
+ "reason": "install the optional monitor dependency from requirements-monitor.txt"}
+ try:
+ version = metadata.version("textual")
+ except metadata.PackageNotFoundError:
+ return {**component, "status": "unverified",
+ "reason": "Textual module is present but its installed version is unavailable"}
+ if version != MONITOR_TEXTUAL_VERSION:
+ return {**component, "status": "unverified", "version": version,
+ "reason": f"interactive monitor was qualified with Textual {MONITOR_TEXTUAL_VERSION}"}
+ return {**component, "status": "ok", "version": version,
+ "check": "package_version_only"}
diff --git a/strata_control/gguf_preflight.py b/strata_control/gguf_preflight.py
new file mode 100644
index 000000000..189bc7fb3
--- /dev/null
+++ b/strata_control/gguf_preflight.py
@@ -0,0 +1,177 @@
+"""Bounded, constant-memory read of the GGUF metadata needed for import preview.
+
+This reads tensor directory entries and checks their declared byte ranges, but it
+does not read tensor payloads or establish provenance.
+"""
+
+from __future__ import annotations
+
+import os
+import stat
+import struct
+from pathlib import Path
+
+from strata_control.profiles import ProfileError
+from tools.gguf_reader import BLOCK_GEOMETRY, GGML_TYPES
+
+
+MAX_HEADER_BYTES = 64 * 1024 * 1024
+MAX_METADATA_KEYS = 4096
+MAX_STRING_BYTES = 1024 * 1024
+MAX_ARRAY_ITEMS = 500_000
+MAX_TENSORS = 100_000
+SCALAR_BYTES = {0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4, 6: 4, 7: 1,
+ 10: 8, 11: 8, 12: 8}
+CAPTURE_STRINGS = {"general.architecture", "tokenizer.ggml.model"}
+PRESENCE_KEYS = {"tokenizer.ggml.tokens", "tokenizer.ggml.merges"}
+
+
+class _Reader:
+ def __init__(self, stream, size: int):
+ self.stream, self.size, self.used = stream, size, 0
+
+ def take(self, count: int) -> bytes:
+ if count < 0 or self.used + count > min(self.size, MAX_HEADER_BYTES):
+ raise ProfileError("GGUF metadata exceeds the bounded inspection limit", 5)
+ data = self.stream.read(count)
+ if len(data) != count:
+ raise ProfileError("GGUF metadata is truncated", 5)
+ self.used += count
+ return data
+
+ def skip(self, count: int) -> None:
+ if count < 0 or self.used + count > min(self.size, MAX_HEADER_BYTES):
+ raise ProfileError("GGUF metadata exceeds the bounded inspection limit", 5)
+ self.stream.seek(count, os.SEEK_CUR)
+ self.used += count
+
+ def u32(self) -> int:
+ return struct.unpack("<I", self.take(4))[0]
+
+ def u64(self) -> int:
+ return struct.unpack("<Q", self.take(8))[0]
+
+ def string(self, *, capture: bool = False) -> str | None:
+ size = self.u64()
+ if size > MAX_STRING_BYTES:
+ raise ProfileError("GGUF metadata string is too large to inspect", 5)
+ if not capture:
+ self.skip(size)
+ return None
+ try:
+ return self.take(size).decode("utf-8")
+ except UnicodeError:
+ raise ProfileError("GGUF metadata has invalid UTF-8", 5) from None
+
+ def value(self, kind: int, *, capture: bool = False) -> object:
+ if kind == 8:
+ return self.string(capture=capture)
+ if kind == 9:
+ element_type, count = self.u32(), self.u64()
+ if count > MAX_ARRAY_ITEMS:
+ raise ProfileError("GGUF metadata array exceeds the inspection limit", 5)
+ if element_type == 8:
+ for _ in range(count):
+ self.string()
+ elif element_type in SCALAR_BYTES:
+ self.skip(count * SCALAR_BYTES[element_type])
+ else:
+ raise ProfileError("GGUF metadata has an unsupported array type", 5)
+ return element_type, count
+ if kind not in SCALAR_BYTES:
+ raise ProfileError("GGUF metadata has an unsupported value type", 5)
+ if capture and kind in (4, 10):
+ return struct.unpack("<I" if kind == 4 else "<Q", self.take(SCALAR_BYTES[kind]))[0]
+ self.skip(SCALAR_BYTES[kind])
+ return None
+
+
+def inspect_metadata(path: Path) -> dict:
+ """Return only bounded compatibility signals from one regular GGUF v3 shard."""
+ try:
+ if stat.S_ISLNK(path.lstat().st_mode):
+ raise ProfileError("GGUF shard is a symlink", 5)
+ descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
+ with os.fdopen(descriptor, "rb") as stream:
+ details = os.fstat(stream.fileno())
+ if not stat.S_ISREG(details.st_mode):
+ raise ProfileError("GGUF shard must be a regular file", 5)
+ reader = _Reader(stream, details.st_size)
+ if reader.take(4) != b"GGUF":
+ raise ProfileError("file does not begin with a GGUF header", 5)
+ version, tensors, keys = reader.u32(), reader.u64(), reader.u64()
+ if version != 3:
+ raise ProfileError("Strata metadata preflight requires GGUF v3", 5)
+ if not 1 <= tensors <= MAX_TENSORS or keys > MAX_METADATA_KEYS:
+ raise ProfileError("GGUF tensor or metadata count exceeds the inspection limit", 5)
+ found: dict[str, object] = {}
+ for _ in range(keys):
+ key = reader.string(capture=True)
+ if key is None or len(key) > 256:
+ raise ProfileError("GGUF metadata key is invalid or too long", 5)
+ value_type = reader.u32()
+ if key in CAPTURE_STRINGS and value_type != 8:
+ raise ProfileError("GGUF architecture or tokenizer model is not a string", 5)
+ value = reader.value(value_type, capture=key in CAPTURE_STRINGS or
+ key == "general.alignment")
+ if key in CAPTURE_STRINGS:
+ found[key] = value
+ elif key in PRESENCE_KEYS:
+ found[key] = value_type == 9 and isinstance(value, tuple) and \
+ value[0] == 8 and value[1] > 0
+ elif key == "general.alignment":
+ found[key] = value
+ alignment = found.get("general.alignment", 32)
+ if type(alignment) is not int or not 1 <= alignment <= 4096 or \
+ alignment & (alignment - 1):
+ raise ProfileError("GGUF tensor alignment is invalid", 5)
+ tensor_types: dict[str, int] = {}
+ expert_types: dict[str, int] = {}
+ required_payload_bytes = 0
+ extents: list[tuple[int, int]] = []
+ for _ in range(tensors):
+ name = reader.string(capture=True)
+ if not name or len(name) > 256:
+ raise ProfileError("GGUF tensor name is invalid or too long", 5)
+ dimensions = reader.u32()
+ if not 1 <= dimensions <= 8:
+ raise ProfileError("GGUF tensor dimension count is invalid", 5)
+ elements = 1
+ for _ in range(dimensions):
+ size = reader.u64()
+ if size == 0 or size > 1_000_000_000 or elements > (1 << 63) // size:
+ raise ProfileError("GGUF tensor shape is invalid", 5)
+ elements *= size
+ type_id, offset = reader.u32(), reader.u64()
+ type_name = GGML_TYPES.get(type_id)
+ geometry = BLOCK_GEOMETRY.get(type_name) if type_name else None
+ if geometry is None or elements % geometry[0]:
+ raise ProfileError("GGUF tensor has an unsupported encoding or shape", 5)
+ if offset % alignment:
+ raise ProfileError("GGUF tensor offset is not aligned", 5)
+ needed = offset + elements // geometry[0] * geometry[1]
+ required_payload_bytes = max(required_payload_bytes, needed)
+ extents.append((offset, needed))
+ tensor_types[type_name] = tensor_types.get(type_name, 0) + 1
+ if "_exps" in name or ".experts." in name:
+ expert_types[type_name] = expert_types.get(type_name, 0) + 1
+ data_start = (reader.used + alignment - 1) // alignment * alignment
+ extents.sort()
+ if any(next_start < end for (_, end), (next_start, _) in zip(extents, extents[1:])):
+ raise ProfileError("GGUF tensor byte ranges overlap", 5)
+ if data_start + required_payload_bytes > details.st_size:
+ raise ProfileError("GGUF tensor payload is shorter than its directory requires", 5)
+ if tensors == 1 and details.st_size - (data_start + required_payload_bytes) >= 64:
+ raise ProfileError("single-tensor GGUF shard has unexplained trailing bytes", 5)
+ return {"architecture": found.get("general.architecture"),
+ "tokenizer_model": found.get("tokenizer.ggml.model"),
+ "tokenizer_tokens_present": found.get("tokenizer.ggml.tokens") is True,
+ "tokenizer_merges_present": found.get("tokenizer.ggml.merges") is True,
+ "tensor_count_reported": tensors, "tensor_count_scanned": tensors,
+ "tensor_types": dict(sorted(tensor_types.items())),
+ "expert_tensor_types": dict(sorted(expert_types.items())),
+ "header_bytes_scanned": reader.used,
+ "payload_bytes_required": required_payload_bytes,
+ "payload_extent_valid": True}
+ except OSError:
+ raise ProfileError("GGUF metadata could not be read", 5) from None
diff --git a/strata_control/journal.py b/strata_control/journal.py
new file mode 100644
index 000000000..6de895aaa
--- /dev/null
+++ b/strata_control/journal.py
@@ -0,0 +1,438 @@
+"""Bounded local records for typed recipe and direct operator runs.
+
+Records contain operation identity and compact outcomes, never credentials,
+request bodies or full calibration reports. A running record after a caller
+crash has unknown completion; it is not proof that a worker is still running.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import os
+import re
+import stat
+import time
+import uuid
+from pathlib import Path
+
+from strata_control import profiles, recipes
+from strata_control.profiles import ProfileError
+
+
+MAX_RECORDS = 500
+MAX_RECORD_BYTES = 64 * 1024
+ID = re.compile(r"[0-9a-f]{32}\Z")
+TERMINAL = frozenset({"succeeded", "failed", "completion_unknown"})
+RESULT_KEYS = frozenset({"ok", "state", "instance_id", "previous_instance_id", "restarted",
+ "source_switched", "source_migrated", "rollback_source_config",
+ "rollback_snapshot_cleanup_pending",
+ "rolled_back", "error", "exit_code", "report_path", "report_id",
+ "applicable", "issue_codes", "error_type", "changed",
+ "application_record", "setup_settings_removed", "generation_ready",
+ "api_identity_verified", "launch_attested", "readiness_state", "verified_now",
+ "run_id", "successful", "cancelled"})
+RECORD_KEYS = frozenset({"schema_version", "operation_id", "profile", "recipe", "kind",
+ "recipe_revision", "profile_revision", "owner_pid", "intent",
+ "state", "started_at", "finished_at", "cancellation_policy",
+ "events", "result"})
+DIRECT_RECORD_KEYS = (RECORD_KEYS - {"recipe", "recipe_revision"}) | {"origin"}
+DIRECT_KINDS = frozenset({"runtime.start", "runtime.stop", "runtime.restart", "runtime.verify",
+ "bench.run",
+ "engine.calibrate.measure", "engine.calibrate.apply", "engine.calibrate.rollback"})
+
+
+def _directory(profile: str, *, create: bool = False) -> Path:
+ directory = recipes._directory(profile, create=create) / ".runs"
+ if create:
+ directory.mkdir(mode=0o700, exist_ok=True)
+ if directory.exists() or directory.is_symlink():
+ details = directory.lstat()
+ if not stat.S_ISDIR(details.st_mode):
+ raise ProfileError("operation journal directory must not be a symlink", 5)
+ if os.name == "posix" and (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077):
+ raise ProfileError("operation journal directory must be owner-only", 5)
+ return directory
+
+
+def _path(profile: str, operation_id: str, *, create: bool = False) -> Path:
+ if not ID.fullmatch(operation_id):
+ raise ProfileError("operation ID must be a 32-character hex value")
+ return _directory(profile, create=create) / f"{operation_id}.json"
+
+
+def _bytes(record: dict) -> bytes:
+ data = (json.dumps(record, sort_keys=True, indent=2, ensure_ascii=False, allow_nan=False) + "\n").encode("utf-8")
+ if len(data) > MAX_RECORD_BYTES:
+ raise ProfileError("operation journal record exceeds 64 KiB", 6)
+ return data
+
+
+def _lock_name(profile: str) -> str:
+ import hashlib
+ return "job" + hashlib.sha256(profile.encode("utf-8")).hexdigest()[:24]
+
+
+def _validate_direct_intent(kind: str, intent: object) -> dict:
+ if kind not in DIRECT_KINDS or not isinstance(intent, dict):
+ raise ProfileError("direct operation kind or intent is unsupported", 5)
+ expected = ({"bench.run": {"path", "suite", "concurrency", "repeat", "request_timeout",
+ "condition", "if_profile_revision", "if_source_sha256",
+ "if_owner_id", "if_instance_id"},
+ "runtime.start": {"wait_s", "shutdown_timeout_s",
+ "expected_profile_revision", "expected_source_sha256"},
+ "runtime.stop": {"wait_s", "expected_owner_id", "expected_instance_id"},
+ "runtime.restart": {"wait_s", "startup_wait_s", "expected_profile_revision",
+ "expected_owner_id", "expected_instance_id",
+ "allow_source_switch", "allow_source_migration",
+ "expected_source_sha256"},
+ "runtime.verify": {"wait_s", "load",
+ "expected_owner_id", "expected_instance_id"}}
+ .get(kind, {"report_path", "exclusive_ack"}))
+ former_restart = expected - {"expected_owner_id", "expected_instance_id"}
+ legacy_restart = (former_restart, former_restart - {"allow_source_migration"},
+ former_restart - {"allow_source_switch", "allow_source_migration",
+ "expected_source_sha256"})
+ legacy_start = kind == "runtime.start" and set(intent) == expected - {
+ "expected_profile_revision", "expected_source_sha256"}
+ legacy_stop = kind == "runtime.stop" and set(intent) == {"wait_s"}
+ legacy_verify = kind == "runtime.verify" and set(intent) == {"wait_s", "load"}
+ calibration_job = (kind.startswith("engine.calibrate.") and
+ set(intent) == expected | {"if_source_sha256", "if_report_sha256"})
+ if (set(intent) != expected and not calibration_job and not legacy_start and not legacy_stop and not legacy_verify and
+ not (kind == "runtime.restart" and set(intent) in legacy_restart)):
+ raise ProfileError("direct operation intent has unsupported fields", 5)
+ if kind == "bench.run":
+ from strata_cli import bench
+ path = intent["path"]
+ suite = intent["suite"]
+ maximum = 64 if suite == "parallel-overload-v1" else 16
+ if (not isinstance(path, str) or len(path) > 1024 or not Path(path).is_absolute() or
+ any(ord(char) < 32 or ord(char) == 127 or
+ 0x202a <= ord(char) <= 0x202e or 0x2066 <= ord(char) <= 0x2069
+ for char in path) or
+ not isinstance(suite, str) or suite not in bench.SUITES or
+ type(intent["concurrency"]) is not int or
+ not 1 <= intent["concurrency"] <= maximum or type(intent["repeat"]) is not int or
+ not 1 <= intent["repeat"] <= 5 or type(intent["request_timeout"]) not in (int, float) or
+ not math.isfinite(intent["request_timeout"]) or
+ not 1 <= intent["request_timeout"] <= 600 or
+ (intent["condition"] is not None and
+ (not isinstance(intent["condition"], str) or
+ not re.fullmatch(r"[a-z][a-z0-9_-]{0,39}", intent["condition"]))) or
+ not isinstance(intent["if_profile_revision"], str) or
+ not re.fullmatch(r"[0-9a-f]{16}", intent["if_profile_revision"]) or
+ not isinstance(intent["if_source_sha256"], str) or
+ not re.fullmatch(r"[0-9a-f]{64}", intent["if_source_sha256"]) or
+ any(not isinstance(intent[key], str) or not re.fullmatch(r"[0-9a-f]{32}", intent[key])
+ for key in ("if_owner_id", "if_instance_id"))):
+ raise ProfileError("direct benchmark intent is invalid", 5)
+ elif kind.startswith("runtime."):
+ ranges = {"wait_s": (0, 600) if kind == "runtime.start" else
+ (1, 1800) if kind == "runtime.restart" else (1, 600),
+ "shutdown_timeout_s": (0, 300), "startup_wait_s": (1, 600)}
+ for key in set(intent) - {"expected_profile_revision", "expected_source_sha256",
+ "expected_owner_id", "expected_instance_id", "load",
+ "allow_source_switch", "allow_source_migration"}:
+ value = intent[key]
+ low, high = ranges[key]
+ if type(value) not in (int, float) or not math.isfinite(value) or not low <= value <= high:
+ raise ProfileError("direct runtime intent has an invalid timeout", 5)
+ revision = intent.get("expected_profile_revision")
+ if kind == "runtime.verify" and type(intent["load"]) is not bool:
+ raise ProfileError("direct verification intent has an invalid load flag", 5)
+ if "allow_source_switch" in intent and type(intent["allow_source_switch"]) is not bool:
+ raise ProfileError("direct restart intent has an invalid source switch flag", 5)
+ if "allow_source_migration" in intent and type(intent["allow_source_migration"]) is not bool:
+ raise ProfileError("direct restart intent has an invalid source migration flag", 5)
+ source_digest = intent.get("expected_source_sha256")
+ if kind in ("runtime.start", "runtime.restart") and ((source_digest is not None and
+ (not isinstance(source_digest, str) or
+ not re.fullmatch(r"[0-9a-f]{64}", source_digest))) or
+ ((intent.get("allow_source_switch") is True or
+ intent.get("allow_source_migration") is True) and
+ source_digest is None)):
+ raise ProfileError("direct runtime intent needs a valid candidate source digest", 5)
+ if kind in ("runtime.start", "runtime.restart") and revision is not None and \
+ (not isinstance(revision, str) or not re.fullmatch(r"[0-9a-f]{16}", revision)):
+ raise ProfileError("direct runtime intent has an invalid profile revision", 5)
+ if kind in ("runtime.stop", "runtime.restart", "runtime.verify"):
+ for key in ("expected_owner_id", "expected_instance_id"):
+ identity = intent.get(key)
+ if identity is not None and (not isinstance(identity, str) or
+ not re.fullmatch(r"[0-9a-f]{32}", identity)):
+ raise ProfileError("direct runtime intent has an invalid identity", 5)
+ if kind == "runtime.verify" and (intent.get("expected_owner_id") is None) != \
+ (intent.get("expected_instance_id") is None):
+ raise ProfileError("direct verification intent needs both identities", 5)
+ else:
+ path = intent["report_path"]
+ if not isinstance(path, str) or len(path) > 4096 or not Path(path).is_absolute() or \
+ intent["exclusive_ack"] is not True:
+ raise ProfileError("direct calibration intent needs an absolute report path and exclusive access", 5)
+ if calibration_job and (not isinstance(intent["if_source_sha256"], str) or
+ not re.fullmatch(r"[0-9a-f]{64}", intent["if_source_sha256"]) or
+ (kind == "engine.calibrate.measure" and intent["if_report_sha256"] is not None) or
+ (kind != "engine.calibrate.measure" and
+ (not isinstance(intent["if_report_sha256"], str) or
+ not re.fullmatch(r"[0-9a-f]{64}", intent["if_report_sha256"])))):
+ raise ProfileError("direct calibration job intent is invalid", 5)
+ return intent
+
+
+def _load_file(path: Path, profile: str) -> dict:
+ try:
+ details = path.lstat()
+ if not stat.S_ISREG(details.st_mode) or details.st_size > MAX_RECORD_BYTES:
+ raise ProfileError("operation record must be a regular file under 64 KiB", 5)
+ if os.name == "posix" and (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077):
+ raise ProfileError("operation record must be owner-only", 5)
+ record = json.loads(path.read_text(encoding="utf-8"))
+ except FileNotFoundError:
+ raise ProfileError("operation record was not found", 5) from None
+ except (OSError, UnicodeError, ValueError) as exc:
+ if isinstance(exc, ProfileError):
+ raise
+ raise ProfileError(f"cannot read operation record ({type(exc).__name__})", 5) from None
+ schema = record.get("schema_version") if isinstance(record, dict) else None
+ expected_keys = RECORD_KEYS if schema == 1 else DIRECT_RECORD_KEYS if schema == 2 else None
+ if not isinstance(record, dict) or expected_keys is None or set(record) != expected_keys or \
+ type(record.get("schema_version")) is not int or \
+ record.get("operation_id") != path.stem or record.get("profile") != profile or \
+ not isinstance(record.get("profile_revision"), str) or \
+ not re.fullmatch(r"[0-9a-f]{16}", record["profile_revision"]) or \
+ not isinstance(record.get("state"), str) or record["state"] not in {"running", *TERMINAL} or \
+ type(record.get("owner_pid")) is not int or record["owner_pid"] < 1 or \
+ not isinstance(record.get("started_at"), (int, float)) or \
+ not math.isfinite(record["started_at"]) or \
+ record.get("cancellation_policy") != "caller_interrupt_may_leave_remote_work_running" or \
+ not isinstance(record.get("events"), list) or not 1 <= len(record["events"]) <= 16 or \
+ (record["state"] == "running" and record.get("finished_at") is not None) or \
+ (record["state"] == "running" and record.get("result") is not None) or \
+ (record["state"] in TERMINAL and not isinstance(record.get("finished_at"), (int, float))) or \
+ (record["state"] in TERMINAL and not math.isfinite(record["finished_at"])) or \
+ (record["state"] in TERMINAL and not isinstance(record.get("result"), dict)):
+ raise ProfileError("operation record has an unsupported shape", 5)
+ try:
+ if schema == 1:
+ if not isinstance(record.get("recipe"), str) or \
+ not profiles.PROFILE_ID.fullmatch(record["recipe"]) or \
+ not isinstance(record.get("recipe_revision"), str) or \
+ not re.fullmatch(r"[0-9a-f]{16}", record["recipe_revision"]):
+ raise ProfileError("operation record has an invalid recipe revision", 5)
+ recipes._validate({"schema_version": 1, "profile": profile, "id": record["recipe"],
+ "kind": record["kind"], "params": record["intent"]},
+ profile, record["recipe"])
+ elif record.get("origin") != "direct":
+ raise ProfileError("operation record has an invalid origin", 5)
+ else:
+ _validate_direct_intent(record["kind"], record["intent"])
+ except (ProfileError, TypeError):
+ raise ProfileError("operation record has an unsupported intent", 5) from None
+ if not all(isinstance(event, dict) and set(event) == {"seq", "at", "state"} and
+ type(event["seq"]) is int and event["seq"] == index and
+ isinstance(event["at"], (int, float)) and math.isfinite(event["at"]) and
+ isinstance(event["state"], str) and event["state"] in {"running", *TERMINAL}
+ for index, event in enumerate(record["events"], 1)):
+ raise ProfileError("operation record has invalid events", 5)
+ if record["events"][0]["state"] != "running" or record["events"][-1]["state"] != record["state"]:
+ raise ProfileError("operation record has inconsistent events", 5)
+ if record["result"] is not None and set(record["result"]) - RESULT_KEYS:
+ raise ProfileError("operation record has unsupported result fields", 5)
+ return record
+
+
+def load(profile: str, operation_id: str) -> dict:
+ record = _load_file(_path(profile, operation_id), profile)
+ if record["state"] == "running":
+ return {**record, "completion_unverified": True}
+ return record
+
+
+def list_runs(profile: str, *, limit: int = 20) -> list[dict]:
+ if not 1 <= limit <= 100:
+ raise ProfileError("operation list limit must be 1..100")
+ directory = _directory(profile)
+ if not directory.exists():
+ return []
+ paths = sorted((path for path in directory.glob("*.json") if ID.fullmatch(path.stem)),
+ key=lambda path: path.lstat().st_mtime, reverse=True)
+ items = []
+ for path in paths[:limit]:
+ try:
+ record = _load_file(path, profile)
+ items.append({"operation_id": record["operation_id"], "recipe": record.get("recipe"),
+ "origin": "recipe" if record["schema_version"] == 1 else "direct",
+ "kind": record["kind"], "state": record["state"],
+ "started_at": record["started_at"], "finished_at": record.get("finished_at"),
+ "completion_unverified": record["state"] == "running"})
+ except ProfileError as exc:
+ items.append({"operation_id": path.stem, "error": str(exc)})
+ return items
+
+
+def _prune(directory: Path, profile: str) -> None:
+ paths = sorted((path for path in directory.glob("*.json") if ID.fullmatch(path.stem)),
+ key=lambda path: path.lstat().st_mtime)
+ count = len(paths)
+ for path in paths:
+ if count < MAX_RECORDS:
+ break
+ try:
+ record = _load_file(path, profile)
+ except ProfileError:
+ continue
+ if record["state"] in TERMINAL:
+ path.unlink()
+ (directory / f"{path.stem}.progress.json").unlink(missing_ok=True)
+ (directory / f"{path.stem}.cancel").unlink(missing_ok=True)
+ count -= 1
+ if count >= MAX_RECORDS:
+ raise ProfileError("operation journal is full; archive completed records before running another action", 5)
+
+
+def _save_new(profile: str, record: dict) -> dict:
+ directory = _directory(profile, create=True)
+ path = _path(profile, record["operation_id"])
+ with profiles._lock(_lock_name(profile)):
+ _prune(directory, profile)
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
+ if hasattr(os, "O_NOFOLLOW"):
+ flags |= os.O_NOFOLLOW
+ descriptor = os.open(path, flags, 0o600)
+ try:
+ with os.fdopen(descriptor, "wb") as stream:
+ stream.write(_bytes(record))
+ stream.flush()
+ os.fsync(stream.fileno())
+ except BaseException:
+ path.unlink(missing_ok=True)
+ raise
+ return record
+
+
+def _running_base(profile: str, kind: str, profile_revision: str, intent: dict,
+ operation_id: str | None = None) -> dict:
+ now = time.time()
+ return {"operation_id": operation_id or uuid.uuid4().hex, "profile": profile, "kind": kind,
+ "profile_revision": profile_revision, "owner_pid": os.getpid(), "intent": intent,
+ "state": "running", "started_at": now, "finished_at": None,
+ "cancellation_policy": "caller_interrupt_may_leave_remote_work_running",
+ "events": [{"seq": 1, "at": now, "state": "running"}], "result": None}
+
+
+def begin(profile: str, recipe: str, kind: str, recipe_revision: str,
+ profile_revision: str, *, intent: dict | None = None) -> dict:
+ if intent is None:
+ intent = {}
+ if not isinstance(intent, dict):
+ raise ProfileError("operation intent must be typed")
+ recipes._validate({"schema_version": 1, "profile": profile, "id": recipe,
+ "kind": kind, "params": intent}, profile, recipe)
+ if not isinstance(recipe_revision, str) or not isinstance(profile_revision, str) or \
+ not re.fullmatch(r"[0-9a-f]{16}", recipe_revision) or \
+ not re.fullmatch(r"[0-9a-f]{16}", profile_revision):
+ raise ProfileError("operation revisions must be full 16-character values")
+ record = {"schema_version": 1, **_running_base(profile, kind, profile_revision, intent),
+ "recipe": recipe, "recipe_revision": recipe_revision}
+ return _save_new(profile, record)
+
+
+def begin_direct(profile: str, kind: str, profile_revision: str, intent: dict,
+ *, operation_id: str | None = None) -> dict:
+ _, current_revision = profiles.load(profile)
+ _validate_direct_intent(kind, intent)
+ if not isinstance(profile_revision, str) or not re.fullmatch(r"[0-9a-f]{16}", profile_revision):
+ raise ProfileError("operation profile revision must be a full 16-character value")
+ if profile_revision != current_revision:
+ raise ProfileError("profile changed before direct operation; preview again", 6)
+ if operation_id is not None and (not isinstance(operation_id, str) or
+ not ID.fullmatch(operation_id)):
+ raise ProfileError("operation ID must be a 32-character hex value")
+ record = {"schema_version": 2, **_running_base(profile, kind, profile_revision, dict(intent), operation_id),
+ "origin": "direct"}
+ return _save_new(profile, record)
+
+
+def finish(profile: str, operation_id: str, state: str, result: dict) -> dict:
+ if state not in TERMINAL:
+ raise ProfileError("operation terminal state is invalid")
+ if not isinstance(result, dict) or set(result) - RESULT_KEYS:
+ raise ProfileError("operation result contains unsupported fields")
+ path = _path(profile, operation_id)
+ with profiles._lock(_lock_name(profile)):
+ record = _load_file(path, profile)
+ if record["state"] != "running":
+ raise ProfileError("operation has already finished", 6)
+ now = time.time()
+ record.update({"state": state, "finished_at": now, "result": result})
+ record["events"].append({"seq": len(record["events"]) + 1, "at": now, "state": state})
+ profiles._atomic(path, _bytes(record))
+ return record
+
+
+def run_direct(profile: str, kind: str, profile_revision: str, intent: dict, action) -> tuple[str, dict]:
+ """Record one already-authorized CLI action; uncertain interruption stays explicit."""
+ record = begin_direct(profile, kind, profile_revision, intent)
+ try:
+ result = action()
+ if not isinstance(result, dict):
+ raise ProfileError("direct operation returned an invalid result", 6)
+ except BaseException as exc:
+ unknown = isinstance(exc, (KeyboardInterrupt, SystemExit)) or \
+ (isinstance(exc, ProfileError) and exc.exit_code == 8)
+ finish(profile, record["operation_id"], "completion_unknown" if unknown else "failed",
+ {"error_type": type(exc).__name__,
+ "exit_code": exc.exit_code if isinstance(exc, ProfileError) else 130 if unknown else 6})
+ raise
+ state = ("succeeded" if result.get("ok", True) else
+ "completion_unknown" if result.get("exit_code") == 8 else "failed")
+ finish(profile, record["operation_id"], state, compact_direct_result(kind, result))
+ return record["operation_id"], result
+
+
+def compact_direct_result(kind: str, result: dict) -> dict:
+ if kind == "bench.run":
+ summary = result.get("summary") or {}
+ return {"ok": result.get("ok", True), "report_path": result.get("path"),
+ "run_id": summary.get("run_id"), "instance_id": summary.get("instance_id"),
+ "successful": result.get("successful"), "cancelled": summary.get("cancelled")}
+ if kind == "runtime.verify":
+ return {key: result.get(key) for key in ("ok", "state", "instance_id", "error", "exit_code",
+ "api_identity_verified", "launch_attested", "generation_ready",
+ "readiness_state", "verified_now")}
+ if kind.startswith("runtime."):
+ return {key: result.get(key) for key in ("ok", "state", "instance_id", "previous_instance_id",
+ "restarted", "rolled_back", "source_switched",
+ "source_migrated", "rollback_source_config",
+ "rollback_snapshot_cleanup_pending", "launch_attested",
+ "error", "exit_code")}
+ if kind == "engine.calibrate.measure":
+ report = result.get("report") or {}
+ return {"ok": result.get("ok", True), "report_path": result.get("report_path"),
+ "report_id": report.get("report_id"), "applicable": report.get("applicable")}
+ if kind == "engine.calibrate.apply":
+ application = result.get("application") or {}
+ return {"ok": result.get("ok", True), "report_id": application.get("report_id"),
+ "changed": application.get("changed"),
+ "application_record": application.get("application_record")}
+ rollback = result.get("rollback") or {}
+ return {"ok": result.get("ok", True), "report_id": rollback.get("report_id"),
+ "changed": rollback.get("changed"),
+ "setup_settings_removed": rollback.get("setup_settings_removed")}
+
+
+def compact_result(kind: str, result: dict) -> dict:
+ """Only reviewed, bounded fields reach the persistent journal."""
+ if kind == "runtime.restart":
+ return {key: result.get(key) for key in ("ok", "state", "instance_id", "previous_instance_id",
+ "restarted", "rolled_back", "source_switched",
+ "source_migrated", "rollback_source_config",
+ "rollback_snapshot_cleanup_pending", "launch_attested",
+ "error", "exit_code")}
+ if kind == "engine.calibrate.measure":
+ report = result.get("report") or {}
+ return {"ok": result.get("ok"), "report_path": result.get("report_path"),
+ "report_id": report.get("report_id"), "applicable": report.get("applicable")}
+ report = result.get("report") or {}
+ return {"ok": result.get("ok"), "issue_codes": [item.get("code") for item in report.get("issues", [])][:50]}
diff --git a/strata_control/management.py b/strata_control/management.py
new file mode 100644
index 000000000..56c6a22d7
--- /dev/null
+++ b/strata_control/management.py
@@ -0,0 +1,613 @@
+"""Owner-local, typed runtime operations shared by CLI and future Desktop adapters.
+
+The one-shot JSON entry point is for a trusted local host process. It is not an
+HTTP API and must not be forwarded from a browser or an inference credential.
+All mutations still pass through the existing owner host and operation journal.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import hashlib
+import json
+import math
+import re
+import sys
+from pathlib import Path
+from typing import Any
+
+from strata_control import doctor, journal, models, profiles, runtime
+from strata_control.profiles import ProfileError
+
+
+MAX_REQUEST_BYTES = 64 * 1024
+_ACTIONS = {
+ "bench.run.plan": {"path", "suite", "concurrency", "repeat", "request_timeout", "condition"},
+ "bench.run": {"path", "suite", "concurrency", "repeat", "request_timeout", "condition",
+ "if_profile_revision", "if_source_sha256", "if_owner_id", "if_instance_id"},
+ "bench.job.create": {"job_id", "path", "suite", "concurrency", "repeat", "request_timeout",
+ "condition", "if_profile_revision", "if_source_sha256",
+ "if_owner_id", "if_instance_id"},
+ "bench.job": {"job_id"},
+ "bench.progress": {"path"},
+ "bench.cancel": {"path"},
+ "bench.report": {"path"},
+ "bench.compare": {"baseline", "candidate"},
+ "calibration.plan": set(),
+ "calibration.job.create": {"job_id", "action", "path", "exclusive_ack",
+ "if_profile_revision", "if_source_sha256", "if_report_sha256"},
+ "calibration.job": {"job_id"},
+ "calibration.cancel": {"job_id"},
+ "calibration.measure": {"path", "exclusive_ack", "if_profile_revision", "if_source_sha256"},
+ "calibration.apply.plan": {"path"},
+ "calibration.apply": {"path", "exclusive_ack", "if_profile_revision", "if_source_sha256",
+ "if_report_sha256"},
+ "calibration.rollback.plan": {"path"},
+ "calibration.rollback": {"path", "exclusive_ack", "if_profile_revision", "if_source_sha256",
+ "if_report_sha256"},
+ "components.inspect": {"live"},
+ "models.installed": set(),
+ "models.inspect": {"model_id"},
+ "models.import.plan": {"path"},
+ "profile.inspect": set(),
+ "profile.change.plan": {"overrides", "source_config", "if_revision"},
+ "profile.change": {"overrides", "source_config", "if_revision", "if_source_sha256"},
+ "runtime.start.plan": {"shutdown_timeout_s"},
+ "runtime.start": {"wait_s", "shutdown_timeout_s", "if_profile_revision", "if_source_sha256"},
+ "runtime.status": set(),
+ "runtime.verify.plan": {"load"},
+ "runtime.verify": {"wait_s", "load", "if_owner_id", "if_instance_id"},
+ "runtime.stop.plan": set(),
+ "runtime.stop": {"wait_s", "if_owner_id", "if_instance_id"},
+ "runtime.restart.plan": {"allow_source_switch", "allow_source_migration"},
+ "runtime.restart": {"wait_s", "startup_wait_s", "if_profile_revision",
+ "if_owner_id", "if_instance_id", "allow_source_switch",
+ "allow_source_migration", "if_source_sha256"},
+}
+
+
+def _profile_change_plan(profile: str, overrides: object, source_config: object) -> tuple[dict, dict]:
+ """Validate an editable candidate without changing the saved profile."""
+ current, revision = profiles.load(profile)
+ if not isinstance(overrides, dict):
+ raise ProfileError("profile overrides must be an object")
+ profiles.validate_overrides(overrides)
+ if not isinstance(source_config, str) or not Path(source_config).is_absolute():
+ raise ProfileError("source_config must be an absolute path")
+ if source_config == current["source_config"]:
+ source = source_config
+ else:
+ proposed_source, source_revision = profiles.propose_source(profile, source_config)
+ if source_revision != revision:
+ raise ProfileError("profile changed during source preview; retry", 6)
+ source = proposed_source["source_config"]
+ proposed = {**current, "source_config": source, "overrides": dict(overrides)}
+ profiles.validate_profile(proposed, expected_name=profile)
+ path = Path(source)
+ try:
+ raw = path.read_bytes()
+ if len(raw) > 1024 * 1024:
+ raise ProfileError("run config is larger than 1 MiB", 5)
+ cfg = profiles.read_run_config(path)
+ if path.read_bytes() != raw:
+ raise ProfileError("run config changed during profile preview; retry", 6)
+ except OSError as exc:
+ raise ProfileError(f"cannot read run config ({type(exc).__name__})", 5) from None
+ from strata_cli.cli import _effective
+ effective, origins = _effective(cfg, proposed)
+ changes = {key: {"before": current["overrides"].get(key), "after": overrides.get(key)}
+ for key in sorted(profiles.OVERRIDE_KEYS)
+ if current["overrides"].get(key) != overrides.get(key)}
+ plan = {"profile": profile, "revision": revision,
+ "source_config_before": current["source_config"],
+ "source_config_after": source,
+ "source_sha256": hashlib.sha256(raw).hexdigest(),
+ "overrides_before": current["overrides"],
+ "overrides_after": proposed["overrides"],
+ "changes": changes, "effective": effective, "origin": origins,
+ "would_save": bool(changes or current["source_config"] != source),
+ "running_unchanged": True}
+ return plan, proposed
+
+
+def _seconds(value: object, low: float, high: float, label: str) -> float:
+ if (type(value) not in (int, float) or not math.isfinite(value) or
+ not low <= value <= high):
+ raise ProfileError(f"{label} must be finite seconds in {low:g}..{high:g}")
+ return float(value)
+
+
+def _boolean(value: object, label: str) -> bool:
+ if type(value) is not bool:
+ raise ProfileError(f"{label} must be true or false")
+ return value
+
+
+def _optional_revision(value: object, label: str) -> str | None:
+ if value is None:
+ return None
+ if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value):
+ raise ProfileError(f"{label} must be a 64-character lowercase SHA-256")
+ return value
+
+
+def _profile_revision(value: object) -> str | None:
+ if value is None:
+ return None
+ if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{16}", value):
+ raise ProfileError("if_profile_revision must be a 16-character lowercase revision")
+ return value
+
+
+def _optional_identity(value: object, label: str) -> str | None:
+ if value is None:
+ return None
+ if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{32}", value):
+ raise ProfileError(f"{label} must be a 32-character lowercase ID")
+ return value
+
+
+def _local_report_path(value: object, label: str) -> Path:
+ if not isinstance(value, str) or len(value) > 1024 or not Path(value).is_absolute() or \
+ any(ord(char) < 32 or ord(char) == 127 or
+ 0x202a <= ord(char) <= 0x202e or 0x2066 <= ord(char) <= 0x2069 for char in value):
+ raise ProfileError(f"{label} must be an absolute local report path under 1024 characters")
+ return Path(value)
+
+
+def _calibration_source(profile: str) -> tuple[str, str]:
+ source, saved, revision = profiles.resolve(profile)
+ if saved is None or revision is None:
+ raise ProfileError("calibration requires a saved profile", 2)
+ try:
+ raw = source.read_bytes()
+ except OSError:
+ raise ProfileError("calibration source config is unavailable", 5) from None
+ if len(raw) > 1024 * 1024:
+ raise ProfileError("calibration source config exceeds 1 MiB", 5)
+ return revision, hashlib.sha256(raw).hexdigest()
+
+
+def _calibration_expected_source(profile: str, params: dict) -> tuple[str, str]:
+ revision = _profile_revision(params["if_profile_revision"])
+ digest = _optional_revision(params["if_source_sha256"], "if_source_sha256")
+ if revision is None or digest is None:
+ raise ProfileError("calibration needs the reviewed profile revision and source digest")
+ if (revision, digest) != _calibration_source(profile):
+ raise ProfileError("calibration source changed after review; review again", 6)
+ return revision, digest
+
+
+def _calibration_report(profile: str, value: object, label: str) -> tuple[Path, dict]:
+ from strata_control import calibration
+ path = _local_report_path(value, label)
+ report = calibration.load_report(path)
+ return path, report
+
+
+def runtime_action(action: str, profile: str, *, plan: bool = False,
+ wait: float = 300, shutdown_timeout: float = 30,
+ startup_wait: float = 300, load: bool = False,
+ if_profile_revision: str | None = None,
+ if_owner_id: str | None = None,
+ if_instance_id: str | None = None,
+ allow_source_switch: bool = False,
+ allow_source_migration: bool = False,
+ if_source_sha256: str | None = None) -> dict:
+ """Execute one validated owner operation and return its CLI/host result."""
+ runtime._name(profile)
+ if type(plan) is not bool:
+ raise ProfileError("plan must be true or false")
+ if action == "start":
+ wait = _seconds(wait, 0, 600, "start wait")
+ shutdown_timeout = _seconds(shutdown_timeout, 0, 300, "shutdown timeout")
+ if_profile_revision = _profile_revision(if_profile_revision)
+ if_source_sha256 = _optional_revision(if_source_sha256, "if_source_sha256")
+ if plan:
+ if if_profile_revision is not None or if_source_sha256 is not None:
+ raise ProfileError("start plan cannot include execution preconditions")
+ runtime._supported()
+ profiles.load(profile)
+ launch, source_sha256 = runtime._start_candidate(profile)
+ repeated_launch, repeated_digest = runtime._start_candidate(profile)
+ if launch != repeated_launch or source_sha256 != repeated_digest:
+ raise ProfileError("start candidate changed during preview; retry", 6)
+ return {"ok": True, "plan": {"profile": profile, "launch": launch,
+ "source_sha256": source_sha256,
+ "shutdown_timeout": shutdown_timeout,
+ "would_start": False}}
+ revision = profiles.load(profile)[1]
+ if if_profile_revision is not None or if_source_sha256 is not None:
+ runtime._check_start_candidate(profile, if_profile_revision, if_source_sha256)
+ operation_id, result = journal.run_direct(profile, "runtime.start", revision,
+ {"wait_s": wait, "shutdown_timeout_s": shutdown_timeout,
+ "expected_profile_revision": if_profile_revision,
+ "expected_source_sha256": if_source_sha256},
+ lambda: runtime.start(profile, wait=wait, shutdown_timeout=shutdown_timeout,
+ expected_profile_revision=if_profile_revision,
+ expected_source_sha256=if_source_sha256))
+ elif action == "status":
+ if plan:
+ raise ProfileError("status has no plan")
+ return runtime.status(profile)
+ elif action == "verify":
+ load = _boolean(load, "load")
+ if_owner_id = _optional_identity(if_owner_id, "if_owner_id")
+ if_instance_id = _optional_identity(if_instance_id, "if_instance_id")
+ if plan:
+ if if_owner_id is not None or if_instance_id is not None:
+ raise ProfileError("verify plan cannot include execution preconditions")
+ current = runtime.status(profile)
+ if not current.get("ok") or current.get("state") != "ready":
+ return {"ok": False, "state": current.get("state", "unavailable"),
+ "error": "runtime_not_ready", "exit_code": 6}
+ owner, instance = current.get("owner_id"), current.get("instance_id")
+ if _optional_identity(owner, "owner_id") is None or \
+ _optional_identity(instance, "instance_id") is None:
+ raise ProfileError("runtime verification needs an owned ready instance", 6)
+ return {"ok": True, "plan": {"profile": profile, "state": "ready",
+ "owner_id": owner, "instance_id": instance,
+ "model_state": current.get("model_state"),
+ "load": load, "would_load": load and current.get("model_state") == "unloaded",
+ "would_verify": False, "probe": "one_token_generation"}}
+ wait = _seconds(wait, 1, 600, "verify wait")
+ if (if_owner_id is None) != (if_instance_id is None):
+ raise ProfileError("verify requires both reviewed owner and instance IDs")
+ if if_owner_id is not None:
+ current = runtime.status(profile)
+ if current.get("owner_id") != if_owner_id:
+ raise ProfileError("owner_changed_after_verify_plan", 6)
+ if current.get("instance_id") != if_instance_id:
+ raise ProfileError("instance_changed_after_verify_plan", 6)
+ revision = profiles.load(profile)[1]
+ operation_id, result = journal.run_direct(profile, "runtime.verify", revision,
+ {"wait_s": wait, "load": load,
+ "expected_owner_id": if_owner_id, "expected_instance_id": if_instance_id},
+ lambda: runtime.verify(profile, timeout=wait, load=load,
+ expected_owner_id=if_owner_id,
+ expected_instance_id=if_instance_id))
+ elif action == "stop":
+ wait = _seconds(wait, 1, 600, "stop wait")
+ if_owner_id = _optional_identity(if_owner_id, "if_owner_id")
+ if_instance_id = _optional_identity(if_instance_id, "if_instance_id")
+ if plan:
+ if if_owner_id is not None or if_instance_id is not None:
+ raise ProfileError("stop plan cannot include execution preconditions")
+ return runtime.plan_stop(profile)
+ if if_owner_id is not None:
+ current = runtime.status(profile)
+ if current.get("owner_id") != if_owner_id:
+ raise ProfileError("owner_changed_after_stop_plan", 6)
+ if current.get("instance_id") != if_instance_id:
+ raise ProfileError("instance_changed_after_stop_plan", 6)
+ revision = profiles.load(profile)[1]
+ operation_id, result = journal.run_direct(profile, "runtime.stop", revision,
+ {"wait_s": wait, "expected_owner_id": if_owner_id,
+ "expected_instance_id": if_instance_id},
+ lambda: runtime.stop(profile, timeout=wait,
+ expected_owner_id=if_owner_id,
+ expected_instance_id=if_instance_id))
+ elif action == "restart":
+ allow_source_switch = _boolean(allow_source_switch, "allow_source_switch")
+ allow_source_migration = _boolean(allow_source_migration, "allow_source_migration")
+ if_source_sha256 = _optional_revision(if_source_sha256, "if_source_sha256")
+ if_profile_revision = _profile_revision(if_profile_revision)
+ if_owner_id = _optional_identity(if_owner_id, "if_owner_id")
+ if_instance_id = _optional_identity(if_instance_id, "if_instance_id")
+ if plan:
+ if any(value is not None for value in (if_profile_revision, if_source_sha256,
+ if_owner_id, if_instance_id)):
+ raise ProfileError("restart plan cannot include execution preconditions")
+ return runtime.plan_restart(profile, allow_source_switch=allow_source_switch,
+ allow_source_migration=allow_source_migration)
+ wait = _seconds(wait, 1, 1800, "restart wait")
+ startup_wait = _seconds(startup_wait, 1, 600, "startup wait")
+ if (if_owner_id is None) != (if_instance_id is None):
+ raise ProfileError("restart requires both reviewed owner and instance IDs")
+ if (allow_source_switch or allow_source_migration) and not if_source_sha256:
+ raise ProfileError("source change needs --if-source-sha256 from --plan")
+ if if_owner_id is not None:
+ current = runtime.status(profile)
+ if current.get("owner_id") != if_owner_id:
+ raise ProfileError("owner_changed_after_restart_plan", 6)
+ if current.get("instance_id") != if_instance_id:
+ raise ProfileError("instance_changed_after_restart_plan", 6)
+ revision = profiles.load(profile)[1]
+ expected = if_profile_revision or revision
+ operation_id, result = journal.run_direct(profile, "runtime.restart", revision,
+ {"wait_s": wait, "startup_wait_s": startup_wait,
+ "expected_profile_revision": expected,
+ "expected_owner_id": if_owner_id,
+ "expected_instance_id": if_instance_id,
+ "allow_source_switch": allow_source_switch,
+ "allow_source_migration": allow_source_migration,
+ "expected_source_sha256": if_source_sha256},
+ lambda: runtime.restart(profile, timeout=wait, startup_wait=startup_wait,
+ expected_profile_revision=expected,
+ expected_owner_id=if_owner_id,
+ expected_instance_id=if_instance_id,
+ allow_source_switch=allow_source_switch,
+ allow_source_migration=allow_source_migration,
+ expected_source_sha256=if_source_sha256))
+ else:
+ raise ProfileError("unsupported runtime action")
+ return {**result, "operation_id": operation_id}
+
+
+def dispatch(request: object) -> dict:
+ """Validate one versioned local-host request; reject unknown fields/actions."""
+ if (not isinstance(request, dict) or set(request) !=
+ {"schema_version", "action", "profile", "params"} or
+ type(request.get("schema_version")) is not int or request["schema_version"] != 1):
+ raise ProfileError("management request needs schema_version 1, action, profile and params")
+ action, profile, params = request["action"], request["profile"], request["params"]
+ if not isinstance(action, str) or action not in _ACTIONS:
+ raise ProfileError("management action is unsupported")
+ if not isinstance(profile, str) or not profiles.PROFILE_ID.fullmatch(profile):
+ raise ProfileError("management profile name is invalid")
+ if not isinstance(params, dict) or (set(params) != _ACTIONS[action] and
+ not (action == "bench.run" and set(params) == _ACTIONS[action] | {"job_id"}) and
+ not (action in ("calibration.measure", "calibration.apply", "calibration.rollback") and
+ set(params) == _ACTIONS[action] | {"job_id"})):
+ raise ProfileError("management action parameters are invalid")
+ if action in ("calibration.measure", "calibration.apply", "calibration.rollback") and "job_id" in params:
+ from strata_control import calibration_jobs
+ result = calibration_jobs.execute(profile, action.removeprefix("calibration."), params)
+ elif action in ("bench.run.plan", "bench.run"):
+ from strata_control import benchmarking
+ checked = {**params, "path": str(_local_report_path(params["path"], "benchmark output path"))}
+ if action == "bench.run":
+ identities = (_profile_revision(checked["if_profile_revision"]),
+ _optional_revision(checked["if_source_sha256"], "if_source_sha256"),
+ _optional_identity(checked["if_owner_id"], "if_owner_id"),
+ _optional_identity(checked["if_instance_id"], "if_instance_id"))
+ if any(identity is None for identity in identities):
+ raise ProfileError("benchmark execution needs reviewed profile, source, owner and instance IDs")
+ result = benchmarking.run(profile, checked)
+ else:
+ result = {"ok": True, "plan": benchmarking.plan(profile, checked)}
+ elif action == "bench.job.create":
+ from strata_control import benchmarking
+ checked = {**params, "path": str(_local_report_path(params["path"], "benchmark output path"))}
+ result = benchmarking.create_job(profile, checked)
+ elif action == "bench.job":
+ from strata_control import benchmarking
+ result = benchmarking.job_status(profile, params["job_id"])
+ elif action == "bench.progress":
+ from strata_cli import bench
+ from strata_control import benchmarking
+ profiles.load(profile)
+ target = _local_report_path(params["path"], "benchmark progress path")
+ progress = bench.progress(target)
+ directory = target.parent if target.name in ("results.json", "progress.json") else target
+ result = {"ok": True, "progress": progress,
+ "activity": benchmarking.benchmark_activity(profile, directory),
+ "cancel_requested": benchmarking.cancel_requested(directory)}
+ elif action == "bench.cancel":
+ from strata_control import benchmarking
+ profiles.load(profile)
+ result = benchmarking.request_cancel(
+ profile, _local_report_path(params["path"], "benchmark cancel path"))
+ elif action == "bench.report":
+ from strata_cli import bench
+ profiles.load(profile)
+ report = bench.load(_local_report_path(params["path"], "benchmark report path"))
+ result = {"ok": True, "summary": bench.summary(report),
+ "markdown": bench.markdown_report(report)}
+ elif action == "bench.compare":
+ from strata_cli import bench
+ profiles.load(profile)
+ baseline = bench.load(_local_report_path(params["baseline"], "baseline report path"))
+ candidate = bench.load(_local_report_path(params["candidate"], "candidate report path"))
+ comparison = bench.compare(baseline, candidate)
+ result = {"ok": True, "comparison": comparison,
+ "markdown": bench.markdown_comparison(comparison)}
+ elif action == "calibration.plan":
+ from strata_control import calibration
+ result = {"ok": True, "plan": calibration.preview(profile)}
+ elif action == "calibration.job.create":
+ from strata_control import calibration_jobs
+ if params["action"] not in calibration_jobs.KINDS:
+ raise ProfileError("calibration job action is invalid", 2)
+ _calibration_expected_source(profile, params)
+ if _boolean(params["exclusive_ack"], "exclusive_ack") is not True:
+ raise ProfileError("calibration requires exclusive-access acknowledgement")
+ path = _local_report_path(params["path"], "calibration report path")
+ report_sha = params["if_report_sha256"]
+ if params["action"] == "measure":
+ if report_sha is not None or path.exists() or path.is_symlink() or not path.parent.is_dir():
+ raise ProfileError("calibration output must be a new file in an existing directory", 2)
+ else:
+ _, report = _calibration_report(profile, str(path), "calibration report path")
+ expected = _optional_revision(report_sha, "if_report_sha256")
+ if expected is None or expected != report["body_sha256"]:
+ raise ProfileError("calibration report changed after review; review again", 6)
+ result = calibration_jobs.create(profile, params["action"], {**params, "path": str(path)})
+ elif action == "calibration.job":
+ from strata_control import calibration_jobs
+ result = calibration_jobs.status(profile, params["job_id"])
+ elif action == "calibration.cancel":
+ from strata_control import calibration_jobs
+ result = calibration_jobs.cancel(profile, params["job_id"])
+ elif action == "calibration.measure":
+ from strata_control import calibration
+ revision, digest = _calibration_expected_source(profile, params)
+ if _boolean(params["exclusive_ack"], "exclusive_ack") is not True:
+ raise ProfileError("calibration requires exclusive-access acknowledgement")
+ path = _local_report_path(params["path"], "calibration report path")
+ operation_id, measured = journal.run_direct(profile, "engine.calibrate.measure", revision,
+ {"report_path": str(path), "exclusive_ack": True},
+ lambda: {"ok": True, "report_path": str(path), "report": calibration.measure(
+ profile, path, exclusive_ack=True, say=lambda _: None,
+ expected_profile_revision=revision, expected_source_sha256=digest)})
+ report = measured["report"]
+ result = {"ok": True, "operation_id": operation_id, "path": str(path),
+ "report_id": report["report_id"], "applicable": report["applicable"],
+ "settings": report["settings"]}
+ elif action in ("calibration.apply.plan", "calibration.rollback.plan"):
+ from strata_control import calibration
+ revision, digest = _calibration_source(profile)
+ path, report = _calibration_report(profile, params["path"], "calibration report path")
+ review = (calibration.review(profile, path) if action == "calibration.apply.plan" else
+ calibration.review_rollback(profile, path))
+ result = {"ok": True, "plan": review, "path": str(path),
+ "profile_revision": revision, "source_sha256": digest,
+ "report_sha256": report["body_sha256"]}
+ elif action in ("calibration.apply", "calibration.rollback"):
+ from strata_control import calibration
+ revision, _ = _calibration_expected_source(profile, params)
+ if _boolean(params["exclusive_ack"], "exclusive_ack") is not True:
+ raise ProfileError("calibration requires exclusive-access acknowledgement")
+ path, report = _calibration_report(profile, params["path"], "calibration report path")
+ expected_report = _optional_revision(params["if_report_sha256"], "if_report_sha256")
+ if expected_report is None or report["body_sha256"] != expected_report:
+ raise ProfileError("calibration report changed after review; review again", 6)
+ kind = "engine.calibrate.apply" if action == "calibration.apply" else "engine.calibrate.rollback"
+ operation_id, outcome = journal.run_direct(profile, kind, revision,
+ {"report_path": str(path), "exclusive_ack": True},
+ lambda: {"ok": True, ("application" if action == "calibration.apply" else "rollback"):
+ calibration.apply_result(profile, path, exclusive_ack=True,
+ expected_report_sha256=expected_report) if action == "calibration.apply" else
+ calibration.rollback_result(profile, path, exclusive_ack=True,
+ expected_report_sha256=expected_report)})
+ result = {"ok": True, "operation_id": operation_id,
+ "application" if action == "calibration.apply" else "rollback":
+ outcome["application" if action == "calibration.apply" else "rollback"]}
+ elif action == "components.inspect":
+ live = _boolean(params["live"], "live")
+ source, _, _ = profiles.resolve(profile)
+ result = {"ok": True, "report": doctor.inspect(source, profile_id=profile, live=live)}
+ elif action == "models.installed":
+ profiles.load(profile)
+ result = {"ok": True, "inventory": models.list_installed()}
+ elif action == "models.inspect":
+ profiles.load(profile)
+ result = {"ok": True, "inspection": models.inspect(params["model_id"])}
+ elif action == "models.import.plan":
+ profiles.load(profile)
+ source = params["path"]
+ if not isinstance(source, str) or len(source) > 1024 or not Path(source).is_absolute() or \
+ any(ord(char) < 32 or ord(char) == 127 for char in source):
+ raise ProfileError("model import path must be an absolute path under 1024 characters")
+ result = {"ok": True, "plan": models.plan_import(source)}
+ elif action == "profile.inspect":
+ saved, revision = profiles.load(profile)
+ plan, _ = _profile_change_plan(profile, saved["overrides"], saved["source_config"])
+ if plan["revision"] != revision or plan["overrides_before"] != saved["overrides"] or \
+ plan["source_config_before"] != saved["source_config"]:
+ raise ProfileError("profile changed during inspection; reload it", 6)
+ result = {"ok": True, "profile": saved, "revision": revision,
+ "source_sha256": plan["source_sha256"],
+ "effective": plan["effective"], "origin": plan["origin"]}
+ elif action == "profile.change.plan":
+ expected_revision = _profile_revision(params["if_revision"])
+ if expected_revision is None:
+ raise ProfileError("profile preview needs its loaded revision")
+ plan, _ = _profile_change_plan(profile, params["overrides"], params["source_config"])
+ if plan["revision"] != expected_revision:
+ raise ProfileError("profile changed since it was loaded; reload before review", 6)
+ result = {"ok": True, "plan": plan}
+ elif action == "profile.change":
+ expected_revision = _profile_revision(params["if_revision"])
+ expected_source = _optional_revision(params["if_source_sha256"], "if_source_sha256")
+ if expected_revision is None or expected_source is None:
+ raise ProfileError("profile save needs its reviewed revision and source digest")
+ plan, proposed = _profile_change_plan(profile, params["overrides"], params["source_config"])
+ if plan["revision"] != expected_revision or plan["source_sha256"] != expected_source:
+ raise ProfileError("profile or source config changed after review; review again", 6)
+ saved, revision = profiles.save(profile, proposed, expected_revision=expected_revision,
+ expected_source_sha256=expected_source)
+ result = {"ok": True, "profile": saved, "previous_revision": expected_revision,
+ "revision": revision, "source_sha256": expected_source,
+ "saved": plan["would_save"], "running_unchanged": True}
+ elif action == "runtime.start.plan":
+ result = runtime_action("start", profile, plan=True,
+ shutdown_timeout=params["shutdown_timeout_s"])
+ elif action == "runtime.start":
+ if params["if_profile_revision"] is None or params["if_source_sha256"] is None:
+ raise ProfileError("Desktop start needs the profile revision and source digest from its plan")
+ result = runtime_action("start", profile, wait=params["wait_s"],
+ shutdown_timeout=params["shutdown_timeout_s"],
+ if_profile_revision=params["if_profile_revision"],
+ if_source_sha256=params["if_source_sha256"])
+ elif action == "runtime.status":
+ result = runtime_action("status", profile)
+ elif action == "runtime.verify.plan":
+ result = runtime_action("verify", profile, plan=True, load=params["load"])
+ elif action == "runtime.verify":
+ if params["if_owner_id"] is None or params["if_instance_id"] is None:
+ raise ProfileError("Desktop verify needs the owner and instance IDs from its plan")
+ result = runtime_action("verify", profile, wait=params["wait_s"], load=params["load"],
+ if_owner_id=params["if_owner_id"],
+ if_instance_id=params["if_instance_id"])
+ elif action == "runtime.stop.plan":
+ result = runtime_action("stop", profile, plan=True)
+ elif action == "runtime.stop":
+ if params["if_owner_id"] is None:
+ raise ProfileError("Desktop stop needs the owner ID from its plan")
+ result = runtime_action("stop", profile, wait=params["wait_s"],
+ if_owner_id=params["if_owner_id"],
+ if_instance_id=params["if_instance_id"])
+ elif action == "runtime.restart.plan":
+ result = runtime_action("restart", profile, plan=True,
+ allow_source_switch=params["allow_source_switch"],
+ allow_source_migration=params["allow_source_migration"])
+ else:
+ if any(params[key] is None for key in ("if_profile_revision", "if_source_sha256",
+ "if_owner_id", "if_instance_id")):
+ raise ProfileError("Desktop restart needs profile, source, owner and instance IDs from its plan")
+ result = runtime_action("restart", profile, wait=params["wait_s"],
+ startup_wait=params["startup_wait_s"],
+ if_profile_revision=params["if_profile_revision"],
+ if_owner_id=params["if_owner_id"],
+ if_instance_id=params["if_instance_id"],
+ allow_source_switch=params["allow_source_switch"],
+ allow_source_migration=params["allow_source_migration"],
+ if_source_sha256=params["if_source_sha256"])
+ return {"schema_version": 1, **result}
+
+
+def _unique_pairs(pairs: list[tuple[str, Any]]) -> dict:
+ result = {}
+ for key, value in pairs:
+ if key in result:
+ raise ProfileError("management request has a duplicate field")
+ result[key] = value
+ return result
+
+
+def _reject_constant(_: str) -> None:
+ raise ProfileError("management request has a nonfinite number")
+
+
+def main() -> int:
+ """Handle one owner-local JSON request on stdin and one JSON response on stdout."""
+ try:
+ payload = sys.stdin.buffer.read(MAX_REQUEST_BYTES + 1)
+ if not payload or len(payload) > MAX_REQUEST_BYTES:
+ raise ProfileError("management request must be 1..65536 bytes")
+ request = json.loads(payload.decode("utf-8"), object_pairs_hook=_unique_pairs,
+ parse_constant=_reject_constant)
+ with contextlib.redirect_stdout(sys.stderr):
+ response = dispatch(request)
+ code = 0 if response.get("ok") else response.get("exit_code", 6)
+ if code != 0 and "exit_code" not in response:
+ response = {**response, "exit_code": code}
+ except (ProfileError, ValueError, UnicodeError) as exc:
+ code = getattr(exc, "exit_code", 2)
+ response = {"schema_version": 1, "ok": False, "error": str(exc), "exit_code": code}
+ except OSError as exc:
+ code = 6
+ response = {"schema_version": 1, "ok": False,
+ "error": f"local operation failed ({type(exc).__name__})", "exit_code": code}
+ except KeyboardInterrupt:
+ code = 130
+ response = {"schema_version": 1, "ok": False,
+ "error": "operation interrupted; completion must be checked in the journal",
+ "exit_code": code}
+ print(json.dumps(response, ensure_ascii=False, allow_nan=False))
+ return code
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/strata_control/models.py b/strata_control/models.py
new file mode 100644
index 000000000..c2dcb660a
--- /dev/null
+++ b/strata_control/models.py
@@ -0,0 +1,300 @@
+"""Bounded, read-only discovery of setup-written local model run configs.
+
+The setup installer writes strata-*.json beside setup.py. A configured model is
+not automatically a compatible or loadable model: component presence and native
+engine compatibility are reported separately.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import re
+import stat
+from pathlib import Path
+
+from strata_control.doctor import inspect as inspect_components
+from strata_control.gguf_preflight import inspect_metadata
+from strata_control.profiles import ProfileError
+
+
+ROOT = Path(__file__).resolve().parents[1]
+MODEL_ID = re.compile(r"[a-z0-9][a-z0-9_-]{0,127}\Z")
+MAX_CONFIG_BYTES = 1024 * 1024
+MAX_CONFIGS = 128
+MAX_IMPORT_SHARDS = 128
+SHARD = re.compile(r"(.+)-(\d{5})-of-(\d{5})\.gguf\Z", re.I)
+SUPPORTED_SELECTIONS = frozenset({"qwen/Q2_0", "qwen/IQ2_XS", "qwen/IQ3_XXS", "qwen/IQ3_S",
+ "swift/IQ2_XS", "swift/IQ3_XXS", "coder/IQ1_M",
+ "unsloth/UD-IQ4_XS", "unsloth/UD-Q4_K_XL"})
+
+
+def install_dir(override: str | None = None) -> Path:
+ raw = override or os.environ.get("STRATA_INSTALL_DIR")
+ if raw is None:
+ return ROOT
+ path = Path(raw).expanduser()
+ if not path.is_absolute() or not path.is_dir():
+ raise ProfileError("install directory must be an existing absolute directory", 5)
+ return path.resolve()
+
+
+def _model_id(path: Path) -> str | None:
+ if not path.name.startswith("strata-") or not path.name.endswith(".json") or \
+ path.name.endswith(".shared-settings.json"):
+ return None
+ value = path.name[len("strata-"):-len(".json")]
+ return value if MODEL_ID.fullmatch(value) else None
+
+
+def _paths(directory: Path) -> list[tuple[str, Path]]:
+ try:
+ entries = [(name, path) for path in directory.iterdir() if (name := _model_id(path)) is not None]
+ except OSError:
+ raise ProfileError("cannot read installed model directory", 5) from None
+ if len(entries) > MAX_CONFIGS:
+ raise ProfileError("more than 128 model configs need inspection", 5)
+ return sorted(entries, key=lambda item: item[0])
+
+
+def _read(path: Path) -> tuple[bytes, dict]:
+ flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
+ try:
+ if stat.S_ISLNK(path.lstat().st_mode):
+ raise ProfileError("run config must not be a symlink", 5)
+ descriptor = os.open(path, flags)
+ with os.fdopen(descriptor, "rb") as stream:
+ details = os.fstat(stream.fileno())
+ if not stat.S_ISREG(details.st_mode) or details.st_size > MAX_CONFIG_BYTES:
+ raise ProfileError("run config must be a regular file under 1 MiB", 5)
+ raw = stream.read(MAX_CONFIG_BYTES + 1)
+ if len(raw) > MAX_CONFIG_BYTES:
+ raise ProfileError("run config exceeds 1 MiB", 5)
+ value = json.loads(raw.decode("utf-8-sig"))
+ except (OSError, UnicodeError, ValueError) as exc:
+ if isinstance(exc, ProfileError):
+ raise
+ raise ProfileError("run config is unreadable or invalid JSON", 5) from None
+ if not isinstance(value, dict) or not isinstance(value.get("exe"), str) or not value["exe"] or \
+ not isinstance(value.get("tokenizer"), str) or not value["tokenizer"] or \
+ not isinstance(value.get("args"), list) or \
+ not all(isinstance(arg, str) for arg in value["args"]):
+ raise ProfileError("run config lacks engine, tokenizer or string arguments", 5)
+ return raw, value
+
+
+def _short(value: object) -> str | None:
+ if not isinstance(value, str):
+ return None
+ return "".join(char if char.isprintable() and char not in "\x1b\x7f" else " " for char in value)[:120]
+
+
+def _arg(args: list[str], flag: str) -> str | None:
+ try:
+ index = args.index(flag)
+ return args[index + 1] if index + 1 < len(args) else None
+ except ValueError:
+ return None
+
+
+def _summary(model_id: str, path: Path, raw: bytes, cfg: dict, report: dict) -> dict:
+ context = _arg(cfg["args"], "--max-context")
+ context_tokens = int(context) if isinstance(context, str) and 1 <= len(context) <= 8 and \
+ context.isascii() and context.isdecimal() and 1 <= int(context) <= 16_777_216 else None
+ backend = cfg.get("backend")
+ return {"id": model_id, "name": _short(cfg.get("model_name")) or model_id,
+ "source_config": str(path), "source_sha256": hashlib.sha256(raw).hexdigest(),
+ "backend": _short(backend) if backend is not None else None,
+ "context_tokens": context_tokens,
+ "component_status": "present" if report["ok"] else "missing_or_invalid",
+ "issue_codes": [item.get("code") for item in report["issues"]][:32],
+ "execution_compatibility": "unverified"}
+
+
+def _inspect_one(model_id: str, path: Path) -> tuple[dict, dict]:
+ raw, cfg = _read(path)
+ try:
+ report = inspect_components(path)
+ after, _ = _read(path)
+ except (OSError, ValueError):
+ raise ProfileError("run config changed or became invalid during inspection", 6) from None
+ if after != raw:
+ raise ProfileError("run config changed during inspection; retry", 6)
+ return _summary(model_id, path, raw, cfg, report), report
+
+
+def list_installed(override: str | None = None) -> dict:
+ directory = install_dir(override)
+ models = []
+ for model_id, path in _paths(directory):
+ try:
+ summary, _ = _inspect_one(model_id, path)
+ except ProfileError as exc:
+ summary = {"id": model_id, "source_config": str(path), "component_status": "invalid",
+ "error": str(exc), "execution_compatibility": "unverified"}
+ models.append(summary)
+ return {"scope": "local_run_configs", "install_dir": str(directory), "models": models,
+ "model_count": len(models), "discovery_limit": MAX_CONFIGS}
+
+
+def inspect(model_id: str, override: str | None = None) -> dict:
+ if not isinstance(model_id, str) or not MODEL_ID.fullmatch(model_id):
+ raise ProfileError("model ID must be a setup config name without a path")
+ directory = install_dir(override)
+ choices = dict(_paths(directory))
+ path = choices.get(model_id)
+ if path is None:
+ raise ProfileError(f"model {model_id!r} is not configured in this installation", 5)
+ summary, report = _inspect_one(model_id, path)
+ return {"scope": "local_run_config", "install_dir": str(directory), "model": summary,
+ "components": report}
+
+
+def _gguf_header(path: Path) -> dict:
+ try:
+ if stat.S_ISLNK(path.lstat().st_mode):
+ raise ProfileError("GGUF shard is a symlink", 5)
+ descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
+ with os.fdopen(descriptor, "rb") as stream:
+ details = os.fstat(stream.fileno())
+ if not stat.S_ISREG(details.st_mode) or details.st_size < 8:
+ raise ProfileError("GGUF shard is not a nonempty regular file", 5)
+ header = stream.read(8)
+ except OSError:
+ raise ProfileError("GGUF shard is unreadable", 5) from None
+ if header[:4] != b"GGUF":
+ raise ProfileError("file does not begin with a GGUF header", 5)
+ version = int.from_bytes(header[4:8], "little")
+ if version not in (2, 3):
+ raise ProfileError("GGUF header version is not recognized", 5)
+ return {"name": path.name, "path": str(path), "bytes": details.st_size,
+ "gguf_version": version}
+
+
+def _candidate_selection(shards: list[Path]) -> dict | None:
+ fingerprint_file = ROOT / "data" / "gguf_fingerprints.json"
+ try:
+ if fingerprint_file.stat().st_size > 128 * 1024:
+ raise ProfileError("model fingerprint catalog exceeds 128 KiB", 5)
+ catalog = json.loads(fingerprint_file.read_text(encoding="utf-8"))
+ except (OSError, UnicodeError, ValueError):
+ raise ProfileError("model fingerprint catalog is unavailable", 5) from None
+ names = {item.name for item in shards}
+ for selection in sorted(SUPPORTED_SELECTIONS):
+ row = catalog.get(selection) if isinstance(catalog, dict) else None
+ expected = row.get("files") if isinstance(row, dict) else None
+ if isinstance(expected, list) and expected and names == {Path(name).name for name in expected}:
+ family, model = selection.split("/", 1)
+ expected_experts = row.get("expert_bytes")
+ return {"family": family, "model": model, "basis": "known_shard_names_only",
+ "expected_expert_types": sorted(expected_experts) if isinstance(expected_experts, dict) else [],
+ "expected_tensor_count": row.get("tensors") if type(row.get("tensors")) is int else None,
+ "setup_args_hint": ["--family", family, "--model", model,
+ "--gguf-dir", str(shards[0].parent)]}
+ return None
+
+
+def plan_import(raw_path: str) -> dict:
+ """Inspect a local candidate without copying, parsing tensors or adopting it."""
+ path = Path(raw_path).expanduser()
+ if not path.is_absolute():
+ raise ProfileError("model import path must be absolute")
+ try:
+ details = path.lstat()
+ except OSError:
+ raise ProfileError("model import path does not exist", 5) from None
+ if stat.S_ISLNK(details.st_mode):
+ raise ProfileError("model import path must not be a symlink", 5)
+ if stat.S_ISDIR(details.st_mode):
+ try:
+ shards = []
+ ignored_auxiliary = []
+ for child in path.iterdir():
+ if child.name.lower().endswith(".gguf"):
+ if child.name.lower().startswith("mmproj"):
+ ignored_auxiliary.append(child.name)
+ continue
+ shards.append(child)
+ if len(shards) > MAX_IMPORT_SHARDS:
+ raise ProfileError("more than 128 GGUF candidates in the directory", 5)
+ except OSError:
+ raise ProfileError("cannot inspect GGUF directory", 5) from None
+ elif stat.S_ISREG(details.st_mode) and path.name.lower().endswith(".gguf"):
+ ignored_auxiliary = []
+ match = SHARD.fullmatch(path.name)
+ if match:
+ total = int(match.group(3))
+ if not 1 <= total <= MAX_IMPORT_SHARDS:
+ raise ProfileError("GGUF shard count must be in 1..128", 5)
+ shards = [path.with_name(f"{match.group(1)}-{i:05d}-of-{total:05d}.gguf")
+ for i in range(1, total + 1)]
+ else:
+ shards = [path]
+ else:
+ raise ProfileError("model import needs a GGUF file or directory", 5)
+ if not shards:
+ raise ProfileError("no GGUF files found at the model import path", 5)
+ shards.sort(key=lambda item: item.name)
+ groups = {}
+ for item in shards:
+ match = SHARD.fullmatch(item.name)
+ if match:
+ key = (match.group(1), int(match.group(3)))
+ groups.setdefault(key, set()).add(int(match.group(2)))
+ else:
+ groups.setdefault((item.name, 1), set()).add(1)
+ issues = []
+ if len(groups) != 1:
+ issues.append("multiple_model_groups")
+ if len(groups) == 1:
+ (_, total), indices = next(iter(groups.items()))
+ if total > MAX_IMPORT_SHARDS or indices != set(range(1, total + 1)):
+ issues.append("incomplete_or_invalid_shard_set")
+ files = []
+ for item in shards:
+ try:
+ files.append(_gguf_header(item))
+ except ProfileError as exc:
+ issues.append(f"{item.name}: {exc}")
+ metadata = None
+ observed_experts: set[str] = set()
+ observed_tensor_count = 0
+ if files and not issues:
+ for item in shards:
+ try:
+ inspected = inspect_metadata(item)
+ except ProfileError as exc:
+ issues.append(f"{item.name}: {exc}")
+ continue
+ if metadata is None:
+ metadata = inspected
+ observed_experts.update(inspected["expert_tensor_types"])
+ observed_tensor_count += inspected["tensor_count_scanned"]
+ if inspected["architecture"] is not None and inspected["architecture"] != "qwen4exp":
+ issues.append(f"{item.name}: unsupported_architecture")
+ if metadata is not None:
+ if metadata["architecture"] != "qwen4exp":
+ issues.append("unsupported_or_missing_architecture")
+ if metadata["tokenizer_model"] != "gpt2" or not metadata["tokenizer_tokens_present"] or \
+ not metadata["tokenizer_merges_present"]:
+ issues.append("unsupported_or_incomplete_tokenizer_metadata")
+ candidate = _candidate_selection(shards)
+ if candidate is None:
+ issues.append("unrecognized_or_unsupported_model_variant")
+ elif metadata is not None:
+ expected = set(candidate["expected_expert_types"])
+ if not observed_experts or observed_experts - expected:
+ issues.append("missing_or_unexpected_expert_quantization")
+ return {"source": str(path), "scope": "local_gguf_candidate", "files": files,
+ "file_count": len(files), "total_bytes": sum(item["bytes"] for item in files),
+ "metadata": metadata, "candidate_selection": candidate,
+ "observed_expert_types": sorted(observed_experts),
+ "observed_tensor_count": observed_tensor_count,
+ "ignored_auxiliary_files": sorted(ignored_auxiliary),
+ "file_set_status": "plausible" if not issues else "invalid_or_incomplete",
+ "issues": issues, "adoption_status": "requires_architecture_quantization_tokenizer_and_engine_checks",
+ "execution_compatibility": "unverified", "would_write": False,
+ "notes": ["A known shard name is only a selection hint; it does not prove provenance or file integrity",
+ "Tensor directory, model-pack, engine version and hardware checks remain before adoption",
+ "No model is adopted or copied by this preview"]}
diff --git a/strata_control/offline.py b/strata_control/offline.py
new file mode 100644
index 000000000..70dba4c8d
--- /dev/null
+++ b/strata_control/offline.py
@@ -0,0 +1,191 @@
+"""Offline policy: what "no download" means, and for whom (checklist U08).
+
+The checklist asks for two claims that are easy to conflate, so this module keeps them apart:
+
+* **runtime-only no-download** — the server, while serving, fetches nothing. The engine runs from
+ local files; no model, library or asset is fetched mid-request. This can be true while the machine
+ has a network and while other parts of the product do download.
+* **strict offline** — nothing in the process tree reaches the network at all, including children,
+ tool subprocesses and the agent runtime. This must hold even though a tool or a model file might
+ want to fetch something.
+
+They are tested separately because a passing runtime-only test says nothing about the second: the
+first is about the server's own code paths, and the second is about every process it can start.
+
+How each is enforced:
+
+**Environment, for children.** Every child the server starts is given variables that the common
+runtimes honour — Hugging Face, Transformers, pip, and the proxy variables that make an accidental
+HTTP call fail fast rather than hang. This is the mechanism that reaches code we do not control.
+
+**A guard, for our own fetches.** `check_url` is the single place the product decides whether a URL
+may be fetched, so "offline" is one predicate rather than a scattered set of `if offline` checks. A
+test asserts the server's image path calls it, because a guard that is not wired in is decoration.
+
+**A preflight, for the profile.** A profile that names MCP servers, a `before_load` command or remote
+image sources cannot be strict-offline, and saying so before the server starts is more useful than
+failing on the first request.
+
+**What this cannot do.** It cannot stop a child that ignores the environment and opens a socket
+directly, because that would need a sandbox this product does not have on all three platforms.
+`limits()` states that plainly, and the qualification kit asks for the network-isolated run that
+would settle it. Recording the limit is the honest option; claiming enforcement would not be.
+"""
+
+from __future__ import annotations
+
+import os
+import shutil
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Mapping
+from urllib.parse import urlparse
+
+#: Environment for children. The first group is what the Python ML stack reads; the second makes an
+#: accidental HTTP call fail immediately instead of hanging on a timeout; the third tells tools that
+#: ask that they are offline.
+OFFLINE_ENV: dict[str, str] = {
+ "HF_HUB_OFFLINE": "1",
+ "TRANSFORMERS_OFFLINE": "1",
+ "HF_HUB_DISABLE_TELEMETRY": "1",
+ "DO_NOT_TRACK": "1",
+ "PIP_NO_INDEX": "1",
+ "PIP_DISABLE_PIP_VERSION_CHECK": "1",
+ "NO_PROXY": "*",
+ "no_proxy": "*",
+ "HTTP_PROXY": "",
+ "HTTPS_PROXY": "",
+ "http_proxy": "",
+ "https_proxy": "",
+ "STRATA_OFFLINE": "1",
+}
+
+#: Schemes that are local by construction and therefore always allowed.
+LOCAL_SCHEMES = ("file", "data", "blob")
+
+#: Hosts that mean "this machine" and never leave it.
+LOCAL_HOSTS = ("localhost", "127.0.0.1", "::1", "[::1]", "0.0.0.0")
+
+
+@dataclass(frozen=True)
+class Decision:
+ """Whether a URL may be fetched, and the reason either way."""
+
+ allowed: bool
+ reason: str
+
+ def __bool__(self) -> bool:
+ return self.allowed
+
+
+class OfflineViolation(RuntimeError):
+ """A fetch was attempted under a policy that forbids it."""
+
+ def __init__(self, url: str, reason: str) -> None:
+ super().__init__(f"offline policy forbids fetching {url!r}: {reason}")
+ self.url = url
+ self.reason = reason
+
+
+def check_url(url: str, *, offline: bool) -> Decision:
+ """May this URL be fetched?
+
+ A local scheme or a loopback host is allowed even under strict offline: talking to this machine
+ is not a download, and forbidding it would break the local API the product is built on.
+ """
+ if not offline:
+ return Decision(True, "not offline")
+ if not url:
+ return Decision(False, "no URL")
+ parsed = urlparse(str(url))
+ scheme = (parsed.scheme or "").lower()
+ if scheme in LOCAL_SCHEMES:
+ return Decision(True, f"the {scheme} scheme is local")
+ if scheme in ("", "http", "https"):
+ host = (parsed.hostname or "").lower()
+ if scheme == "" and not host:
+ # A bare path is a local file, which is how a profile usually names an image.
+ return Decision(True, "a local path, not a URL")
+ if host in LOCAL_HOSTS:
+ return Decision(True, f"{host} is this machine")
+ return Decision(False, f"{scheme or 'http'} to {host or 'an unnamed host'} would leave this machine")
+ return Decision(False, f"the {scheme} scheme is not local")
+
+
+def require_url(url: str, *, offline: bool) -> None:
+ """`check_url`, as an exception. Used where a refusal must stop the operation."""
+ decision = check_url(url, offline=offline)
+ if not decision.allowed:
+ raise OfflineViolation(url, decision.reason)
+
+
+def child_environment(*, offline: bool, base: Mapping[str, str] | None = None) -> dict[str, str]:
+ """The environment a child process gets.
+
+ Under strict offline the variables are *set*, not merely left alone: a child that would otherwise
+ read the parent's proxy settings must be told not to use them.
+ """
+ env = dict(base if base is not None else os.environ)
+ if offline:
+ env.update(OFFLINE_ENV)
+ else:
+ # Not offline: remove the markers so a previous run's policy cannot leak into this one, which
+ # would make a later server mysteriously refuse to fetch.
+ for key in OFFLINE_ENV:
+ env.pop(key, None)
+ return env
+
+
+def profile_requirements(cfg: Mapping[str, Any]) -> list[str]:
+ """The parts of a profile that need the network, named so a refusal can explain itself."""
+ needs: list[str] = []
+ servers = cfg.get("mcp_servers") or cfg.get("mcpServers")
+ if servers:
+ count = len(servers) if hasattr(servers, "__len__") else 1
+ needs.append(f"the profile declares {count} MCP server(s), which are started as subprocesses "
+ "and may fetch tools")
+ for key in ("before_load", "beforeLoad"):
+ if cfg.get(key):
+ needs.append(f"the profile declares a {key} command, which runs before the model loads")
+ for key in ("images", "vision"):
+ section = cfg.get(key)
+ if isinstance(section, dict):
+ for field in ("remote_sources", "allowed_hosts", "url"):
+ if section.get(field):
+ needs.append(f"the profile's {key}.{field} permits network sources")
+ return needs
+
+
+def ensure_strictly_offline(cfg: Mapping[str, Any]) -> list[str]:
+ """Why this profile cannot be strict-offline. Empty means it can.
+
+ Refusing before the server starts is more useful than failing on the first request, and it keeps
+ the promise precise: a profile that permits a network source is not offline, whatever the flag
+ says.
+ """
+ return profile_requirements(cfg)
+
+
+def limits() -> list[str]:
+ """What this policy does not enforce. Stated so it is not over-read as a sandbox."""
+ return [
+ "a child that ignores the environment and opens a socket directly is not stopped; that needs "
+ "an OS sandbox, which this product does not have on all three platforms",
+ "a library already loaded with its own network stack is not intercepted",
+ "DNS resolution is not blocked, so a lookup may still occur before a connection fails",
+ ]
+
+
+def report(*, offline: bool, cfg: Mapping[str, Any] | None = None) -> dict[str, Any]:
+ """What the policy is doing, for the logs and the evidence record."""
+ requirements = profile_requirements(cfg or {})
+ return {
+ "strict_offline": bool(offline),
+ "runtime_only_no_download": True,
+ "child_environment": sorted(OFFLINE_ENV) if offline else [],
+ "profile_needs_network": requirements,
+ "enforced": (["our own fetches go through check_url",
+ "every child is given the offline environment"] if offline else
+ ["serving itself fetches nothing; downloads elsewhere are permitted"]),
+ "not_enforced": limits() if offline else [],
+ }
diff --git a/strata_control/owner_transport.py b/strata_control/owner_transport.py
new file mode 100644
index 000000000..b32ed5c11
--- /dev/null
+++ b/strata_control/owner_transport.py
@@ -0,0 +1,177 @@
+"""Owner transport: the private channel between a Strata Control owner and its clients.
+
+There is exactly one owner per installation. Clients attach to it over a channel that must be
+reachable only by the same user, and the design differs per platform for a concrete reason:
+
+**POSIX (macOS, Linux)** uses an ``AF_UNIX`` stream socket inside the owner's private runtime
+directory (mode ``0700``), with the socket itself at ``0600``. Access control is the filesystem's:
+another user cannot open the path. This is the implementation the terminal layer already used and it
+is preserved unchanged here.
+
+**Windows** cannot create a named pipe from the Python standard library — there is no
+``socket.AF_UNIX`` that carries a security descriptor, and ``CreateNamedPipe`` is not exposed. The
+transport is therefore a **loopback TCP listener owned by the owner process**, protected by three
+things rather than by a pipe ACL:
+
+1. it binds ``127.0.0.1`` only, never ``0.0.0.0``, and it never enables a wildcard or IPv6-any
+ listener that would also accept remote traffic;
+2. every request carries the owner's 256-bit control token, compared in constant time, which the
+ client reads from a state file in the owner's private directory (``0700``, owner-only);
+3. a connection that fails the token check is dropped immediately and counts toward a small
+ per-owner failure budget, so the port cannot be used as a token oracle.
+
+A local TCP port is reachable by other users on the same machine *if* they can guess it and *if*
+they have the token. That is a weaker guarantee than a pipe ACL, and it is recorded as such: on
+Windows the security of the owner channel rests on the token, exactly as it does for a Jupyter
+server or any other loopback-authenticated service. A native ``CreateNamedPipe`` implementation with
+``SDDL`` restricting the pipe to the owner is a scoped improvement, not a prerequisite, and
+``docs/work/IMPLEMENTATION_STATUS.md`` tracks it as the honest difference between the platforms.
+
+This module is deliberately small: it provides the two operations the runtime needs (listen,
+connect), plus the addressing helpers. It owns no policy, no identity and no lifecycle.
+"""
+
+from __future__ import annotations
+
+import errno
+import os
+import socket
+import stat
+import sys
+from pathlib import Path
+
+#: The largest single message either side will read. Both the state file and the socket protocol
+#: assume it, so it lives here with the transport rather than with either caller.
+MAX_MESSAGE = 64 * 1024
+
+WINDOWS = sys.platform == "win32"
+
+
+class TransportError(OSError):
+ """The channel could not be established, with the reason the caller should report."""
+
+
+def address_for(runtime_dir: Path, name: str) -> str:
+ """The address a client connects to, stored in the owner's state file.
+
+ On POSIX this is the socket path. The digest keeps it inside the ``AF_UNIX`` length limit
+ (``sun_path`` is about 104 bytes on macOS and 108 on Linux), which a long home directory would
+ otherwise exceed; when even the private-directory form is too long the address falls back to a
+ short ``/tmp`` path that only this user can traverse.
+ """
+ if WINDOWS:
+ # The port is chosen by the listener and written into the state file; the address here is
+ # only a placeholder that the caller always overwrites with the real one.
+ return f"tcp:127.0.0.1:0"
+ import hashlib
+ digest = hashlib.sha256(f"{runtime_dir}\0{name}".encode()).hexdigest()[:16]
+ candidate = runtime_dir / f"{digest}.sock"
+ if len(str(candidate).encode()) <= 90:
+ return str(candidate)
+ return f"/tmp/strata-{os.getuid()}-{digest}.sock"
+
+
+class Listener:
+ """An accepting endpoint for the owner's private channel.
+
+ Use as a context manager. ``accept()`` returns a connected socket, or ``None`` on timeout so the
+ owner can service its other work between polls.
+ """
+
+ def __init__(self, address: str, *, timeout: float = 1.0) -> None:
+ self.requested = address
+ self.address = address
+ self._sock: socket.socket | None = None
+ self._timeout = timeout
+ self._bound = False
+
+ def bind(self) -> str:
+ if WINDOWS:
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ # Loopback only, and no SO_REUSEADDR: a second owner must fail to bind rather than
+ # silently share the port with the first.
+ sock.bind(("127.0.0.1", 0))
+ self.address = f"tcp:127.0.0.1:{sock.getsockname()[1]}"
+ else:
+ path = Path(self.requested)
+ if path.exists():
+ # A leftover socket from a crashed owner. Only unlink when nothing is listening,
+ # which is exactly what the caller's stale check established before calling bind.
+ path.unlink()
+ sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
+ sock.bind(str(path))
+ os.chmod(path, 0o600)
+ sock.listen(5)
+ sock.settimeout(self._timeout)
+ self._sock = sock
+ self._bound = True
+ return self.address
+
+ def accept(self) -> socket.socket | None:
+ if self._sock is None:
+ raise TransportError("the listener is not bound")
+ try:
+ conn, _ = self._sock.accept()
+ except socket.timeout:
+ return None
+ except OSError as e:
+ if e.errno in (errno.EINTR, errno.EAGAIN):
+ return None
+ raise
+ return conn
+
+ def close(self) -> None:
+ if self._sock is not None:
+ try:
+ self._sock.close()
+ finally:
+ self._sock = None
+ if not WINDOWS and self._bound:
+ # Remove the path so a later owner can bind it; ignore a racing removal.
+ try:
+ Path(self.requested).unlink()
+ except OSError:
+ pass
+ self._bound = False
+
+ def __enter__(self) -> "Listener":
+ self.bind()
+ return self
+
+ def __exit__(self, *exc: object) -> None:
+ self.close()
+
+
+def connect(address: str, *, timeout: float = 5.0) -> socket.socket:
+ """Connect to an owner's private channel."""
+ sock = socket.socket(socket.AF_INET if WINDOWS else socket.AF_UNIX, socket.SOCK_STREAM)
+ sock.settimeout(timeout)
+ try:
+ if WINDOWS:
+ _, host, port = address.split(":", 2)
+ sock.connect((host, int(port)))
+ else:
+ sock.connect(address)
+ except OSError:
+ sock.close()
+ raise
+ return sock
+
+
+def check_state_file(path: Path) -> None:
+ """Validate that a state file is one this user may trust.
+
+ Refuses anything that is not a regular file, is not owned by this user, or is group/world
+ accessible. This is what stops another account from pointing a client at its own listener.
+ """
+ st = path.lstat()
+ if stat.S_ISLNK(st.st_mode):
+ raise TransportError("the runtime state file is a symlink")
+ if not stat.S_ISREG(st.st_mode):
+ raise TransportError("the runtime state file is not a regular file")
+ if st.st_size > 16 * 1024:
+ raise TransportError("the runtime state file is implausibly large")
+ if hasattr(os, "getuid") and st.st_uid != os.getuid():
+ raise TransportError("the runtime state file is owned by another user")
+ if st.st_mode & 0o077:
+ raise TransportError("the runtime state file is readable by other users")
diff --git a/strata_control/profiles.py b/strata_control/profiles.py
new file mode 100644
index 000000000..9c633bd92
--- /dev/null
+++ b/strata_control/profiles.py
@@ -0,0 +1,385 @@
+"""Versioned, owner-editable serving profiles separate from setup's run config.
+
+The source JSON belongs to setup.py; this small layer keeps operator overrides in
+the user's configuration directory so an installer update cannot silently erase
+them. It deliberately does not start processes or contact a network service.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import math
+import os
+import re
+import shlex
+import stat
+import subprocess
+import tempfile
+from contextlib import contextmanager
+from pathlib import Path
+
+
+PROFILE_ID = re.compile(r"[a-z][a-z0-9_-]{0,63}\Z")
+OVERRIDE_KEYS = frozenset({"host", "port", "parallel", "batch_groups", "max_queue", "queue_timeout", "offline",
+ "batch_telemetry"})
+
+
+class ProfileError(ValueError):
+ """A profile is missing, invalid or changed while it was being edited."""
+
+ def __init__(self, message: str, exit_code: int = 2):
+ super().__init__(message)
+ self.exit_code = exit_code
+
+
+def profile_dir() -> Path:
+ explicit = os.environ.get("STRATA_PROFILE_DIR")
+ if explicit:
+ return Path(explicit).expanduser()
+ if os.name == "nt":
+ base = os.environ.get("APPDATA")
+ return (Path(base) if base else Path.home() / "AppData" / "Roaming") / "Strata" / "profiles"
+ return Path(os.environ.get("XDG_CONFIG_HOME", str(Path.home() / ".config"))) / "strata" / "profiles"
+
+
+def _name(name: str) -> str:
+ if not PROFILE_ID.fullmatch(name):
+ raise ProfileError("profile name must start with a lowercase letter and use only a-z, 0-9, _ or -")
+ return name
+
+
+def _path(name: str) -> Path:
+ return profile_dir() / f"{_name(name)}.json"
+
+
+def _bytes(profile: dict) -> bytes:
+ return (json.dumps(profile, indent=2, ensure_ascii=False, sort_keys=True) + "\n").encode("utf-8")
+
+
+def _revision(data: bytes) -> str:
+ return hashlib.sha256(data).hexdigest()[:16]
+
+
+def parse_assignment(text: str) -> tuple[str, object]:
+ key, sep, raw = text.partition("=")
+ if not sep or key not in OVERRIDE_KEYS:
+ raise ProfileError(f"expected one of {', '.join(sorted(OVERRIDE_KEYS))} as KEY=VALUE")
+ if key in ("port", "parallel", "max_queue"):
+ try:
+ value: object = int(raw)
+ except ValueError:
+ raise ProfileError(f"{key} must be a whole number") from None
+ elif key == "queue_timeout":
+ try:
+ value = float(raw)
+ except ValueError:
+ raise ProfileError("queue_timeout must be a number of seconds") from None
+ elif key == "batch_groups":
+ if raw == "auto":
+ value = raw
+ else:
+ try:
+ value = int(raw)
+ except ValueError:
+ raise ProfileError("batch_groups must be auto or a positive whole number") from None
+ elif key in ("offline", "batch_telemetry"):
+ if raw not in ("true", "false"):
+ raise ProfileError(f"{key} must be true or false")
+ value = raw == "true"
+ else:
+ value = raw
+ validate_overrides({key: value})
+ return key, value
+
+
+def validate_overrides(overrides: object) -> dict:
+ if not isinstance(overrides, dict) or set(overrides) - OVERRIDE_KEYS:
+ raise ProfileError("overrides must contain only supported serving settings")
+ for key, value in overrides.items():
+ if key == "host" and (not isinstance(value, str) or not value or any(c.isspace() for c in value)):
+ raise ProfileError("host must be a nonempty address without whitespace")
+ if key == "port" and (type(value) is not int or not 0 <= value <= 65535):
+ raise ProfileError("port must be in 0..65535")
+ if key == "parallel" and (type(value) is not int or not 1 <= value <= 1024):
+ raise ProfileError("parallel must be in 1..1024")
+ if key == "max_queue" and (type(value) is not int or not 0 <= value <= 4096):
+ raise ProfileError("max_queue must be in 0..4096")
+ if key == "queue_timeout" and (type(value) not in (int, float) or not math.isfinite(value)
+ or not 0.1 <= value <= 600):
+ raise ProfileError("queue_timeout must be finite seconds in 0.1..600")
+ if key == "batch_groups" and value != "auto" and (type(value) is not int or not 1 <= value <= 1024):
+ raise ProfileError("batch_groups must be auto or in 1..1024")
+ if key in ("offline", "batch_telemetry") and type(value) is not bool:
+ raise ProfileError(f"{key} must be true or false")
+ return overrides
+
+
+def validate_profile(value: object, *, expected_name: str | None = None) -> dict:
+ if not isinstance(value, dict) or set(value) != {"schema_version", "id", "source_config", "overrides"}:
+ raise ProfileError("profile needs schema_version, id, source_config and overrides")
+ if type(value["schema_version"]) is not int or value["schema_version"] != 1:
+ raise ProfileError("unsupported profile schema version")
+ name = _name(value["id"] if isinstance(value["id"], str) else "")
+ if expected_name is not None and name != expected_name:
+ raise ProfileError("profile ID does not match its filename")
+ source = value["source_config"]
+ if not isinstance(source, str) or not Path(source).is_absolute():
+ raise ProfileError("source_config must be an absolute path")
+ validate_overrides(value["overrides"])
+ return value
+
+
+def read_run_config(path: Path) -> dict:
+ try:
+ cfg = json.loads(path.read_text(encoding="utf-8-sig"))
+ except (OSError, ValueError) as exc:
+ raise ProfileError(f"cannot read run config ({type(exc).__name__})", 5) from None
+ if not isinstance(cfg, dict) or not isinstance(cfg.get("args"), list) or not all(
+ isinstance(arg, str) for arg in cfg["args"]
+ ):
+ raise ProfileError("run config needs an args array of strings")
+ for key in ("exe", "tokenizer"):
+ if not isinstance(cfg.get(key), str) or not cfg[key]:
+ raise ProfileError(f"run config needs a nonempty {key} path")
+ return cfg
+
+
+def load(name: str) -> tuple[dict, str]:
+ path = _path(name)
+ try:
+ if not stat.S_ISREG(path.lstat().st_mode):
+ raise ProfileError("profile must be a regular file", 5)
+ data = path.read_bytes()
+ if len(data) > 1024 * 1024:
+ raise ProfileError("profile is larger than 1 MiB", 5)
+ value = json.loads(data.decode("utf-8-sig"))
+ except FileNotFoundError:
+ raise ProfileError(f"profile {name!r} is not saved; use strata profile create", 5) from None
+ except (OSError, ValueError, UnicodeError) as exc:
+ if isinstance(exc, ProfileError):
+ raise
+ raise ProfileError(f"cannot read profile ({type(exc).__name__})", 5) from None
+ return validate_profile(value, expected_name=name), _revision(data)
+
+
+def list_profiles() -> list[dict]:
+ directory = profile_dir()
+ if not directory.exists():
+ return []
+ result = []
+ for path in sorted(directory.glob("*.json")):
+ if not PROFILE_ID.fullmatch(path.stem):
+ continue
+ try:
+ profile, revision = load(path.stem)
+ result.append({"id": path.stem, "revision": revision, "source_config": profile["source_config"]})
+ except ProfileError as exc:
+ result.append({"id": path.stem, "error": str(exc)})
+ return result
+
+
+@contextmanager
+def _lock(name: str):
+ directory = profile_dir()
+ directory.mkdir(mode=0o700, parents=True, exist_ok=True)
+ lock = directory / f".{_name(name)}.lock"
+ with open(lock, "a+b") as stream:
+ if os.name == "nt":
+ import msvcrt
+ stream.seek(0)
+ if not stream.read(1):
+ stream.write(b"0")
+ stream.flush()
+ stream.seek(0)
+ msvcrt.locking(stream.fileno(), msvcrt.LK_LOCK, 1)
+ try:
+ yield
+ finally:
+ stream.seek(0)
+ msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1)
+ else:
+ import fcntl
+ fcntl.flock(stream.fileno(), fcntl.LOCK_EX)
+ try:
+ yield
+ finally:
+ fcntl.flock(stream.fileno(), fcntl.LOCK_UN)
+
+
+def _atomic(path: Path, data: bytes) -> None:
+ fd, temp_name = tempfile.mkstemp(prefix=f".{path.stem}-", suffix=".tmp", dir=path.parent)
+ try:
+ with os.fdopen(fd, "wb") as stream:
+ stream.write(data)
+ stream.flush()
+ os.fsync(stream.fileno())
+ os.replace(temp_name, path)
+ if os.name != "nt":
+ try:
+ parent_fd = os.open(path.parent, os.O_RDONLY)
+ try:
+ os.fsync(parent_fd)
+ finally:
+ os.close(parent_fd)
+ except OSError:
+ # Replacement already succeeded; do not report a failed save after it changed the profile.
+ pass
+ finally:
+ if os.path.exists(temp_name):
+ os.unlink(temp_name)
+
+
+def create(name: str, source_config: str) -> tuple[dict, str]:
+ name = _name(name)
+ try:
+ source = Path(source_config).expanduser().resolve(strict=True)
+ except OSError as exc:
+ raise ProfileError(f"run config is unavailable ({type(exc).__name__})", 5) from None
+ read_run_config(source)
+ profile = {"schema_version": 1, "id": name, "source_config": str(source), "overrides": {}}
+ with _lock(name):
+ path = _path(name)
+ if path.exists() or path.is_symlink():
+ raise ProfileError(f"profile {name!r} already exists")
+ _atomic(path, _bytes(profile))
+ return load(name)
+
+
+def propose_source(name: str, source_config: str) -> tuple[dict, str]:
+ """Select another installed run config without changing its contents."""
+ current, revision = load(name)
+ try:
+ source = Path(source_config).expanduser().resolve(strict=True)
+ except OSError as exc:
+ raise ProfileError(f"run config is unavailable ({type(exc).__name__})", 5) from None
+ if not stat.S_ISREG(source.lstat().st_mode):
+ raise ProfileError("run config must be a regular file", 5)
+ read_run_config(source)
+ proposed = {**current, "source_config": str(source)}
+ return validate_profile(proposed, expected_name=name), revision
+
+
+def save(name: str, proposed: dict, *, expected_revision: str,
+ expected_source_sha256: str | None = None) -> tuple[dict, str]:
+ name = _name(name)
+ validate_profile(proposed, expected_name=name)
+ read_run_config(Path(proposed["source_config"]))
+ with _lock(name):
+ current, revision = load(name)
+ if revision != expected_revision:
+ raise ProfileError("profile changed during edit; reload it before saving", 6)
+ if expected_source_sha256 is not None:
+ if not re.fullmatch(r"[0-9a-f]{64}", expected_source_sha256):
+ raise ProfileError("source digest must be a lowercase SHA-256")
+ try:
+ source = Path(proposed["source_config"]).read_bytes()
+ except OSError:
+ raise ProfileError("run config changed after review; retry", 6) from None
+ if len(source) > 1024 * 1024 or hashlib.sha256(source).hexdigest() != expected_source_sha256:
+ raise ProfileError("run config changed after review; retry", 6)
+ if current == proposed:
+ return current, revision
+ history = profile_dir() / ".history" / name
+ history.mkdir(mode=0o700, parents=True, exist_ok=True)
+ old = _path(name).read_bytes()
+ if _revision(old) != revision:
+ raise ProfileError("profile changed during edit; reload it before saving", 6)
+ old_path = history / f"{revision}.json"
+ if not old_path.exists():
+ _atomic(old_path, old)
+ _atomic(_path(name), _bytes(proposed))
+ return load(name)
+
+
+def set_values(name: str, assignments: list[str]) -> tuple[dict, str, str]:
+ proposed, revision = propose_values(name, assignments)
+ saved, new_revision = save(name, proposed, expected_revision=revision)
+ return saved, revision, new_revision
+
+
+def propose_values(name: str, assignments: list[str]) -> tuple[dict, str]:
+ current, revision = load(name)
+ changed = {key: value for key, value in (parse_assignment(item) for item in assignments)}
+ proposed = {**current, "overrides": {**current["overrides"], **changed}}
+ validate_profile(proposed, expected_name=name)
+ return proposed, revision
+
+
+def history(name: str) -> list[dict]:
+ _name(name)
+ directory = profile_dir() / ".history" / name
+ entries = []
+ if directory.exists():
+ for path in directory.glob("*.json"):
+ if re.fullmatch(r"[0-9a-f]{16}", path.stem) and path.is_file() and not path.is_symlink():
+ entries.append({"revision": path.stem, "saved_at": path.stat().st_mtime})
+ _, current = load(name)
+ return [{"revision": current, "current": True},
+ *sorted((item for item in entries if item["revision"] != current),
+ key=lambda item: item["saved_at"], reverse=True)]
+
+
+def rollback(name: str, target_revision: str) -> tuple[dict, str, str]:
+ _name(name)
+ if not re.fullmatch(r"[0-9a-f]{16}", target_revision):
+ raise ProfileError("rollback target must be a full 16-character revision")
+ _, current_revision = load(name)
+ path = profile_dir() / ".history" / name / f"{target_revision}.json"
+ try:
+ if not stat.S_ISREG(path.lstat().st_mode):
+ raise ProfileError("profile history must be a regular file", 5)
+ data = path.read_bytes()
+ if _revision(data) != target_revision:
+ raise ProfileError("profile history content does not match its revision", 5)
+ target = validate_profile(json.loads(data.decode("utf-8")), expected_name=name)
+ except FileNotFoundError:
+ raise ProfileError(f"profile revision {target_revision} was not found", 5) from None
+ except (OSError, UnicodeError, ValueError) as exc:
+ if isinstance(exc, ProfileError):
+ raise
+ raise ProfileError(f"cannot read profile history ({type(exc).__name__})", 5) from None
+ saved, new_revision = save(name, target, expected_revision=current_revision)
+ return saved, current_revision, new_revision
+
+
+def edit(name: str) -> tuple[dict, str, str]:
+ current, revision = load(name)
+ editor = os.environ.get("VISUAL") or os.environ.get("EDITOR")
+ if not editor:
+ raise ProfileError("set VISUAL or EDITOR, or use strata profile set")
+ command = shlex.split(editor, posix=os.name != "nt")
+ if not command:
+ raise ProfileError("VISUAL or EDITOR is empty")
+ fd, temp_name = tempfile.mkstemp(prefix=f".{name}-edit-", suffix=".json", dir=profile_dir())
+ keep_draft = False
+ try:
+ with os.fdopen(fd, "wb") as stream:
+ stream.write(_bytes(current))
+ result = subprocess.run([*command, temp_name], check=False)
+ if result.returncode:
+ keep_draft = True
+ raise ProfileError(f"editor exited with status {result.returncode}; draft kept at {temp_name}", 6)
+ try:
+ proposed = json.loads(Path(temp_name).read_text(encoding="utf-8-sig"))
+ except (OSError, ValueError) as exc:
+ keep_draft = True
+ raise ProfileError(f"edited profile is not valid JSON ({type(exc).__name__}); draft kept at {temp_name}") from None
+ try:
+ saved, new_revision = save(name, proposed, expected_revision=revision)
+ except ProfileError as exc:
+ keep_draft = True
+ raise ProfileError(f"{exc}; draft kept at {temp_name}", exc.exit_code) from None
+ return saved, revision, new_revision
+ finally:
+ if not keep_draft:
+ Path(temp_name).unlink(missing_ok=True)
+
+
+def resolve(ref: str) -> tuple[Path, dict | None, str | None]:
+ """A saved name or an explicit JSON path; path-like values never fall back to names."""
+ path = Path(ref).expanduser()
+ if path.suffix.lower() == ".json" or path.is_absolute() or "/" in ref or "\\" in ref:
+ return path.resolve(), None, None
+ profile, revision = load(ref)
+ return Path(profile["source_config"]), profile, revision
diff --git a/strata_control/readiness.py b/strata_control/readiness.py
new file mode 100644
index 000000000..91a158024
--- /dev/null
+++ b/strata_control/readiness.py
@@ -0,0 +1,141 @@
+"""Bounded, local API verification for a managed server instance.
+
+The ready file is only a hint that a port was bound. This module asks that
+same instance for telemetry, then performs one one-token generation when the
+model is loaded. Credentials stay in memory and no response text is saved.
+"""
+
+from __future__ import annotations
+
+import http.client
+import hmac
+import ipaddress
+import json
+import os
+import re
+import socket
+import time
+
+
+class ReadinessError(Exception):
+ pass
+
+
+def _address(ready: dict, expected_host: str) -> tuple[str, int]:
+ host = ready.get("bound_host")
+ port = ready.get("bound_port")
+ if host != expected_host or type(port) is not int or not 1 <= port <= 65535:
+ raise ReadinessError("ready_endpoint_mismatch")
+ if host in ("", "0.0.0.0"):
+ return "127.0.0.1", port
+ if host == "::":
+ return "::1", port
+ if host == "localhost":
+ return host, port
+ try:
+ ipaddress.ip_address(host)
+ except ValueError:
+ raise ReadinessError("ready_endpoint_not_numeric") from None
+ return host, port
+
+
+def _credential(source_bytes: bytes) -> str | None:
+ from serve.server import api_key_of, key_list
+
+ cfg = json.loads(source_bytes.decode("utf-8-sig"))
+ if not isinstance(cfg, dict):
+ raise ValueError("run config must be an object")
+ raw = os.environ.get("STRATA_API_KEY") or cfg.get("api_key", "")
+ keys = key_list(api_key_of(raw))
+ return keys[0] if keys else None
+
+
+def _request(host: str, port: int, method: str, path: str, key: str | None,
+ timeout: float, body: dict | None = None) -> dict:
+ payload = json.dumps(body, ensure_ascii=False).encode() if body is not None else None
+ headers = {"Accept": "application/json"}
+ if payload is not None:
+ headers["Content-Type"] = "application/json"
+ if key is not None:
+ headers["Authorization"] = "Bearer " + key
+ connection = http.client.HTTPConnection(host, port, timeout=max(0.1, timeout))
+ try:
+ connection.request(method, path, body=payload, headers=headers)
+ response = connection.getresponse()
+ raw = response.read(512 * 1024 + 1)
+ if len(raw) > 512 * 1024:
+ raise ReadinessError("probe_response_too_large")
+ if response.status != 200:
+ raise ReadinessError(f"probe_http_{response.status}")
+ result = json.loads(raw)
+ if not isinstance(result, dict):
+ raise ReadinessError("probe_invalid_response")
+ return result
+ except (OSError, socket.timeout, http.client.HTTPException):
+ raise ReadinessError("probe_transport_failed") from None
+ except (UnicodeError, ValueError):
+ raise ReadinessError("probe_invalid_response") from None
+ finally:
+ connection.close()
+
+
+def verify(ready: dict, source_bytes: bytes, *, expected_host: str,
+ expected_instance: str, expected_attestation: str,
+ timeout: float, force_load: bool = False) -> dict:
+ if not isinstance(expected_attestation, str) or not re.fullmatch(r"[0-9a-f]{64}", expected_attestation):
+ raise ReadinessError("probe_launch_attestation_unavailable")
+ host, port = _address(ready, expected_host)
+ display_host = f"[{host}]" if ":" in host else host
+ api_url = f"http://{display_host}:{port}"
+ deadline = time.monotonic() + timeout
+ try:
+ cfg = json.loads(source_bytes.decode("utf-8-sig"))
+ key = _credential(source_bytes)
+ except (UnicodeError, ValueError, TypeError):
+ raise ReadinessError("probe_credential_invalid") from None
+ if not isinstance(cfg, dict) or not isinstance(ready.get("model_id"), str) or \
+ (cfg.get("model_name") is not None and ready["model_id"] != cfg["model_name"]):
+ raise ReadinessError("probe_model_mismatch")
+ telemetry = _request(host, port, "GET", "/v1/telemetry", key,
+ max(0.1, deadline - time.monotonic()))
+ instance = telemetry.get("instance")
+ model = telemetry.get("model")
+ if not isinstance(instance, dict) or instance.get("id") != expected_instance:
+ raise ReadinessError("probe_instance_mismatch")
+ reported_attestation = instance.get("launch_attestation")
+ if not isinstance(reported_attestation, str) or not hmac.compare_digest(
+ reported_attestation, expected_attestation):
+ raise ReadinessError("probe_launch_attestation_mismatch")
+ if not isinstance(model, dict) or model.get("id") != ready.get("model_id"):
+ raise ReadinessError("probe_model_mismatch")
+ if ready.get("model_state") not in ("ready", "unloaded"):
+ raise ReadinessError("probe_model_state_invalid")
+ loaded = model.get("loaded")
+ if type(loaded) is not bool:
+ raise ReadinessError("probe_model_state_unavailable")
+ if not loaded and not force_load:
+ return {"api_identity_verified": True, "launch_attested": True, "generation_ready": False,
+ "readiness_state": "unloaded", "model_state": "unloaded", "api_url": api_url}
+ probe = {"model": ready.get("model_id"), "messages": [{"role": "user", "content": "hi"}],
+ "max_tokens": 1, "temperature": 0, "stream": False}
+ while True:
+ try:
+ result = _request(host, port, "POST", "/v1/chat/completions", key,
+ max(0.1, deadline - time.monotonic()), probe)
+ break
+ except ReadinessError as exc:
+ if str(exc) not in ("probe_http_409", "probe_http_429", "probe_http_503") or \
+ time.monotonic() + 0.25 >= deadline:
+ raise
+ time.sleep(0.25)
+ choices = result.get("choices")
+ if not isinstance(choices, list) or len(choices) != 1 or not isinstance(choices[0], dict) or \
+ not isinstance(choices[0].get("message"), dict) or \
+ not isinstance(choices[0].get("finish_reason"), str):
+ raise ReadinessError("probe_generation_invalid_response")
+ usage = result.get("usage")
+ if not isinstance(usage, dict) or type(usage.get("completion_tokens")) is not int or \
+ usage["completion_tokens"] < 1:
+ raise ReadinessError("probe_generation_no_tokens")
+ return {"api_identity_verified": True, "launch_attested": True, "generation_ready": True,
+ "readiness_state": "generation_ready", "model_state": "ready", "api_url": api_url}
diff --git a/strata_control/recipes.py b/strata_control/recipes.py
new file mode 100644
index 000000000..63df34d4e
--- /dev/null
+++ b/strata_control/recipes.py
@@ -0,0 +1,437 @@
+"""Typed, owner-editable local operation recipes for saved serving profiles.
+
+Recipes contain no executable command text. Each kind routes to an existing
+Strata operation. This is a source-run store; Desktop must later use the same
+schema and operation authority rather than add a separate implementation.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import re
+import shlex
+import stat
+import subprocess
+import sys
+import tempfile
+import uuid
+from pathlib import Path
+
+from strata_control import profiles
+from strata_control.profiles import ProfileError
+
+
+KINDS = frozenset({"runtime.restart", "engine.calibrate.measure", "components.verify"})
+MAX_BYTES = 64 * 1024
+
+
+def _identity(profile: str, name: str) -> tuple[str, str]:
+ if not profiles.PROFILE_ID.fullmatch(profile) or not profiles.PROFILE_ID.fullmatch(name):
+ raise ProfileError("recipe profile and name must use lowercase letters, digits, _ or -")
+ return profile, name
+
+
+def _directory(profile: str, *, create: bool = False) -> Path:
+ profiles.load(profile)
+ base = profiles.profile_dir()
+ directory = base / ".ops" / profile
+ for path in (base, directory.parent):
+ if not path.exists() and not path.is_symlink():
+ continue
+ details = path.lstat()
+ if not stat.S_ISDIR(details.st_mode):
+ raise ProfileError("recipe directory must not be a symlink", 5)
+ if os.name == "posix" and (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077):
+ raise ProfileError("recipe directory must be owner-only (mode 0700)", 5)
+ if create:
+ directory.parent.mkdir(mode=0o700, exist_ok=True)
+ directory.mkdir(mode=0o700, exist_ok=True)
+ if directory.exists() or directory.is_symlink():
+ details = directory.lstat()
+ if not stat.S_ISDIR(details.st_mode):
+ raise ProfileError("recipe directory must not be a symlink", 5)
+ if os.name == "posix" and (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077):
+ raise ProfileError("recipe directory must be owner-only (mode 0700)", 5)
+ return directory
+
+
+def _path(profile: str, name: str, *, create: bool = False) -> Path:
+ _identity(profile, name)
+ return _directory(profile, create=create) / f"{name}.json"
+
+
+def _lock_name(profile: str) -> str:
+ return "ops" + hashlib.sha256(profile.encode("utf-8")).hexdigest()[:24]
+
+
+def _history_dir(profile: str, name: str, *, create: bool = False) -> Path:
+ root = _path(profile, name).parent / ".history"
+ directory = root / name
+ for path in (root, directory):
+ if path.is_symlink():
+ raise ProfileError("recipe history directory must not be a symlink", 5)
+ if create:
+ root.mkdir(mode=0o700, exist_ok=True)
+ directory.mkdir(mode=0o700, exist_ok=True)
+ for path in (root, directory):
+ if path.exists():
+ details = path.lstat()
+ if not stat.S_ISDIR(details.st_mode) or (os.name == "posix" and
+ (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)):
+ raise ProfileError("recipe history directory must be owner-only", 5)
+ return directory
+
+
+def _bytes(recipe: dict) -> bytes:
+ return (json.dumps(recipe, sort_keys=True, indent=2, ensure_ascii=False, allow_nan=False) + "\n").encode("utf-8")
+
+
+def _validate(recipe: object, profile: str, name: str) -> dict:
+ if not isinstance(recipe, dict) or set(recipe) != {"schema_version", "profile", "id", "kind", "params"}:
+ raise ProfileError("recipe needs schema_version, profile, id, kind and params")
+ if type(recipe["schema_version"]) is not int or recipe["schema_version"] != 1:
+ raise ProfileError("unsupported recipe schema version")
+ if recipe["profile"] != profile or recipe["id"] != name:
+ raise ProfileError("recipe profile or ID does not match its file")
+ kind, params = recipe["kind"], recipe["params"]
+ if not isinstance(kind, str) or kind not in KINDS or not isinstance(params, dict):
+ raise ProfileError("recipe kind or parameters are unsupported")
+ if kind == "runtime.restart":
+ if set(params) != {"startup_wait_s"} or type(params["startup_wait_s"]) is not int or \
+ not 1 <= params["startup_wait_s"] <= 600:
+ raise ProfileError("restart recipe needs startup_wait_s in 1..600")
+ elif kind == "engine.calibrate.measure":
+ directory = params.get("report_dir")
+ if set(params) != {"report_dir"} or not isinstance(directory, str) or not directory or "\x00" in directory or \
+ not Path(directory).is_absolute():
+ raise ProfileError("calibration recipe needs an absolute report_dir")
+ elif set(params) - {"live"} or ("live" in params and type(params["live"]) is not bool):
+ raise ProfileError("component verification recipe accepts only live=true|false")
+ return recipe
+
+
+def _default(profile: str, name: str, kind: str) -> dict:
+ if not isinstance(kind, str) or kind not in KINDS:
+ raise ProfileError("recipe kind is unsupported")
+ if kind == "runtime.restart":
+ params = {"startup_wait_s": 300}
+ elif kind == "engine.calibrate.measure":
+ params = {"report_dir": str(profiles.profile_dir().resolve() / ".reports")}
+ else:
+ params = {}
+ return _validate({"schema_version": 1, "profile": profile, "id": name,
+ "kind": kind, "params": params}, profile, name)
+
+
+def create(profile: str, name: str, kind: str) -> tuple[dict, str]:
+ profile, name = _identity(profile, name)
+ value = _default(profile, name, kind)
+ path = _path(profile, name, create=True)
+ with profiles._lock(_lock_name(profile)):
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
+ if hasattr(os, "O_NOFOLLOW"):
+ flags |= os.O_NOFOLLOW
+ try:
+ descriptor = os.open(path, flags, 0o600)
+ except FileExistsError:
+ raise ProfileError(f"recipe {name!r} already exists") from None
+ try:
+ with os.fdopen(descriptor, "wb") as stream:
+ stream.write(_bytes(value))
+ stream.flush()
+ os.fsync(stream.fileno())
+ except BaseException:
+ path.unlink(missing_ok=True)
+ raise
+ return load(profile, name)
+
+
+def initialize(profile: str) -> list[str]:
+ profiles.load(profile)
+ defaults = (("restart", "runtime.restart"),
+ ("calibrate", "engine.calibrate.measure"),
+ ("check", "components.verify"))
+ for name, kind in defaults:
+ path = _path(profile, name)
+ if path.exists() or path.is_symlink():
+ saved, _ = load(profile, name)
+ if saved["kind"] != kind:
+ raise ProfileError(f"recipe {name!r} exists with a different kind; choose another name")
+ created = []
+ for name, kind in defaults:
+ path = _path(profile, name)
+ if not path.exists() and not path.is_symlink():
+ try:
+ create(profile, name, kind)
+ created.append(name)
+ except ProfileError as exc:
+ if "already exists" not in str(exc):
+ raise
+ saved, _ = load(profile, name)
+ if saved["kind"] != kind:
+ raise ProfileError(f"recipe {name!r} exists with a different kind; choose another name")
+ return created
+
+
+def load(profile: str, name: str) -> tuple[dict, str]:
+ path = _path(profile, name)
+ try:
+ details = path.lstat()
+ if not stat.S_ISREG(details.st_mode) or details.st_size > MAX_BYTES:
+ raise ProfileError("recipe must be a regular file under 64 KiB", 5)
+ if os.name == "posix" and (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077):
+ raise ProfileError("recipe file must be owner-only (mode 0600)", 5)
+ data = path.read_bytes()
+ value = json.loads(data.decode("utf-8-sig"))
+ except FileNotFoundError:
+ raise ProfileError(f"recipe {name!r} is missing; use strata ops init --profile {profile}", 5) from None
+ except (OSError, UnicodeError, ValueError) as exc:
+ if isinstance(exc, ProfileError):
+ raise
+ raise ProfileError(f"cannot read recipe ({type(exc).__name__})", 5) from None
+ return _validate(value, profile, name), profiles._revision(data)
+
+
+def list_recipes(profile: str) -> list[dict]:
+ directory = _directory(profile)
+ if not directory.exists():
+ return []
+ items = []
+ for path in sorted(directory.glob("*.json")):
+ if profiles.PROFILE_ID.fullmatch(path.stem):
+ try:
+ recipe, revision = load(profile, path.stem)
+ items.append({"id": path.stem, "kind": recipe["kind"], "revision": revision})
+ except ProfileError as exc:
+ items.append({"id": path.stem, "error": str(exc)})
+ return items
+
+
+def save(profile: str, name: str, proposed: dict, expected_revision: str) -> tuple[dict, str]:
+ _validate(proposed, profile, name)
+ with profiles._lock(_lock_name(profile)):
+ current, revision = load(profile, name)
+ if revision != expected_revision:
+ raise ProfileError("recipe changed during edit; reload it before saving", 6)
+ if current == proposed:
+ return current, revision
+ path = _path(profile, name)
+ old = path.read_bytes()
+ if profiles._revision(old) != revision:
+ raise ProfileError("recipe changed during edit; reload it before saving", 6)
+ history_dir = _history_dir(profile, name, create=True)
+ backup = history_dir / f"{revision}.json"
+ if backup.exists() or backup.is_symlink():
+ details = backup.lstat()
+ if not stat.S_ISREG(details.st_mode) or (os.name == "posix" and
+ (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077)) or \
+ backup.read_bytes() != old:
+ raise ProfileError("recipe history conflicts with the saved revision", 5)
+ else:
+ profiles._atomic(backup, old)
+ profiles._atomic(path, _bytes(proposed))
+ return load(profile, name)
+
+
+def history(profile: str, name: str) -> list[dict]:
+ _, current = load(profile, name)
+ directory = _history_dir(profile, name)
+ entries = []
+ if directory.exists():
+ for path in directory.glob("*.json"):
+ if re.fullmatch(r"[0-9a-f]{16}", path.stem) and path.is_file() and not path.is_symlink():
+ entries.append({"revision": path.stem, "saved_at": path.stat().st_mtime})
+ return [{"revision": current, "current": True},
+ *sorted((item for item in entries if item["revision"] != current),
+ key=lambda item: item["saved_at"], reverse=True)]
+
+
+def rollback(profile: str, name: str, target_revision: str) -> tuple[dict, str, str]:
+ if not re.fullmatch(r"[0-9a-f]{16}", target_revision):
+ raise ProfileError("rollback target must be a full 16-character revision")
+ _, current_revision = load(profile, name)
+ path = _history_dir(profile, name) / f"{target_revision}.json"
+ try:
+ details = path.lstat()
+ if not stat.S_ISREG(details.st_mode) or details.st_size > MAX_BYTES:
+ raise ProfileError("recipe history must be a regular file under 64 KiB", 5)
+ if os.name == "posix" and (details.st_uid != os.getuid() or stat.S_IMODE(details.st_mode) & 0o077):
+ raise ProfileError("recipe history file must be owner-only", 5)
+ data = path.read_bytes()
+ if profiles._revision(data) != target_revision:
+ raise ProfileError("recipe history content does not match its revision", 5)
+ proposed = _validate(json.loads(data.decode("utf-8")), profile, name)
+ except FileNotFoundError:
+ raise ProfileError(f"recipe revision {target_revision} was not found", 5) from None
+ except (OSError, UnicodeError, ValueError) as exc:
+ if isinstance(exc, ProfileError):
+ raise
+ raise ProfileError(f"cannot read recipe history ({type(exc).__name__})", 5) from None
+ saved, new_revision = save(profile, name, proposed, current_revision)
+ return saved, current_revision, new_revision
+
+
+def propose_value(profile: str, name: str, assignment: str) -> tuple[dict, str]:
+ current, revision = load(profile, name)
+ key, separator, raw = assignment.partition("=")
+ if not separator or not raw:
+ raise ProfileError("expected a typed recipe parameter as KEY=VALUE")
+ kind = current["kind"]
+ if kind == "runtime.restart" and key == "startup_wait_s":
+ try:
+ value: object = int(raw)
+ except ValueError:
+ raise ProfileError("startup_wait_s must be a whole number") from None
+ elif kind == "engine.calibrate.measure" and key == "report_dir":
+ value = raw
+ elif kind == "components.verify" and key == "live" and raw in ("true", "false"):
+ value = raw == "true"
+ else:
+ raise ProfileError("parameter is not supported by this recipe kind")
+ proposed = {**current, "params": {**current["params"], key: value}}
+ return _validate(proposed, profile, name), revision
+
+
+def edit(profile: str, name: str) -> tuple[dict, str, str]:
+ current, revision = load(profile, name)
+ editor = os.environ.get("VISUAL") or os.environ.get("EDITOR")
+ if not editor:
+ raise ProfileError("set VISUAL or EDITOR, or use strata ops set")
+ command = shlex.split(editor, posix=os.name != "nt")
+ if not command:
+ raise ProfileError("VISUAL or EDITOR is empty")
+ descriptor, temporary = tempfile.mkstemp(prefix=f".{name}-edit-", suffix=".json", dir=_directory(profile))
+ keep = False
+ try:
+ with os.fdopen(descriptor, "wb") as stream:
+ stream.write(_bytes(current))
+ result = subprocess.run([*command, temporary], check=False)
+ if result.returncode:
+ keep = True
+ raise ProfileError(f"editor exited with status {result.returncode}; draft kept at {temporary}", 6)
+ try:
+ proposed = json.loads(Path(temporary).read_text(encoding="utf-8-sig"))
+ saved, new_revision = save(profile, name, proposed, revision)
+ except (OSError, ValueError) as exc:
+ keep = True
+ code = exc.exit_code if isinstance(exc, ProfileError) else 2
+ raise ProfileError(f"invalid recipe edit ({exc}); draft kept at {temporary}", code) from None
+ return saved, revision, new_revision
+ finally:
+ if not keep:
+ Path(temporary).unlink(missing_ok=True)
+
+
+def plan(profile: str, name: str) -> dict:
+ recipe, revision = load(profile, name)
+ kind = recipe["kind"]
+ if kind == "runtime.restart":
+ from strata_control import runtime
+ preflight = runtime.plan_restart(profile)
+ profile_revision = preflight.get("candidate_profile_revision")
+ operation = {"ok": preflight["ok"], "exit_code": preflight.get("exit_code", 6),
+ "preflight": preflight, "startup_wait_s": recipe["params"]["startup_wait_s"],
+ "run_effects": {"drain_current_instance": True, "start_new_instance": True,
+ "rollback_previous_launch_on_activation_failure": True}}
+ elif kind == "engine.calibrate.measure":
+ from strata_control import calibration
+ preflight = calibration.preview(profile)
+ profile_revision = preflight["profile_revision"]
+ operation = {"ok": preflight["component_preflight"]["ok"], "exit_code": 5,
+ "preflight": preflight, "report_dir": recipe["params"]["report_dir"],
+ "run_effects": {"start_engine_for_decode_sweep": True, "write_new_report": True,
+ "change_run_config": False, "requires_exclusive_acknowledgement": True}}
+ else:
+ from strata_control.doctor import inspect as inspect_components
+ path, _, _ = profiles.resolve(profile)
+ live = recipe["params"].get("live", False)
+ report = inspect_components(path, profile_id=profile, live=live)
+ profile_revision = profiles.load(profile)[1]
+ operation = {"ok": report["ok"], "exit_code": 5, "preflight": report,
+ "run_effects": {"read_components": True, "query_host_gpus": live, "write_files": False}}
+ if profile_revision is not None and profile_revision != profiles.load(profile)[1]:
+ raise ProfileError("profile changed during recipe preview; retry", 6)
+ return {"profile": profile, "profile_revision": profile_revision,
+ "recipe": name, "recipe_revision": revision,
+ "kind": kind, "operation": operation, "would_execute": False}
+
+
+def run(profile: str, name: str, *, exclusive_ack: bool = False,
+ expected_revision: str | None = None,
+ expected_profile_revision: str | None = None,
+ expected_owner_id: str | None = None,
+ expected_instance_id: str | None = None,
+ expected_source_sha256: str | None = None) -> dict:
+ recipe, revision = load(profile, name)
+ if expected_revision is not None and revision != expected_revision:
+ raise ProfileError("recipe changed after preview; plan it again before running", 6)
+ if expected_profile_revision is not None and profiles.load(profile)[1] != expected_profile_revision:
+ raise ProfileError("profile changed after preview; plan it again before running", 6)
+ kind = recipe["kind"]
+ if kind == "runtime.restart":
+ from strata_control import runtime
+ if (expected_owner_id is None) != (expected_instance_id is None):
+ raise ProfileError("restart recipe needs both reviewed owner and instance IDs")
+ if any(value is not None for value in (expected_owner_id, expected_instance_id,
+ expected_source_sha256)):
+ preflight = runtime.plan_restart(profile)
+ if not preflight["ok"]:
+ raise ProfileError(preflight.get("error", "restart preflight failed"),
+ preflight.get("exit_code", 6))
+ if expected_owner_id is not None and preflight["current_owner_id"] != expected_owner_id:
+ raise ProfileError("owner_changed_after_restart_plan", 6)
+ if expected_instance_id is not None and preflight["current_instance_id"] != expected_instance_id:
+ raise ProfileError("instance_changed_after_restart_plan", 6)
+ if (expected_source_sha256 is not None and
+ preflight["candidate_source_sha256"] != expected_source_sha256):
+ raise ProfileError("source_changed_after_preview", 6)
+ elif any(value is not None for value in (expected_owner_id, expected_instance_id,
+ expected_source_sha256)):
+ raise ProfileError("owner, instance and source preconditions require a restart recipe")
+ if kind == "engine.calibrate.measure" and not exclusive_ack:
+ raise ProfileError("calibration recipe requires --exclusive for each run")
+ from strata_control import journal
+ profile_revision = profiles.load(profile)[1]
+ record = journal.begin(profile, name, kind, revision, profile_revision,
+ intent=dict(recipe["params"]))
+ try:
+ if kind == "runtime.restart":
+ from strata_control import runtime
+ kwargs = {"startup_wait": recipe["params"]["startup_wait_s"]}
+ if expected_profile_revision is not None:
+ kwargs["expected_profile_revision"] = expected_profile_revision
+ if expected_owner_id is not None:
+ kwargs["expected_owner_id"] = expected_owner_id
+ kwargs["expected_instance_id"] = expected_instance_id
+ if expected_source_sha256 is not None:
+ kwargs["expected_source_sha256"] = expected_source_sha256
+ result = runtime.restart(profile, **kwargs)
+ elif kind == "engine.calibrate.measure":
+ from strata_control import calibration
+ directory = Path(recipe["params"]["report_dir"])
+ directory.mkdir(mode=0o700, exist_ok=True)
+ if not stat.S_ISDIR(directory.lstat().st_mode):
+ raise ProfileError("report_dir must be a directory, not a symlink", 5)
+ report_path = directory / f"calibration-{uuid.uuid4().hex}.json"
+ report = calibration.measure(profile, report_path, exclusive_ack=True,
+ say=lambda message: print(message, file=sys.stderr))
+ result = {"ok": True, "report_path": str(report_path), "report": report,
+ "requires_review_before_apply": True}
+ else:
+ from strata_control.doctor import inspect as inspect_components
+ path, _, _ = profiles.resolve(profile)
+ report = inspect_components(path, profile_id=profile, live=recipe["params"].get("live", False))
+ result = {"ok": report["ok"], "report": report}
+ except BaseException as exc:
+ unknown = isinstance(exc, (KeyboardInterrupt, SystemExit)) or \
+ (isinstance(exc, ProfileError) and exc.exit_code == 8)
+ journal.finish(profile, record["operation_id"], "completion_unknown" if unknown else "failed",
+ {"error_type": type(exc).__name__,
+ "exit_code": exc.exit_code if isinstance(exc, ProfileError) else 130 if unknown else 6})
+ raise
+ journal.finish(profile, record["operation_id"], "succeeded" if result["ok"] else "failed",
+ journal.compact_result(kind, result))
+ return {"profile": profile, "recipe": name, "recipe_revision": revision,
+ "kind": kind, "operation_id": record["operation_id"], "result": result}
diff --git a/strata_control/runtime.py b/strata_control/runtime.py
new file mode 100644
index 000000000..d1c593869
--- /dev/null
+++ b/strata_control/runtime.py
@@ -0,0 +1,1054 @@
+"""Local owner-controlled supervisor for one saved Strata serving profile.
+
+The supervisor holds the Popen handle for the server it started. A client never
+sends a signal to a PID found in a ready file. The control socket and token live
+in an owner-private directory. This first implementation supports POSIX; Windows
+needs a qualified owner-only pipe/ACL implementation before it may manage work.
+"""
+
+from __future__ import annotations
+
+import argparse
+import errno
+import hashlib
+import json
+import os
+import re
+import secrets
+import signal
+import socket
+import stat
+import subprocess
+import sys
+import threading
+import time
+import uuid
+from pathlib import Path
+
+try:
+ import fcntl
+except ImportError: # Windows has no qualified owner transport yet.
+ fcntl = None
+
+from strata_control import owner_transport, profiles, readiness
+from serve import launch_identity
+from strata_control.profiles import ProfileError
+
+
+MAX_MESSAGE = 64 * 1024
+ROOT = Path(__file__).resolve().parents[1]
+_STARTED_HOSTS: dict[str, subprocess.Popen] = {}
+
+
+def _supported() -> None:
+ """Refuse only when no transport exists at all.
+
+ POSIX uses an owner-private ``AF_UNIX`` socket. Windows uses a loopback-only TCP listener whose
+ authority rests on the 256-bit control token plus a ``0700`` state directory, because the Python
+ standard library cannot create a named pipe with a security descriptor; the difference is
+ recorded in ``owner_transport`` and in ``docs/work/IMPLEMENTATION_STATUS.md`` rather than being
+ presented as equivalent. Anything else is refused.
+ """
+ if os.name == "nt" or (os.name == "posix" and hasattr(socket, "AF_UNIX")):
+ return
+ raise ProfileError("managed runtime has no qualified local control transport on this platform", 5)
+
+
+def _name(value: str) -> str:
+ if not profiles.PROFILE_ID.fullmatch(value):
+ raise ProfileError("runtime commands require a saved profile name")
+ return value
+
+
+def runtime_dir() -> Path:
+ _supported()
+ override = os.environ.get("STRATA_RUNTIME_DIR")
+ base = Path(override).expanduser() if override else \
+ Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local" / "state") / "strata" / "runtime"
+ if not base.is_absolute():
+ raise ProfileError("STRATA_RUNTIME_DIR must be absolute")
+ base.mkdir(parents=True, mode=0o700, exist_ok=True)
+ details = base.lstat()
+ if not stat.S_ISDIR(details.st_mode) or details.st_uid != os.getuid() or \
+ stat.S_IMODE(details.st_mode) & 0o077:
+ raise ProfileError("runtime directory must be owner-only (mode 0700)", 5)
+ return base
+
+
+def acquire_activity_lease(*, shared: bool) -> int:
+ """Let managed hosts coexist while excluding a local calibration run."""
+ directory = runtime_dir()
+ flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NOFOLLOW", 0)
+ try:
+ descriptor = os.open(directory / ".activity.lock", flags, 0o600)
+ details = os.fstat(descriptor)
+ if not stat.S_ISREG(details.st_mode) or details.st_uid != os.getuid() or \
+ stat.S_IMODE(details.st_mode) & 0o077:
+ raise ProfileError("runtime activity lock must be owner-only", 5)
+ try:
+ fcntl.flock(descriptor, (fcntl.LOCK_SH if shared else fcntl.LOCK_EX) | fcntl.LOCK_NB)
+ except OSError as exc:
+ if exc.errno in (errno.EWOULDBLOCK, errno.EAGAIN):
+ raise ProfileError("a managed runtime or calibration owns the local engine lease", 6) from None
+ raise
+ return descriptor
+ except BaseException:
+ if "descriptor" in locals():
+ os.close(descriptor)
+ raise
+
+
+def active_managed_instances() -> list[dict]:
+ """Inspect private owner records, including stale or uncertain instances."""
+ directory = runtime_dir()
+ names = [path.stem for path in directory.glob("*.json") if profiles.PROFILE_ID.fullmatch(path.stem)]
+ if len(names) > 64:
+ raise ProfileError("too many managed runtime records to verify exclusive access", 6)
+ active = []
+ for name in names:
+ current = status(name)
+ if current.get("state") != "stopped":
+ active.append({"profile": name, "state": current.get("state", "unknown")})
+ return active
+
+
+def _paths(name: str) -> tuple[Path, Path, Path]:
+ directory = runtime_dir()
+ digest = hashlib.sha256((str(directory) + "\0" + name).encode("utf-8")).hexdigest()[:16]
+ # The address form is the transport's business: POSIX gets a private socket path (with the
+ # short-path fallback for a long home directory), Windows gets its loopback placeholder, which
+ # the listener replaces with the real port when it binds.
+ address = owner_transport.address_for(directory, name)
+ return directory / f"{name}.json", address, directory / f"{name}.host.log"
+
+
+def _read_state(name: str) -> dict | None:
+ path, socket_path, _ = _paths(_name(name))
+ try:
+ details = path.lstat()
+ except FileNotFoundError:
+ return None
+ if not stat.S_ISREG(details.st_mode) or details.st_uid != os.getuid() or \
+ stat.S_IMODE(details.st_mode) & 0o077 or details.st_size > 16 * 1024:
+ raise ProfileError("runtime state file is not private or is invalid", 5)
+ try:
+ state = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, UnicodeError, ValueError):
+ raise ProfileError("runtime state file is unreadable", 5) from None
+ if not isinstance(state, dict) or state.get("schema_version") != 1 or state.get("profile") != name or \
+ state.get("socket") != socket_path or not isinstance(state.get("token"), str) or \
+ not re.fullmatch(r"[0-9a-f]{64}", state["token"]):
+ raise ProfileError("runtime state file has an unsupported shape", 5)
+ return state
+
+
+def _child_marker(name: str, token: str) -> Path:
+ return runtime_dir() / f"{name}-{token}.child.json"
+
+
+def _pid_exists(pid: int) -> bool:
+ try:
+ os.kill(pid, 0) # Liveness check only; never signal a PID from saved state.
+ except ProcessLookupError:
+ return False
+ except PermissionError:
+ return True
+ return True
+
+
+def _host_lease_active(name: str) -> bool:
+ path, _, _ = _paths(name)
+ descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
+ try:
+ try:
+ fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError as exc:
+ if exc.errno in (errno.EWOULDBLOCK, errno.EAGAIN):
+ return True
+ raise
+ return False
+ finally:
+ os.close(descriptor)
+
+
+def _recover_stale(name: str, *, wait: float) -> bool:
+ """Reclaim private state only after the host lease and owned child are gone."""
+ state = _read_state(name)
+ if state is None:
+ return False
+ state_path, socket_path, _ = _paths(name)
+ flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
+ descriptor = os.open(state_path, flags)
+ try:
+ if os.fstat(descriptor).st_ino != state_path.lstat().st_ino:
+ raise ProfileError("runtime state changed during recovery", 6)
+ try:
+ fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError as exc:
+ if exc.errno in (errno.EWOULDBLOCK, errno.EAGAIN):
+ raise ProfileError("this profile already has a live managed runtime", 6) from None
+ raise
+ marker = _child_marker(name, state["token"])
+ try:
+ details = marker.lstat()
+ if not stat.S_ISREG(details.st_mode) or details.st_uid != os.getuid() or \
+ stat.S_IMODE(details.st_mode) & 0o077 or details.st_size > 4096:
+ raise ValueError("invalid owner marker")
+ child = json.loads(marker.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ raise ProfileError("lost host has no valid child ownership record; inspect before recovery", 6) from None
+ if not isinstance(child, dict) or child.get("host_token") != state["token"] or \
+ child.get("phase") != "owned" or type(child.get("pid")) is not int or child["pid"] <= 0:
+ raise ProfileError("lost host child launch is unverified; inspect before recovery", 6)
+ deadline = time.monotonic() + min(45.0, max(5.0, wait))
+ while _pid_exists(child["pid"]) and time.monotonic() < deadline:
+ time.sleep(0.1)
+ if _pid_exists(child["pid"]):
+ raise ProfileError("lost host child is still present; retry after it exits", 6)
+ if not isinstance(child.get("ready"), str):
+ raise ProfileError("lost host ready path is invalid; inspect before recovery", 6)
+ ready = Path(child["ready"])
+ if ready.parent != runtime_dir() or not ready.name.startswith(name + "-") or \
+ not ready.name.endswith(".ready.json"):
+ raise ProfileError("lost host ready path is invalid; inspect before recovery", 6)
+ try:
+ details = ready.lstat()
+ if not stat.S_ISREG(details.st_mode) or details.st_uid != os.getuid() or \
+ stat.S_IMODE(details.st_mode) & 0o077:
+ raise ProfileError("lost host ready file is invalid; inspect before recovery", 6)
+ ready.unlink()
+ except FileNotFoundError:
+ pass
+ if not owner_transport.WINDOWS:
+ # POSIX: the endpoint is a filesystem socket, so it can be inspected directly. A socket
+ # that is still accepting means a live owner, and nothing may be recovered over it.
+ try:
+ details = Path(socket_path).lstat()
+ if not stat.S_ISSOCK(details.st_mode) or details.st_uid != os.getuid():
+ raise ProfileError("lost host socket is invalid; inspect before recovery", 6)
+ with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as probe:
+ probe.settimeout(0.2)
+ try:
+ probe.connect(str(socket_path))
+ except OSError as exc:
+ if exc.errno not in (errno.ECONNREFUSED, errno.ENOENT):
+ raise ProfileError(
+ "lost host socket cannot be verified; inspect before recovery", 6) from None
+ else:
+ raise ProfileError(
+ "a control listener still owns this socket; inspect before recovery", 6)
+ Path(socket_path).unlink()
+ except FileNotFoundError:
+ pass
+ # Windows: the endpoint is a loopback port chosen at bind time, so there is no artifact to
+ # inspect and none to clean up. Recovery rests on the state file, the owner pid and the
+ # token, all of which the caller has already validated.
+ snapshots = list(runtime_dir().glob(f"{name}-{state['token']}-*.rollback.json"))
+ if len(snapshots) > 64:
+ raise ProfileError("too many lost-host config snapshots; inspect before recovery", 6)
+ for snapshot in snapshots:
+ details = snapshot.lstat()
+ if not stat.S_ISREG(details.st_mode) or details.st_uid != os.getuid() or \
+ stat.S_IMODE(details.st_mode) & 0o077:
+ raise ProfileError("lost-host config snapshot is not private; inspect before recovery", 6)
+ snapshot.unlink()
+ marker.unlink()
+ state_path.unlink()
+ return True
+ finally:
+ os.close(descriptor)
+
+
+def _write_new(path: Path, data: bytes) -> int:
+ descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ try:
+ # Keep this lease open in the owner host. The kernel releases it even
+ # after SIGKILL, unlike a PID file or a stale Unix socket.
+ fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ with os.fdopen(os.dup(descriptor), "wb") as stream:
+ stream.write(data)
+ stream.flush()
+ os.fsync(descriptor)
+ return descriptor
+ except BaseException:
+ os.close(descriptor)
+ path.unlink(missing_ok=True)
+ raise
+
+
+def _rpc(name: str, command: str, *, timeout: float = 5, params: dict | None = None) -> dict:
+ state = _read_state(name)
+ if state is None:
+ raise ProfileError("runtime is not managed or is stopped", 3)
+ request = {"token": state["token"], "command": command}
+ if params:
+ request.update(params)
+ raw = (json.dumps(request) + "\n").encode("utf-8")
+ # The transport decides the address family: a private POSIX socket, or the loopback listener
+ # on Windows. The token in `raw` is what authorises the request either way.
+ client = owner_transport.connect(state["socket"], timeout=timeout)
+ try:
+ try:
+ client.sendall(raw)
+ answer = bytearray()
+ while len(answer) <= MAX_MESSAGE:
+ chunk = client.recv(4096)
+ if not chunk:
+ break
+ answer.extend(chunk)
+ if b"\n" in chunk:
+ break
+ except socket.timeout:
+ raise ProfileError("runtime operation wait expired; inspect runtime status", 8) from None
+ except OSError:
+ raise ProfileError("runtime control is unavailable; inspect the private host log", 3) from None
+ finally:
+ client.close()
+ if len(answer) > MAX_MESSAGE:
+ raise ProfileError("runtime control response is too large", 6)
+ try:
+ result = json.loads(answer.split(b"\n", 1)[0])
+ except (ValueError, UnicodeError):
+ raise ProfileError("runtime control returned an invalid response", 6) from None
+ if not isinstance(result, dict) or type(result.get("ok")) is not bool:
+ raise ProfileError("runtime control returned an invalid response", 6)
+ return result
+
+
+def status(name: str) -> dict:
+ state = _read_state(name)
+ if state is None:
+ return {"ok": True, "profile": name, "state": "stopped"}
+ try:
+ active = _host_lease_active(name)
+ except FileNotFoundError:
+ return {"ok": True, "profile": name, "state": "stopped"}
+ if not active:
+ return {"ok": False, "profile": name, "state": "stale", "error": "owner_host_lost",
+ "next_action": "runtime start will recover after the owned child exits", "exit_code": 6}
+ return _rpc(name, "status")
+
+
+def _start_candidate(name: str) -> tuple[dict, str]:
+ from strata_cli.cli import _launch_plan
+ plan, _ = _launch_plan(name)
+ digest = hashlib.sha256(Path(plan["source_config"]).read_bytes()).hexdigest()
+ return plan, digest
+
+
+def _check_start_candidate(name: str, expected_profile_revision: str | None,
+ expected_source_sha256: str | None) -> tuple[dict, str]:
+ plan, digest = _start_candidate(name)
+ if expected_profile_revision is not None and plan["profile_revision"] != expected_profile_revision:
+ raise ProfileError("profile_changed_after_start_plan", 6)
+ if expected_source_sha256 is not None and digest != expected_source_sha256:
+ raise ProfileError("source_changed_after_start_plan", 6)
+ return plan, digest
+
+
+def start(name: str, *, wait: float = 300, shutdown_timeout: float = 30,
+ expected_profile_revision: str | None = None,
+ expected_source_sha256: str | None = None) -> dict:
+ name = _name(name)
+ if not 0 <= wait <= 600 or not 0 <= shutdown_timeout <= 300:
+ raise ProfileError("start wait must be 0..600 and shutdown timeout 0..300 seconds")
+ if expected_profile_revision is not None and (not isinstance(expected_profile_revision, str) or
+ not re.fullmatch(r"[0-9a-f]{16}", expected_profile_revision)):
+ raise ProfileError("expected profile revision must be 16 lowercase hex characters")
+ if expected_source_sha256 is not None and (not isinstance(expected_source_sha256, str) or
+ not re.fullmatch(r"[0-9a-f]{64}", expected_source_sha256)):
+ raise ProfileError("expected source digest must be 64 lowercase hex characters")
+ plan, _ = _check_start_candidate(name, expected_profile_revision, expected_source_sha256)
+ _, _, log_path = _paths(name)
+ flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND
+ if hasattr(os, "O_NOFOLLOW"):
+ flags |= os.O_NOFOLLOW
+ lock_name = "rt" + hashlib.sha256(name.encode("utf-8")).hexdigest()[:24]
+ with profiles._lock(lock_name):
+ if expected_profile_revision is not None or expected_source_sha256 is not None:
+ _check_start_candidate(name, expected_profile_revision, expected_source_sha256)
+ if _read_state(name) is not None:
+ _recover_stale(name, wait=wait)
+ descriptor = os.open(log_path, flags, 0o600)
+ with os.fdopen(descriptor, "ab") as stream:
+ command = [sys.executable, "-m", "strata_control.runtime", "--host", name,
+ "--shutdown-timeout", str(shutdown_timeout),
+ "--startup-wait", str(wait if wait else 300)]
+ if expected_profile_revision is not None:
+ command += ["--expected-profile-revision", expected_profile_revision]
+ if expected_source_sha256 is not None:
+ command += ["--expected-source-sha256", expected_source_sha256]
+ proc = subprocess.Popen(command,
+ cwd=ROOT, stdin=subprocess.DEVNULL, stdout=stream,
+ stderr=subprocess.STDOUT, start_new_session=True, close_fds=True)
+ _STARTED_HOSTS[name] = proc
+ deadline = time.monotonic() + max(5.0, wait)
+ while _read_state(name) is None and proc.poll() is None and time.monotonic() < deadline:
+ time.sleep(0.05)
+ if _read_state(name) is None:
+ if proc.poll() is not None:
+ _STARTED_HOSTS.pop(name, None)
+ raise ProfileError("runtime host failed to start; inspect " + str(log_path), 6)
+ if wait == 0:
+ return {"ok": True, "profile": name, "state": "starting", "plan": plan}
+ deadline = time.monotonic() + wait
+ while time.monotonic() < deadline:
+ result = _rpc(name, "status")
+ if result.get("state") in ("ready", "failed"):
+ return {**result, "ok": result["state"] == "ready",
+ "exit_code": 6 if result["state"] == "failed" else 0}
+ time.sleep(0.2)
+ return {"ok": False, "profile": name, "state": "starting", "error": "startup_wait_expired",
+ "exit_code": 8}
+
+
+def plan_stop(name: str) -> dict:
+ current = status(_name(name))
+ if current.get("state") not in ("ready", "starting", "failed") or not current.get("owner_id"):
+ return {"ok": False, "profile": name, "state": current.get("state", "unknown"),
+ "error": "runtime_not_owned", "exit_code": 6}
+ return {"ok": True, "plan": {"profile": name, "state": current["state"],
+ "owner_id": current["owner_id"],
+ "instance_id": current.get("instance_id"),
+ "profile_revision": current.get("profile_revision"),
+ "would_drain": False, "would_stop": False}}
+
+
+def stop(name: str, *, timeout: float = 330,
+ expected_owner_id: str | None = None,
+ expected_instance_id: str | None = None) -> dict:
+ if not 1 <= timeout <= 600:
+ raise ProfileError("stop wait must be 1..600 seconds")
+ name = _name(name)
+ if expected_owner_id is not None and (not isinstance(expected_owner_id, str) or
+ not re.fullmatch(r"[0-9a-f]{32}", expected_owner_id)):
+ raise ProfileError("expected owner ID must be 32 lowercase hex characters")
+ if expected_instance_id is not None and (not isinstance(expected_instance_id, str) or
+ not re.fullmatch(r"[0-9a-f]{32}", expected_instance_id)):
+ raise ProfileError("expected instance ID must be 32 lowercase hex characters")
+ params = {"expected_owner_id": expected_owner_id,
+ "expected_instance_id": expected_instance_id}
+ result = _rpc(name, "stop", timeout=timeout, params=params)
+ if not result["ok"]:
+ return result
+ owned = _STARTED_HOSTS.pop(name, None)
+ if owned is not None:
+ try:
+ owned.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ _STARTED_HOSTS[name] = owned
+ return result
+
+
+def verify(name: str, *, timeout: float = 300, load: bool = False,
+ expected_owner_id: str | None = None,
+ expected_instance_id: str | None = None) -> dict:
+ if not 1 <= timeout <= 600 or type(load) is not bool:
+ raise ProfileError("verify wait must be 1..600 seconds and load must be true or false")
+ for label, identity in (("owner", expected_owner_id), ("instance", expected_instance_id)):
+ if identity is not None and (not isinstance(identity, str) or
+ not re.fullmatch(r"[0-9a-f]{32}", identity)):
+ raise ProfileError(f"expected {label} ID must be 32 lowercase hex characters")
+ return _rpc(_name(name), "verify", timeout=timeout + 5,
+ params={"wait": timeout, "load": load,
+ "expected_owner_id": expected_owner_id,
+ "expected_instance_id": expected_instance_id})
+
+
+def restart(name: str, *, timeout: float = 1000, startup_wait: float = 300,
+ expected_profile_revision: str | None = None,
+ expected_owner_id: str | None = None,
+ expected_instance_id: str | None = None,
+ allow_source_switch: bool = False,
+ allow_source_migration: bool = False,
+ expected_source_sha256: str | None = None) -> dict:
+ if (not 1 <= timeout <= 1800 or not 1 <= startup_wait <= 600 or
+ type(allow_source_switch) is not bool or type(allow_source_migration) is not bool):
+ raise ProfileError("restart wait must be 1..1800 and startup wait 1..600 seconds")
+ if expected_source_sha256 is not None and (not isinstance(expected_source_sha256, str) or
+ not re.fullmatch(r"[0-9a-f]{64}", expected_source_sha256)):
+ raise ProfileError("expected source SHA-256 must be 64 lowercase hex characters")
+ for label, identity in (("owner", expected_owner_id), ("instance", expected_instance_id)):
+ if identity is not None and (not isinstance(identity, str) or
+ not re.fullmatch(r"[0-9a-f]{32}", identity)):
+ raise ProfileError(f"expected {label} ID must be 32 lowercase hex characters")
+ if (allow_source_switch or allow_source_migration) and expected_source_sha256 is None:
+ raise ProfileError("source change needs the candidate SHA-256 from runtime restart --plan")
+ params = {"startup_wait": startup_wait, "allow_source_switch": allow_source_switch,
+ "allow_source_migration": allow_source_migration}
+ if expected_source_sha256 is not None:
+ params["expected_source_sha256"] = expected_source_sha256
+ if expected_profile_revision is not None:
+ params["expected_profile_revision"] = expected_profile_revision
+ if expected_owner_id is not None:
+ params["expected_owner_id"] = expected_owner_id
+ if expected_instance_id is not None:
+ params["expected_instance_id"] = expected_instance_id
+ return _rpc(_name(name), "restart", timeout=timeout, params=params)
+
+
+def plan_restart(name: str, *, allow_source_switch: bool = False,
+ allow_source_migration: bool = False) -> dict:
+ if type(allow_source_switch) is not bool or type(allow_source_migration) is not bool:
+ raise ProfileError("source change options must be true or false")
+ return _rpc(_name(name), "plan_restart", timeout=10,
+ params={"allow_source_switch": allow_source_switch,
+ "allow_source_migration": allow_source_migration})
+
+
+class Host:
+ def __init__(self, name: str, shutdown_timeout: float, startup_wait: float = 300,
+ expected_profile_revision: str | None = None,
+ expected_source_sha256: str | None = None):
+ self.name = _name(name)
+ self.shutdown_timeout = shutdown_timeout
+ self.expected_profile_revision = expected_profile_revision
+ self.expected_source_sha256 = expected_source_sha256
+ self.state_path, self.socket_path, self.log_path = _paths(name)
+ self.token = secrets.token_hex(32)
+ self.owner_id = uuid.uuid4().hex
+ self.child: subprocess.Popen | None = None
+ self.ready_path: Path | None = None
+ self.args: list[str] | None = None
+ self.source: Path | None = None
+ self.source_bytes: bytes | None = None
+ self.expected_attestation: str | None = None
+ self.revision: str | None = None
+ self.last_error: str | None = None
+ self.running = True
+ self.state_fd: int | None = None
+ self.owner_write_fd: int | None = None
+ self.probe_timeout = startup_wait
+ self.probe_deadline = 0.0
+ self.probe_key: tuple[int, str] | None = None
+ self.probe_result: dict | None = None
+ self.rollback_snapshots: set[Path] = set()
+
+ def _mark_child(self, phase: str, *, pid: int | None = None, ready: Path | None = None) -> None:
+ payload = {"host_token": self.token, "phase": phase}
+ if pid is not None and ready is not None:
+ payload.update(pid=pid, ready=str(ready))
+ profiles._atomic(_child_marker(self.name, self.token), (json.dumps(payload) + "\n").encode())
+
+ def _plan(self) -> tuple[dict, list[str], Path, bytes]:
+ from strata_cli.cli import _launch_plan
+ plan, args = _launch_plan(self.name)
+ source = Path(plan["source_config"])
+ return plan, args, source, source.read_bytes()
+
+ def _source_change_check(self, source: Path, source_bytes: bytes,
+ allow_source_switch: bool,
+ allow_source_migration: bool) -> tuple[bool, bool, str | None]:
+ """Identify when rollback needs an owner-private copy of the running config."""
+ if source == self.source:
+ migrated = source_bytes != self.source_bytes
+ return False, migrated, ("source_config_changed_restart_requires_migration"
+ if migrated and not allow_source_migration else None)
+ if not allow_source_switch:
+ return True, False, "source_switch_requires_opt_in"
+ try:
+ old_stat, new_stat = self.source.lstat(), source.lstat()
+ if (not stat.S_ISREG(old_stat.st_mode) or not stat.S_ISREG(new_stat.st_mode) or
+ (old_stat.st_dev, old_stat.st_ino) == (new_stat.st_dev, new_stat.st_ino)):
+ return True, False, "source_switch_requires_distinct_regular_files"
+ migrated = self.source.read_bytes() != self.source_bytes
+ except OSError:
+ return True, False, "rollback_source_unavailable"
+ return True, migrated, ("rollback_source_changed" if migrated and not allow_source_migration else None)
+
+ def _snapshot_running_config(self) -> Path:
+ """Save launch bytes before drain; never overwrite the operator's edited file."""
+ path = self.state_path.parent / f"{self.name}-{self.token}-{uuid.uuid4().hex}.rollback.json"
+ descriptor = _write_new(path, self.source_bytes)
+ os.close(descriptor)
+ self.rollback_snapshots.add(path)
+ return path
+
+ def _retire_snapshot(self, path: Path) -> bool:
+ if path in self.rollback_snapshots:
+ try:
+ path.unlink(missing_ok=True)
+ except OSError:
+ return False
+ self.rollback_snapshots.discard(path)
+ return True
+
+ @staticmethod
+ def _config_args(args: list[str], source: Path) -> list[str]:
+ result = list(args)
+ try:
+ index = result.index("--config")
+ result[index + 1] = str(source)
+ except (ValueError, IndexError):
+ raise ProfileError("owned launch has no run config argument", 6) from None
+ return result
+
+ def _launch(self, args: list[str], source: Path, source_bytes: bytes,
+ revision: str | None) -> None:
+ ready = self.state_path.parent / f"{self.name}-{uuid.uuid4().hex}.ready.json"
+ flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND
+ if hasattr(os, "O_NOFOLLOW"):
+ flags |= os.O_NOFOLLOW
+ log = self.state_path.parent / f"{self.name}.server.log"
+ self._mark_child("launching")
+ descriptor = os.open(log, flags, 0o600)
+ reader, writer = os.pipe()
+ server_args = [*args, "--ready-file", str(ready),
+ "--shutdown-timeout", str(self.shutdown_timeout),
+ "--owner-fd", str(reader)]
+ attestation_key = secrets.token_bytes(32)
+ expected_attestation = launch_identity.attestation(attestation_key, source_bytes, server_args)
+ child_env = os.environ.copy()
+ child_env["STRATA_OWNER_ATTEST_KEY"] = attestation_key.hex()
+ try:
+ with os.fdopen(descriptor, "ab") as stream:
+ self.child = subprocess.Popen([sys.executable, "-m", "serve.server", *server_args],
+ cwd=ROOT, stdin=subprocess.DEVNULL, stdout=stream,
+ stderr=subprocess.STDOUT, close_fds=True,
+ pass_fds=(reader,), start_new_session=True, env=child_env)
+ except BaseException:
+ os.close(writer)
+ raise
+ finally:
+ os.close(reader)
+ self.owner_write_fd = writer
+ try:
+ self._mark_child("owned", pid=self.child.pid, ready=ready)
+ except BaseException:
+ # No ownership record means a future start cannot safely reclaim
+ # this instance. Stop this child immediately instead.
+ os.killpg(self.child.pid, signal.SIGKILL)
+ self.child.wait(timeout=10)
+ self._close_owner_pipe()
+ raise
+ self.ready_path = ready
+ self.args, self.source, self.source_bytes, self.revision = list(args), source, source_bytes, revision
+ self.expected_attestation = expected_attestation
+ self.last_error = None
+ self.probe_deadline = time.monotonic() + self.probe_timeout
+ self.probe_key = None
+ self.probe_result = None
+
+ def _verify_ready(self, ready: dict, key: tuple[int, str], host: str, source_bytes: bytes,
+ expected_attestation: str, timeout: float) -> None:
+ try:
+ result = readiness.verify(ready, source_bytes, expected_host=host,
+ expected_instance=key[1],
+ expected_attestation=expected_attestation, timeout=timeout)
+ except readiness.ReadinessError as exc:
+ result = {"error": str(exc)}
+ except Exception:
+ result = {"error": "probe_internal_error"}
+ if self.probe_key == key:
+ self.probe_result = result
+ if "error" in result:
+ self.last_error = result["error"]
+
+ def _status(self) -> dict:
+ child = self.child
+ base = {"ok": True, "profile": self.name, "host_pid": os.getpid(),
+ "owner_id": self.owner_id,
+ "child_pid": child.pid if child else None, "profile_revision": self.revision,
+ "shutdown_timeout": self.shutdown_timeout}
+ if child is None:
+ if self.last_error is not None:
+ return {**base, "ok": False, "state": "failed", "error": self.last_error, "exit_code": 6}
+ return {**base, "state": "stopped"}
+ if child.poll() is not None:
+ return {**base, "ok": False, "state": "failed", "exit_code": child.returncode,
+ "error": self.last_error or "server_exited"}
+ if self.ready_path is not None:
+ try:
+ ready = json.loads(self.ready_path.read_text(encoding="utf-8"))
+ if ready.get("pid") == child.pid and isinstance(ready.get("instance_id"), str):
+ key = (child.pid, ready["instance_id"])
+ if self.probe_key != key:
+ self.probe_key, self.probe_result = key, None
+ host = self.args[self.args.index("--host") + 1]
+ threading.Thread(target=self._verify_ready,
+ args=(ready, key, host, self.source_bytes,
+ self.expected_attestation,
+ max(0.1, self.probe_deadline - time.monotonic())),
+ name="strata-generation-probe", daemon=True).start()
+ if self.probe_result is None:
+ return {**base, "state": "starting", "phase": "verifying_generation",
+ "instance_id": ready["instance_id"]}
+ if "error" in self.probe_result:
+ return {**base, "ok": False, "state": "failed", "error": self.probe_result["error"],
+ "exit_code": 6, "instance_id": ready["instance_id"]}
+ return {**base, "state": "ready", "instance_id": ready["instance_id"],
+ "model_state": ready.get("model_state"),
+ **self.probe_result}
+ except (OSError, ValueError):
+ pass
+ return {**base, "state": "starting"}
+
+ def _wait_ready(self, timeout: float) -> dict:
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ current = self._status()
+ if current["state"] in ("ready", "failed"):
+ return current
+ time.sleep(0.15)
+ current = self._status()
+ if current["state"] in ("ready", "failed"):
+ return current
+ return {**current, "ok": False, "error": "startup_wait_expired", "exit_code": 8}
+
+ def _stop_child(self) -> dict:
+ child = self.child
+ if child is None or child.poll() is not None:
+ self._close_owner_pipe()
+ if self.ready_path is not None:
+ self.ready_path.unlink(missing_ok=True)
+ return {"ok": True, "state": "stopped", "exit_code": child.returncode if child else 0}
+ child.send_signal(signal.SIGTERM)
+ try:
+ code = child.wait(timeout=self.shutdown_timeout + 8)
+ except subprocess.TimeoutExpired:
+ os.killpg(child.pid, signal.SIGKILL)
+ child.wait(timeout=10)
+ self._close_owner_pipe()
+ return {"ok": False, "state": "failed", "error": "server_stop_deadline_expired", "exit_code": 8}
+ self._close_owner_pipe()
+ if self.ready_path is not None:
+ self.ready_path.unlink(missing_ok=True)
+ return {"ok": code == 0, "state": "stopped" if code == 0 else "failed",
+ "exit_code": code, "error": None if code == 0 else "server_stop_failed"}
+
+ def _close_owner_pipe(self) -> None:
+ if self.owner_write_fd is not None:
+ os.close(self.owner_write_fd)
+ self.owner_write_fd = None
+
+ def _restart(self, startup_wait: float, expected_profile_revision: str | None = None,
+ allow_source_switch: bool = False,
+ allow_source_migration: bool = False,
+ expected_source_sha256: str | None = None,
+ expected_owner_id: str | None = None,
+ expected_instance_id: str | None = None) -> dict:
+ old = self._status()
+ if expected_owner_id is not None and old.get("owner_id") != expected_owner_id:
+ return {"ok": False, "error": "owner_changed_after_restart_plan", "exit_code": 6}
+ if expected_instance_id is not None and old.get("instance_id") != expected_instance_id:
+ return {"ok": False, "error": "instance_changed_after_restart_plan", "exit_code": 6}
+ if old["state"] != "ready":
+ return {"ok": False, "state": old["state"], "error": "runtime_not_ready", "exit_code": 6}
+ try:
+ plan, new_args, source, source_bytes = self._plan()
+ except (ProfileError, OSError):
+ return {"ok": False, "state": "ready", "error": "new_profile_preflight_failed", "exit_code": 5}
+ switched, migrated, source_error = self._source_change_check(
+ source, source_bytes, allow_source_switch, allow_source_migration)
+ if source_error:
+ return {"ok": False, "state": "ready", "error": source_error, "exit_code": 6}
+ if expected_source_sha256 is not None and \
+ hashlib.sha256(source_bytes).hexdigest() != expected_source_sha256:
+ return {"ok": False, "state": "ready", "error": "source_changed_after_preview", "exit_code": 6}
+ if expected_profile_revision is not None and plan["profile_revision"] != expected_profile_revision:
+ return {"ok": False, "state": "ready", "error": "profile_changed_after_preview", "exit_code": 6}
+ current = self._status()
+ if expected_instance_id is not None and current.get("instance_id") != expected_instance_id:
+ return {"ok": False, "error": "instance_changed_after_restart_plan", "exit_code": 6}
+ if current["state"] != "ready":
+ return {"ok": False, "state": current["state"], "error": "runtime_not_ready", "exit_code": 6}
+ old_args, old_source, old_bytes, old_revision = self.args, self.source, self.source_bytes, self.revision
+ rollback_source = old_source
+ rollback_args = old_args
+ if migrated:
+ try:
+ rollback_source = self._snapshot_running_config()
+ rollback_args = self._config_args(old_args, rollback_source)
+ except (OSError, ProfileError):
+ if rollback_source != old_source:
+ self._retire_snapshot(rollback_source)
+ return {"ok": False, "state": "ready", "error": "rollback_snapshot_failed", "exit_code": 6}
+ self.probe_timeout = startup_wait
+ stopped = self._stop_child()
+ if not stopped["ok"]:
+ return {**stopped, "profile": self.name, "previous_instance_id": old.get("instance_id")}
+ try:
+ if source.read_bytes() != source_bytes:
+ raise ProfileError("source changed during drain", 6)
+ self._launch(new_args, source, source_bytes, plan["profile_revision"])
+ result = self._wait_ready(startup_wait)
+ if result.get("ok") and result["state"] == "ready":
+ cleanup_ok = True
+ if rollback_source != source:
+ cleanup_ok = self._retire_snapshot(rollback_source) and cleanup_ok
+ if old_source != source:
+ cleanup_ok = self._retire_snapshot(old_source) and cleanup_ok
+ return {**result, "previous_instance_id": old.get("instance_id"), "restarted": True,
+ "source_switched": switched, "source_migrated": migrated,
+ "rollback_snapshot_cleanup_pending": not cleanup_ok}
+ if self.child is not None and self.child.poll() is None:
+ self._stop_child()
+ except (ProfileError, OSError):
+ result = {"state": "failed", "error": "new_instance_launch_failed", "exit_code": 6}
+ # The old launch needs its original bytes, even if the operator edited
+ # the same file. A private snapshot is used only for explicit migration.
+ try:
+ old_source_unchanged = rollback_source.read_bytes() == old_bytes
+ except OSError:
+ old_source_unchanged = False
+ if old_source_unchanged:
+ try:
+ self._launch(rollback_args, rollback_source, old_bytes, old_revision)
+ rollback = self._wait_ready(startup_wait)
+ except (OSError, ProfileError):
+ rollback = {"state": "failed"}
+ if rollback.get("ok") and rollback.get("state") == "ready":
+ cleanup_ok = True
+ if old_source != rollback_source:
+ cleanup_ok = self._retire_snapshot(old_source)
+ return {"ok": False, "state": "ready", "error": result.get("error", "new_instance_failed"),
+ "exit_code": 6, "rolled_back": True,
+ "rollback_snapshot_cleanup_pending": not cleanup_ok,
+ "rollback_source_config": str(rollback_source),
+ "instance_id": rollback.get("instance_id"),
+ "previous_instance_id": old.get("instance_id")}
+ return {"ok": False, "state": "failed", "error": result.get("error", "restart_failed"),
+ "exit_code": 6, "rolled_back": False}
+
+ def _plan_restart(self, allow_source_switch: bool = False,
+ allow_source_migration: bool = False) -> dict:
+ current = self._status()
+ if current["state"] != "ready":
+ return {"ok": False, "state": current["state"], "error": "runtime_not_ready", "exit_code": 6}
+ try:
+ plan, candidate_args, source, source_bytes = self._plan()
+ except (ProfileError, OSError):
+ return {"ok": False, "state": "ready", "error": "new_profile_preflight_failed", "exit_code": 5}
+ switched, migrated, source_error = self._source_change_check(
+ source, source_bytes, allow_source_switch, allow_source_migration)
+ if source_error:
+ return {"ok": False, "state": "ready", "error": source_error, "exit_code": 6,
+ "source_switch": switched, "source_migration": migrated,
+ "requires_allow_source_switch": switched and not allow_source_switch,
+ "requires_allow_source_migration": migrated and not allow_source_migration}
+ from strata_cli.cli import _redact_argv
+ return {"ok": True, "state": "ready", "profile": self.name,
+ "current_owner_id": current["owner_id"],
+ "current_instance_id": current["instance_id"],
+ "current_profile_revision": self.revision,
+ "candidate_profile_revision": plan["profile_revision"],
+ "current_source_config": str(self.source), "candidate_source_config": str(source),
+ "current_source_sha256": hashlib.sha256(self.source_bytes).hexdigest(),
+ "candidate_source_sha256": hashlib.sha256(source_bytes).hexdigest(),
+ "source_switch": switched, "source_migration": migrated,
+ "rollback_snapshot_required": migrated,
+ "current_server_argv": _redact_argv(self.args),
+ "candidate_server_argv": _redact_argv(candidate_args),
+ "changed": switched or migrated or self.args != candidate_args or
+ self.revision != plan["profile_revision"],
+ "shutdown_timeout": self.shutdown_timeout,
+ "would_drain": False, "would_start": False}
+
+ def _handle(self, request: dict) -> dict:
+ if not secrets.compare_digest(str(request.get("token", "")), self.token):
+ return {"ok": False, "error": "unauthorized", "exit_code": 4}
+ command = request.get("command")
+ if command == "status":
+ return self._status()
+ if command == "verify":
+ timeout, force_load = request.get("wait", 300), request.get("load", False)
+ if type(timeout) not in (int, float) or not 1 <= timeout <= 600 or type(force_load) is not bool:
+ return {"ok": False, "error": "invalid_verification_options", "exit_code": 2}
+ owner = request.get("expected_owner_id")
+ instance = request.get("expected_instance_id")
+ for label, identity in (("owner", owner), ("instance", instance)):
+ if identity is not None and (not isinstance(identity, str) or
+ not re.fullmatch(r"[0-9a-f]{32}", identity)):
+ return {"ok": False, "error": f"invalid_expected_{label}_id", "exit_code": 2}
+ if (owner is None) != (instance is None):
+ return {"ok": False, "error": "verification_requires_both_identities", "exit_code": 2}
+ current = self._status()
+ if owner is not None and owner != self.owner_id:
+ return {"ok": False, "error": "owner_changed_after_verify_plan", "exit_code": 6}
+ if instance is not None and current.get("instance_id") != instance:
+ return {"ok": False, "error": "instance_changed_after_verify_plan", "exit_code": 6}
+ if current["state"] != "ready" or self.ready_path is None or self.child is None:
+ return {"ok": False, "state": current["state"], "error": "runtime_not_ready", "exit_code": 6}
+ try:
+ ready = json.loads(self.ready_path.read_text(encoding="utf-8"))
+ if ready.get("pid") != self.child.pid or ready.get("instance_id") != current["instance_id"]:
+ raise readiness.ReadinessError("probe_instance_mismatch")
+ host = self.args[self.args.index("--host") + 1]
+ result = readiness.verify(ready, self.source_bytes, expected_host=host,
+ expected_instance=current["instance_id"],
+ expected_attestation=self.expected_attestation, timeout=timeout,
+ force_load=force_load)
+ except readiness.ReadinessError as exc:
+ return {"ok": False, "state": current["state"], "instance_id": current["instance_id"],
+ "error": str(exc), "exit_code": 6}
+ except (OSError, ValueError):
+ return {"ok": False, "state": current["state"], "instance_id": current["instance_id"],
+ "error": "probe_invalid_ready_file", "exit_code": 6}
+ if self.probe_key == (self.child.pid, current["instance_id"]):
+ self.probe_result = result
+ return {**self._status(), "verified_now": True}
+ if command == "stop":
+ owner = request.get("expected_owner_id")
+ instance = request.get("expected_instance_id")
+ if owner is not None and (not isinstance(owner, str) or
+ not re.fullmatch(r"[0-9a-f]{32}", owner)):
+ return {"ok": False, "error": "invalid_expected_owner_id", "exit_code": 2}
+ if instance is not None and (not isinstance(instance, str) or
+ not re.fullmatch(r"[0-9a-f]{32}", instance)):
+ return {"ok": False, "error": "invalid_expected_instance_id", "exit_code": 2}
+ if owner is not None and owner != self.owner_id:
+ return {"ok": False, "error": "owner_changed_after_stop_plan", "exit_code": 6}
+ if instance is not None and self._status().get("instance_id") != instance:
+ return {"ok": False, "error": "instance_changed_after_stop_plan", "exit_code": 6}
+ result = self._stop_child()
+ self.running = False
+ return {**result, "profile": self.name}
+ if command == "restart":
+ startup_wait = request.get("startup_wait", 300)
+ if type(startup_wait) not in (int, float) or not 1 <= startup_wait <= 600:
+ return {"ok": False, "error": "invalid_startup_wait", "exit_code": 2}
+ revision = request.get("expected_profile_revision")
+ if revision is not None and (not isinstance(revision, str) or
+ not re.fullmatch(r"[0-9a-f]{16}", revision)):
+ return {"ok": False, "error": "invalid_profile_revision", "exit_code": 2}
+ allow_source_switch = request.get("allow_source_switch", False)
+ if type(allow_source_switch) is not bool:
+ return {"ok": False, "error": "invalid_source_switch_option", "exit_code": 2}
+ allow_source_migration = request.get("allow_source_migration", False)
+ if type(allow_source_migration) is not bool:
+ return {"ok": False, "error": "invalid_source_migration_option", "exit_code": 2}
+ expected_source_sha256 = request.get("expected_source_sha256")
+ if (allow_source_switch or allow_source_migration) and \
+ (not isinstance(expected_source_sha256, str) or
+ not re.fullmatch(r"[0-9a-f]{64}", expected_source_sha256)):
+ return {"ok": False, "error": "source_change_needs_candidate_digest", "exit_code": 2}
+ if expected_source_sha256 is not None and (not isinstance(expected_source_sha256, str) or
+ not re.fullmatch(r"[0-9a-f]{64}", expected_source_sha256)):
+ return {"ok": False, "error": "invalid_source_digest", "exit_code": 2}
+ expected_owner_id = request.get("expected_owner_id")
+ expected_instance_id = request.get("expected_instance_id")
+ if expected_owner_id is not None and (not isinstance(expected_owner_id, str) or
+ not re.fullmatch(r"[0-9a-f]{32}", expected_owner_id)):
+ return {"ok": False, "error": "invalid_expected_owner_id", "exit_code": 2}
+ if expected_instance_id is not None and (not isinstance(expected_instance_id, str) or
+ not re.fullmatch(r"[0-9a-f]{32}", expected_instance_id)):
+ return {"ok": False, "error": "invalid_expected_instance_id", "exit_code": 2}
+ return self._restart(startup_wait, revision, allow_source_switch,
+ allow_source_migration, expected_source_sha256,
+ expected_owner_id, expected_instance_id)
+ if command == "plan_restart":
+ allow_source_switch = request.get("allow_source_switch", False)
+ allow_source_migration = request.get("allow_source_migration", False)
+ if type(allow_source_switch) is not bool or type(allow_source_migration) is not bool:
+ return {"ok": False, "error": "invalid_source_change_options", "exit_code": 2}
+ return self._plan_restart(allow_source_switch, allow_source_migration)
+ return {"ok": False, "error": "unsupported_runtime_command", "exit_code": 2}
+
+ def serve(self) -> int:
+ activity_lease = acquire_activity_lease(shared=True)
+ listener = owner_transport.Listener(self.socket_path, timeout=1.0)
+ try:
+ # `bind()` returns the address the client must use, which differs from the requested one
+ # on Windows (the OS assigns the port).
+ bound_address = listener.bind()
+ def shutdown(signum, frame):
+ self.running = False
+ signal.signal(signal.SIGTERM, shutdown)
+ signal.signal(signal.SIGINT, shutdown)
+ self.state_fd = _write_new(self.state_path, (json.dumps({"schema_version": 1, "profile": self.name,
+ "socket": bound_address, "token": self.token,
+ "host_pid": os.getpid()}) + "\n").encode())
+ try:
+ plan, args, source, source_bytes = self._plan()
+ if (self.expected_profile_revision is not None and
+ plan["profile_revision"] != self.expected_profile_revision):
+ raise ProfileError("profile_changed_after_start_plan", 6)
+ if (self.expected_source_sha256 is not None and
+ hashlib.sha256(source_bytes).hexdigest() != self.expected_source_sha256):
+ raise ProfileError("source_changed_after_start_plan", 6)
+ self._launch(args, source, source_bytes, plan["profile_revision"])
+ except (ProfileError, OSError) as exc:
+ self.last_error = str(exc) if isinstance(exc, ProfileError) else type(exc).__name__
+ while self.running:
+ if self.probe_result is not None and "error" in self.probe_result and \
+ self.child is not None and self.child.poll() is None:
+ self._stop_child()
+ try:
+ connection = listener.accept()
+ except socket.timeout:
+ continue
+ if connection is None:
+ # A quiet timeout: the owner loops so it can still service its child.
+ continue
+ with connection:
+ connection.settimeout(5)
+ raw = bytearray()
+ try:
+ while len(raw) <= MAX_MESSAGE and b"\n" not in raw:
+ chunk = connection.recv(4096)
+ if not chunk:
+ break
+ raw.extend(chunk)
+ if len(raw) > MAX_MESSAGE:
+ raise ValueError("message too large")
+ request = json.loads(raw.split(b"\n", 1)[0])
+ if not isinstance(request, dict):
+ raise ValueError("request must be an object")
+ response = self._handle(request)
+ except (OSError, ValueError):
+ response = {"ok": False, "error": "invalid_control_request", "exit_code": 2}
+ try:
+ connection.sendall((json.dumps(response, ensure_ascii=False) + "\n").encode())
+ except OSError:
+ pass
+ finally:
+ if self.child is not None and self.child.poll() is None:
+ self._stop_child()
+ self._close_owner_pipe()
+ listener.close()
+ try:
+ current = _read_state(self.name)
+ if current and current.get("token") == self.token:
+ self.state_path.unlink(missing_ok=True)
+ except ProfileError:
+ pass
+ if not owner_transport.WINDOWS:
+ # POSIX leaves a socket file behind; Windows leaves nothing (the listener's close
+ # releases the port). `Listener.close()` already unlinks the POSIX path, so this is
+ # a second, defensive attempt for the path the caller recorded.
+ Path(self.socket_path).unlink(missing_ok=True)
+ if self.ready_path is not None:
+ self.ready_path.unlink(missing_ok=True)
+ _child_marker(self.name, self.token).unlink(missing_ok=True)
+ for snapshot in tuple(self.rollback_snapshots):
+ self._retire_snapshot(snapshot)
+ if self.state_fd is not None:
+ os.close(self.state_fd)
+ os.close(activity_lease)
+ return 0
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(prog="strata-runtime-host")
+ parser.add_argument("--host", required=True)
+ parser.add_argument("--shutdown-timeout", type=float, default=30)
+ parser.add_argument("--startup-wait", type=float, default=300)
+ parser.add_argument("--expected-profile-revision")
+ parser.add_argument("--expected-source-sha256")
+ args = parser.parse_args(argv)
+ if not 0 <= args.shutdown_timeout <= 300 or not 1 <= args.startup_wait <= 600:
+ parser.error("shutdown timeout must be 0..300")
+ if args.expected_profile_revision is not None and not re.fullmatch(r"[0-9a-f]{16}", args.expected_profile_revision):
+ parser.error("expected profile revision must be 16 lowercase hex characters")
+ if args.expected_source_sha256 is not None and not re.fullmatch(r"[0-9a-f]{64}", args.expected_source_sha256):
+ parser.error("expected source digest must be 64 lowercase hex characters")
+ try:
+ return Host(args.host, args.shutdown_timeout, args.startup_wait,
+ args.expected_profile_revision, args.expected_source_sha256).serve()
+ except (ProfileError, OSError) as exc:
+ print(f"[strata runtime] host failed: {type(exc).__name__}: {exc}", file=sys.stderr)
+ return 6
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/terminal/test_bench.py b/tests/terminal/test_bench.py
new file mode 100644
index 000000000..b4e4f9767
--- /dev/null
+++ b/tests/terminal/test_bench.py
@@ -0,0 +1,699 @@
+"""Serving benchmark evidence with a live mock HTTP server, no model weights."""
+
+import io
+import json
+import os
+import stat
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+import unittest
+from concurrent.futures import ThreadPoolExecutor
+from contextlib import redirect_stdout
+from pathlib import Path
+from unittest import mock
+
+from serve.frontend import ChatTemplate
+from serve.server import ByteTokenizer, IM_END, MockEngine, Service, serve
+from strata_cli import bench
+from strata_cli.cli import main
+from strata_cli.client import Endpoint
+from strata_control import benchmarking, journal, management
+from strata_control.profiles import ProfileError
+
+
+class BenchTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name)
+ tok = ByteTokenizer()
+ service = Service(MockEngine(tok, "Benchmark mock answer.", max_context=4096), tok,
+ ChatTemplate(Path(__file__).resolve().parents[2] / "serve/chat_template.jinja"))
+ service.api_key = "inference-test-secret"
+ service.telemetry_key = "monitor-test-secret"
+ self.service = service
+ self.httpd = serve(service, port=0)
+ self.addCleanup(self.httpd.server_close)
+ self.addCleanup(self.httpd.shutdown)
+ self.url = f"http://127.0.0.1:{self.httpd.server_address[1]}"
+ self.inference = Endpoint(self.url, service.api_key)
+ self.telemetry = Endpoint(self.url, service.telemetry_key)
+
+ def test_live_benchmark_writes_private_report_without_prompt_or_answer(self):
+ out = self.root / "smoke"
+ with redirect_stdout(io.StringIO()):
+ report = bench.run(self.inference, self.telemetry, out, concurrency=2)
+ self.assertTrue(report["successful"])
+ self.assertEqual([p["kind"] for p in report["phases"]], ["warmup", "serial", "mixed"])
+ self.assertEqual(report["phases"][2]["requested"], 2)
+ self.assertEqual(report["phases"][2]["client_workers"], 2)
+ self.assertEqual(report["instance_id"], report["after"]["instance_id"])
+ self.assertTrue(all(r["ttft_s"] is not None and r["completion_tokens"] is not None
+ for p in report["phases"] for r in p["requests"]))
+ contents = (out / "results.json").read_text(encoding="utf-8")
+ for secret in ("inference-test-secret", "monitor-test-secret", "Benchmark mock answer.",
+ "Answer in one sentence"):
+ self.assertNotIn(secret, contents)
+ self.assertIn("prompt_sha256", contents)
+ if os.name != "nt":
+ self.assertEqual(stat.S_IMODE(out.stat().st_mode), 0o700)
+ self.assertEqual(stat.S_IMODE((out / "results.json").stat().st_mode), 0o600)
+ self.assertEqual(bench.summary(bench.load(out))["successful"], True)
+ self.assertEqual(self.telemetry.snapshot()["work"]["client_disconnect_cancels"], 0)
+
+ def test_phase_progress_is_private_and_recovers_from_saved_report(self):
+ output = self.root / "progress"
+ reached = threading.Event()
+ release = threading.Event()
+ original = bench._phase
+
+ def held_phase(*args, **kwargs):
+ if kwargs["kind"] == "mixed":
+ reached.set()
+ if not release.wait(10):
+ raise AssertionError("progress test did not release the mixed phase")
+ return original(*args, **kwargs)
+
+ with mock.patch.object(bench, "_phase", side_effect=held_phase), \
+ ThreadPoolExecutor(max_workers=1) as pool:
+ future = pool.submit(bench.run, self.inference, self.telemetry, output, concurrency=2)
+ try:
+ self.assertTrue(reached.wait(10))
+ active = bench.progress(output)
+ self.assertEqual(active["state"], "running")
+ self.assertEqual(active["completed_phases"], 2)
+ self.assertEqual(active["current_phase"], "mixed")
+ finally:
+ release.set()
+ self.assertTrue(future.result(timeout=10)["successful"])
+ saved = bench.progress(output / "results.json")
+ self.assertEqual(saved["state"], "report_saved")
+ self.assertEqual(saved["completed_phases"], 3)
+ self.assertTrue(saved["successful"])
+ raw = (output / "progress.json").read_text()
+ self.assertNotIn("inference-test-secret", raw)
+ self.assertNotIn("Benchmark mock answer", raw)
+ if os.name == "posix":
+ self.assertEqual(stat.S_IMODE((output / "progress.json").stat().st_mode), 0o600)
+
+ def test_saved_profile_benchmark_lease_refuses_overlap(self):
+ with mock.patch.dict(os.environ, {"STRATA_PROFILE_DIR": str(self.root / "profiles")}):
+ output = self.root / "leased-run"
+ self.assertEqual(benchmarking.benchmark_activity("local", output), "untracked")
+ with benchmarking.benchmark_lease("local", output):
+ self.assertEqual(benchmarking.benchmark_activity("local", output), "active")
+ self.assertEqual(benchmarking.benchmark_activity("local", self.root / "other-run"),
+ "other_active")
+ raw = (self.root / "profiles" / ".bench-local.lock").read_bytes()
+ self.assertNotIn(os.fsencode(str(output)), raw)
+ with self.assertRaisesRegex(ProfileError, "another benchmark is running"):
+ with benchmarking.benchmark_lease("local"):
+ self.fail("overlapping benchmark lease was accepted")
+ self.assertEqual(benchmarking.benchmark_activity("local", output), "ended")
+ self.assertEqual(benchmarking.benchmark_activity("local", self.root / "raw-run"),
+ "untracked")
+ with benchmarking.benchmark_lease("local"):
+ self.assertEqual(benchmarking.benchmark_activity("local", output), "untracked")
+
+ def test_operator_cancel_stops_live_stream_and_saves_distinct_evidence(self):
+ output = self.root / "operator-stopped"
+ self.service.engine.delay = 0.15
+ with mock.patch.dict(os.environ, {"STRATA_PROFILE_DIR": str(self.root / "profiles")}), \
+ ThreadPoolExecutor(max_workers=1) as pool:
+ def execute():
+ with benchmarking.benchmark_lease("local", output):
+ return bench.run(self.inference, self.telemetry, output,
+ concurrency=2, request_timeout=30)
+ started = time.monotonic()
+ future = pool.submit(execute)
+ deadline = started + 10
+ while time.monotonic() < deadline:
+ if output.exists() and self.telemetry.snapshot()["work"]["active"] > 0:
+ break
+ time.sleep(0.05)
+ else:
+ self.fail("benchmark did not enter an active request")
+ wrong = self.root / "another-run"
+ wrong.mkdir(mode=0o700)
+ with self.assertRaisesRegex(ProfileError, "exact benchmark run is not active"):
+ benchmarking.request_cancel("local", wrong)
+ linked = self.root / "linked-run"
+ linked.symlink_to(output, target_is_directory=True)
+ with self.assertRaisesRegex(ProfileError, "owner-only"):
+ benchmarking.request_cancel("local", linked)
+ with mock.patch("strata_control.profiles.load", return_value=({"id": "local"}, "a" * 16)):
+ request = management.dispatch({"schema_version": 1, "action": "bench.cancel",
+ "profile": "local",
+ "params": {"path": str(output / "results.json")}})
+ self.assertEqual(request["state"], "cancel_requested")
+ report = future.result(timeout=10)
+ self.assertLess(time.monotonic() - started, 10)
+ self.assertTrue(report["cancelled"])
+ self.assertFalse(report["successful"])
+ self.assertEqual(bench.progress(output)["state"], "cancelled")
+ self.assertTrue(benchmarking.cancel_requested(output))
+ self.assertTrue(bench.load(output)["cancelled"])
+ self.assertIn("| Result | Cancelled |", bench.markdown_report(report))
+ self.assertEqual(benchmarking.benchmark_activity("local", output), "ended")
+ with self.assertRaisesRegex(ProfileError, "not active"):
+ benchmarking.request_cancel("local", output)
+
+ def test_progress_bridge_reports_exact_run_lease(self):
+ output = self.root / "bridge-progress"
+ with redirect_stdout(io.StringIO()):
+ bench.run(self.inference, self.telemetry, output, concurrency=1)
+ request = {"schema_version": 1, "action": "bench.progress", "profile": "local",
+ "params": {"path": str(output / "results.json")}}
+ with mock.patch.dict(os.environ, {"STRATA_PROFILE_DIR": str(self.root / "profiles")}), \
+ mock.patch("strata_control.profiles.load", return_value=({"id": "local"}, "a" * 16)):
+ with benchmarking.benchmark_lease("local", output):
+ active = management.dispatch(request)
+ self.assertEqual(active["activity"], "active")
+ self.assertEqual(active["progress"]["state"], "report_saved")
+ self.assertEqual(management.dispatch(request)["activity"], "ended")
+
+ def test_durable_benchmark_job_receipt_survives_host_state_loss(self):
+ output = self.root / "durable-job"
+ instance = self.telemetry.snapshot()["instance"]["id"]
+ revision, source = "a" * 16, "b" * 64
+ job_id = "c" * 32
+ params = {"path": str(output), "suite": "serving-smoke", "concurrency": 2,
+ "repeat": 1, "request_timeout": 30, "condition": "baseline",
+ "if_profile_revision": revision, "if_source_sha256": source,
+ "if_owner_id": "d" * 32, "if_instance_id": instance}
+ identity = {"profile": "local", "revision": revision, "source_sha256": source}
+ settings = (None, identity, self.inference, self.telemetry, output)
+ planned = {"profile_revision": revision, "source_sha256": source,
+ "owner_id": "d" * 32, "instance_id": instance}
+ (self.root / "profiles").mkdir(mode=0o700)
+ with mock.patch.dict(os.environ, {"STRATA_PROFILE_DIR": str(self.root / "profiles")}), \
+ mock.patch("strata_control.profiles.load", return_value=({"id": "local"}, revision)), \
+ mock.patch.object(benchmarking, "_settings", return_value=settings), \
+ mock.patch.object(benchmarking, "plan", return_value=planned), \
+ mock.patch.object(bench, "_managed_match", return_value={"matched": True,
+ "instance_id": instance}):
+ created = management.dispatch({"schema_version": 1, "action": "bench.job.create",
+ "profile": "local", "params": {**params, "job_id": job_id}})
+ self.assertEqual(created["job_id"], job_id)
+ self.assertEqual(benchmarking.job_status("local", job_id)["job"]["state"],
+ "launching")
+ real_run = bench.run
+
+ def report_before_worker_receipt(*args, **kwargs):
+ report = real_run(*args, **kwargs)
+ self.assertEqual(benchmarking.job_status("local", job_id)["job"]["state"],
+ "completed")
+ return report
+
+ with mock.patch.object(bench, "run", side_effect=report_before_worker_receipt), \
+ redirect_stdout(io.StringIO()):
+ result = management.dispatch({"schema_version": 1, "action": "bench.run",
+ "profile": "local", "params": {**params, "job_id": job_id}})
+ self.assertTrue(result["successful"])
+ recovered = management.dispatch({"schema_version": 1, "action": "bench.job",
+ "profile": "local", "params": {"job_id": job_id}})["job"]
+ self.assertEqual(recovered["state"], "completed")
+ self.assertTrue(recovered["result"]["successful"])
+ self.assertEqual(recovered["result"]["run_id"], bench.load(output)["run_id"])
+ self.assertEqual(recovered["progress"]["state"], "report_saved")
+ self.assertEqual(journal.load("local", job_id)["state"], "succeeded")
+ self.assertEqual(stat.S_IMODE((self.root / "profiles" / ".ops" / "local" /
+ ".runs" / f"{job_id}.json").stat().st_mode), 0o600)
+
+ failed_path = self.root / "failed-job"
+ failed_params = {**params, "path": str(failed_path)}
+ failed_id = "e" * 32
+ management.dispatch({"schema_version": 1, "action": "bench.job.create",
+ "profile": "local", "params": {**failed_params, "job_id": failed_id}})
+ with mock.patch.object(benchmarking, "plan", side_effect=ProfileError("stale benchmark", 6)):
+ with self.assertRaisesRegex(ProfileError, "stale benchmark"):
+ management.dispatch({"schema_version": 1, "action": "bench.run",
+ "profile": "local", "params": {**failed_params, "job_id": failed_id}})
+ self.assertEqual(benchmarking.job_status("local", failed_id)["job"]["state"], "failed")
+
+ recovered_path = self.root / "report-before-receipt"
+ recovered_params = {**params, "path": str(recovered_path)}
+ recovered_id = "f" * 32
+ management.dispatch({"schema_version": 1, "action": "bench.job.create",
+ "profile": "local", "params": {**recovered_params, "job_id": recovered_id}})
+ with redirect_stdout(io.StringIO()):
+ bench.run(self.inference, self.telemetry, recovered_path, concurrency=2,
+ request_timeout=30, condition="baseline", profile_identity=identity,
+ require_managed_match=True)
+ self.assertEqual(journal.load("local", recovered_id)["state"], "running")
+ self.assertEqual(benchmarking.job_status("local", recovered_id)["job"]["state"],
+ "completed")
+ self.assertEqual(journal.load("local", recovered_id)["state"], "succeeded")
+
+ def test_process_death_releases_exact_run_lease(self):
+ output = self.root / "child-run"
+ ready = self.root / "child-ready"
+ environment = {**os.environ, "STRATA_PROFILE_DIR": str(self.root / "profiles")}
+ code = ("from pathlib import Path\n"
+ "from strata_control.benchmarking import benchmark_lease\n"
+ "from time import sleep\n"
+ f"with benchmark_lease('local', Path({str(output)!r})):\n"
+ f" Path({str(ready)!r}).write_text('ready')\n"
+ " sleep(30)\n")
+ process = subprocess.Popen([sys.executable, "-c", code],
+ cwd=Path(__file__).resolve().parents[2], env=environment,
+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
+ try:
+ deadline = time.monotonic() + 10
+ while not ready.exists() and process.poll() is None and time.monotonic() < deadline:
+ time.sleep(0.05)
+ if not ready.exists():
+ self.fail("benchmark lease child did not become ready: " +
+ (process.stderr.read().decode("utf-8", "replace") if process.poll() is not None else
+ "timed out"))
+ with mock.patch.dict(os.environ, {"STRATA_PROFILE_DIR": environment["STRATA_PROFILE_DIR"]}):
+ self.assertEqual(benchmarking.benchmark_activity("local", output), "active")
+ process.kill()
+ process.wait(timeout=5)
+ self.assertEqual(benchmarking.benchmark_activity("local", output), "ended")
+ finally:
+ if process.poll() is None:
+ process.kill()
+ process.wait(timeout=5)
+ process.stderr.close()
+
+ def test_interrupted_phase_cannot_produce_successful_report(self):
+ output = self.root / "interrupted"
+ original = bench._phase
+
+ def interrupted_phase(*args, **kwargs):
+ if kwargs["kind"] == "serial":
+ raise RuntimeError("synthetic benchmark interruption")
+ return original(*args, **kwargs)
+
+ with mock.patch.object(bench, "_phase", side_effect=interrupted_phase), \
+ redirect_stdout(io.StringIO()):
+ with self.assertRaisesRegex(RuntimeError, "synthetic benchmark interruption"):
+ bench.run(self.inference, self.telemetry, output, concurrency=2)
+ report = bench.load(output)
+ self.assertEqual([p["kind"] for p in report["phases"]], ["warmup"])
+ self.assertEqual(report["planned_phases"], ["warmup", "serial", "mixed"])
+ self.assertFalse(report["successful"])
+ self.assertEqual(bench.summary(report)["completed_phase_count"], 1)
+ self.assertEqual(bench.summary(report)["planned_phase_count"], 3)
+ self.assertIn("| Result | Incomplete |", bench.markdown_report(report))
+ record = bench.progress(output)
+ self.assertEqual(record["state"], "report_saved")
+ self.assertEqual(record["completed_phases"], 1)
+ self.assertEqual(record["current_phase"], None)
+ self.assertFalse(record["successful"])
+ report["successful"] = True
+ (output / "results.json").write_text(json.dumps(report), encoding="utf-8")
+ with self.assertRaisesRegex(ProfileError, "unsupported benchmark report"):
+ bench.load(output)
+ del report["planned_phases"] # Old reports must not claim success for a partial suite either.
+ (output / "results.json").write_text(json.dumps(report), encoding="utf-8")
+ with self.assertRaisesRegex(ProfileError, "unsupported benchmark report"):
+ bench.load(output)
+
+ def test_postflight_telemetry_parse_failure_keeps_failed_evidence(self):
+ output = self.root / "postflight"
+ original = bench._phase
+ postflight = False
+
+ def phase(*args, **kwargs):
+ nonlocal postflight
+ result = original(*args, **kwargs)
+ if kwargs["kind"] == "mixed":
+ postflight = True
+ return result
+
+ def snapshot():
+ if postflight:
+ raise ValueError("malformed postflight telemetry")
+ return self.telemetry.snapshot()
+
+ telemetry = mock.Mock(timeout=self.telemetry.timeout)
+ telemetry.snapshot.side_effect = snapshot
+ with mock.patch.object(bench, "_phase", side_effect=phase), redirect_stdout(io.StringIO()):
+ report = bench.run(self.inference, telemetry, output, concurrency=2)
+ self.assertFalse(report["successful"])
+ self.assertEqual(len(report["phases"]), 3)
+ self.assertEqual(report["after"]["instance_id"], None)
+ self.assertFalse(bench.load(output)["successful"])
+ self.assertEqual(bench.progress(output)["state"], "report_saved")
+
+ def test_auth_failure_is_recorded_and_does_not_claim_success(self):
+ out = self.root / "failed"
+ with redirect_stdout(io.StringIO()):
+ report = bench.run(Endpoint(self.url, "wrong-key"), self.telemetry, out, concurrency=2)
+ self.assertFalse(report["successful"])
+ self.assertTrue((out / "results.json").exists())
+ self.assertTrue(all(r["error_code"] == "authentication_failed"
+ for p in report["phases"] for r in p["requests"]))
+
+ def test_unloaded_model_is_rejected_before_creating_output(self):
+ out = self.root / "unloaded"
+ unloaded = mock.Mock()
+ unloaded.snapshot.return_value = {"instance": {"id": "one"}, "model": {"loaded": False}}
+ with self.assertRaisesRegex(ProfileError, "loaded Strata instance"):
+ bench.run(self.inference, unloaded, out)
+ self.assertFalse(out.exists())
+
+ def test_invalid_condition_is_rejected_before_creating_output(self):
+ out = self.root / "invalid-label"
+ with self.assertRaisesRegex(ProfileError, "condition must be a lowercase name"):
+ bench.run(self.inference, self.telemetry, out, condition="monitor\x1b[31m")
+ self.assertFalse(out.exists())
+
+ def test_run_cli_records_an_operator_condition(self):
+ out = self.root / "cli-baseline"
+ output = io.StringIO()
+ with mock.patch.dict(os.environ, {"STRATA_API_KEY": self.service.api_key}), redirect_stdout(output):
+ code = main(["bench", "run", "--url", self.url, "--condition", "baseline",
+ "--concurrency", "1", "--out", str(out), "--output", "json"])
+ self.assertEqual(code, 0)
+ self.assertEqual(json.loads(output.getvalue())["summary"]["condition"], "baseline")
+ report = bench.load(out)
+ self.assertEqual(report["condition"], "baseline")
+ self.assertTrue(any("monitor attachment is not verified" in note for note in report["limitations"]))
+
+ def test_managed_benchmark_checks_owned_instance_before_and_after(self):
+ identity = {"profile": "local", "revision": "a" * 16,
+ "source_sha256": "b" * 64}
+ instance = self.telemetry.snapshot()["instance"]["id"]
+ owner = {"ok": True, "state": "ready", "launch_attested": True,
+ "api_identity_verified": True, "generation_ready": True,
+ "instance_id": instance, "profile_revision": identity["revision"], "api_url": self.url}
+ plan = {"ok": True, "changed": False, "current_instance_id": instance,
+ "current_profile_revision": identity["revision"],
+ "candidate_profile_revision": identity["revision"]}
+ out = self.root / "managed"
+ with mock.patch("strata_control.runtime.status", return_value=owner) as status, \
+ mock.patch("strata_control.runtime.plan_restart", return_value=plan) as preview, \
+ redirect_stdout(io.StringIO()):
+ report = bench.run(self.inference, self.telemetry, out, concurrency=1,
+ profile_identity=identity, require_managed_match=True)
+ self.assertTrue(report["successful"])
+ self.assertEqual(report["profile_running_match"], "managed_launch_checked")
+ self.assertTrue(report["profile_running_check"]["before"]["matched"])
+ self.assertTrue(report["profile_running_check"]["after"]["matched"])
+ self.assertEqual(bench.summary(report)["profile_running_match"], "managed_launch_checked")
+ self.assertEqual(status.call_count, 2)
+ self.assertEqual(preview.call_count, 2)
+
+ with mock.patch("strata_control.runtime.status", return_value={**owner, "instance_id": "wrong"}), \
+ mock.patch("strata_control.runtime.plan_restart", return_value=plan):
+ rejected = self.root / "rejected"
+ with self.assertRaisesRegex(ProfileError, "managed benchmark preflight failed: instance_mismatch"):
+ bench.run(self.inference, self.telemetry, rejected, concurrency=1,
+ profile_identity=identity, require_managed_match=True)
+ self.assertFalse(rejected.exists())
+
+ with mock.patch("strata_control.runtime.status", return_value=owner), \
+ mock.patch("strata_control.runtime.plan_restart", return_value={**plan, "changed": True}):
+ stale = self.root / "stale"
+ with self.assertRaisesRegex(ProfileError, "managed benchmark preflight failed: profile_or_source_changed"):
+ bench.run(self.inference, self.telemetry, stale, concurrency=1,
+ profile_identity=identity, require_managed_match=True)
+ self.assertFalse(stale.exists())
+
+ with mock.patch("strata_control.runtime.status", side_effect=[owner, {**owner, "instance_id": "wrong"}]), \
+ mock.patch("strata_control.runtime.plan_restart", return_value=plan), \
+ redirect_stdout(io.StringIO()):
+ changed = bench.run(self.inference, self.telemetry, self.root / "changed", concurrency=1,
+ profile_identity=identity, require_managed_match=True)
+ self.assertFalse(changed["successful"])
+ self.assertEqual(changed["profile_running_check"]["after"]["reason"], "instance_mismatch")
+ self.assertTrue((self.root / "changed" / "results.json").is_file())
+
+ def test_managed_match_flag_requires_a_saved_profile(self):
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(["bench", "run", "--url", self.url, "--require-managed-match",
+ "--out", str(self.root / "unused"), "--output", "json"])
+ self.assertEqual(code, 2)
+ self.assertFalse(json.loads(output.getvalue())["ok"])
+ self.assertFalse((self.root / "unused").exists())
+
+ def test_desktop_review_runs_shared_benchmark_and_rejects_changed_owner(self):
+ source = self.root / "run.json"
+ source.write_text("{}", encoding="utf-8")
+ instance = self.telemetry.snapshot()["instance"]["id"]
+ revision = "a" * 16
+ owner_id = ["b" * 32]
+ owner = {"ok": True, "state": "ready", "launch_attested": True,
+ "api_identity_verified": True, "generation_ready": True,
+ "instance_id": instance, "profile_revision": revision, "api_url": self.url}
+ restart = {"ok": True, "changed": False, "current_instance_id": instance,
+ "current_profile_revision": revision, "candidate_profile_revision": revision}
+ launch = {"effective": {"host": "127.0.0.1", "port": self.httpd.server_address[1]}}
+ settings = {"path": str(self.root / "desktop-run"), "suite": "serving-smoke",
+ "concurrency": 2, "repeat": 1, "request_timeout": 120,
+ "condition": "baseline"}
+ def send(action, params):
+ return management.dispatch({"schema_version": 1, "action": action,
+ "profile": "local", "params": params})
+ with mock.patch("strata_control.benchmarking._source", return_value=(
+ source, {"id": "local"}, revision, {"model_name": "test", "gpu": "cpu"})), \
+ mock.patch("strata_control.benchmarking._launch_plan", return_value=(launch, [])), \
+ mock.patch("strata_control.runtime.status", side_effect=lambda _: {
+ **owner, "owner_id": owner_id[0]}), \
+ mock.patch("strata_control.runtime.plan_restart", return_value=restart), \
+ mock.patch.dict(os.environ, {"STRATA_API_KEY": self.service.api_key,
+ "STRATA_TELEMETRY_KEY": self.service.telemetry_key}):
+ reviewed = send("bench.run.plan", settings)["plan"]
+ self.assertEqual(reviewed["planned_requests"], 5)
+ self.assertEqual(reviewed["instance_id"], instance)
+ pinned = {"if_profile_revision": reviewed["profile_revision"],
+ "if_source_sha256": reviewed["source_sha256"],
+ "if_owner_id": reviewed["owner_id"],
+ "if_instance_id": reviewed["instance_id"]}
+ owner_id[0] = "c" * 32
+ with self.assertRaisesRegex(ProfileError, "target changed after review"):
+ send("bench.run", {**settings, **pinned})
+ self.assertFalse(Path(settings["path"]).exists())
+ owner_id[0] = "b" * 32
+ with redirect_stdout(io.StringIO()):
+ result = send("bench.run", {**settings, **pinned})
+ self.assertTrue(result["successful"])
+ self.assertTrue(Path(result["path"]).is_file())
+ self.assertEqual(bench.load(Path(settings["path"]))["profile_running_match"],
+ "managed_launch_checked")
+
+ def test_report_cli_json_and_malformed_report(self):
+ out = self.root / "smoke"
+ with redirect_stdout(io.StringIO()):
+ bench.run(self.inference, self.telemetry, out, concurrency=1)
+ stdout = io.StringIO()
+ with redirect_stdout(stdout):
+ self.assertEqual(main(["bench", "report", str(out), "--output", "json"]), 0)
+ value = json.loads(stdout.getvalue())
+ self.assertTrue(value["ok"])
+ self.assertEqual(value["summary"]["suite"], "serving-smoke")
+ report_file = out / "results.json"
+ data = json.loads(report_file.read_text())
+ for phase in data["phases"]:
+ phase.pop("passed") # reports written before the overload suite remain readable
+ report_file.write_text(json.dumps(data), encoding="utf-8")
+ self.assertTrue(all(phase["passed"] for phase in bench.summary(bench.load(out))["phases"]))
+ data["phases"] = [{"kind": "mixed"}]
+ report_file.write_text(json.dumps(data), encoding="utf-8")
+ with self.assertRaisesRegex(ProfileError, "unsupported benchmark report"):
+ bench.load(out)
+
+ def test_markdown_export_is_local_private_and_keeps_measurement_limits(self):
+ first = self.root / "baseline"
+ second = self.root / "candidate"
+ with redirect_stdout(io.StringIO()):
+ report = bench.run(self.inference, self.telemetry, first, concurrency=1)
+ report["model_id"] = "model | <untrusted>"
+ (first / "results.json").write_text(json.dumps(report), encoding="utf-8")
+ other = json.loads(json.dumps(report))
+ other["run_id"] = "f" * 32
+ second.mkdir()
+ (second / "results.json").write_text(json.dumps(other), encoding="utf-8")
+ share = self.root / "share.md"
+ with mock.patch.object(Endpoint, "snapshot", side_effect=AssertionError("export must stay offline")):
+ with redirect_stdout(io.StringIO()):
+ self.assertEqual(main(["bench", "report", str(first), "--output", "markdown",
+ "--out", str(share)]), 0)
+ comparison = io.StringIO()
+ with redirect_stdout(comparison):
+ self.assertEqual(main(["bench", "compare", str(first), str(second),
+ "--output", "markdown"]), 0)
+ exported = share.read_text(encoding="utf-8")
+ self.assertIn("model \\| \\<untrusted\\>", exported)
+ self.assertIn("Peak slots", exported)
+ self.assertIn("Missing readings appear as `unavailable`", exported)
+ self.assertNotIn(self.url, exported)
+ for secret in ("inference-test-secret", "monitor-test-secret", "Benchmark mock answer.",
+ "Answer in one sentence"):
+ self.assertNotIn(secret, exported)
+ self.assertNotIn(secret, comparison.getvalue())
+ self.assertIn("Provisional comparison", comparison.getvalue())
+ self.assertIn("monitor attachment", comparison.getvalue())
+ original = share.read_bytes()
+ with redirect_stdout(io.StringIO()):
+ self.assertEqual(main(["bench", "report", str(first), "--output", "markdown",
+ "--out", str(share)]), 2)
+ self.assertEqual(share.read_bytes(), original)
+ if os.name != "nt":
+ self.assertEqual(stat.S_IMODE(share.stat().st_mode), 0o600)
+
+ def test_saved_run_comparison_is_read_only_and_provisional(self):
+ baseline_path, candidate_path = self.root / "baseline", self.root / "monitored"
+ with redirect_stdout(io.StringIO()):
+ baseline = bench.run(self.inference, self.telemetry, baseline_path, concurrency=2, repeat=3,
+ condition="baseline")
+ candidate = bench.run(self.inference, self.telemetry, candidate_path, concurrency=2, repeat=3,
+ condition="monitor-default")
+ self.assertTrue(baseline["successful"] and candidate["successful"])
+ before = [(path / "results.json").read_bytes() for path in (baseline_path, candidate_path)]
+ with mock.patch.object(Endpoint, "snapshot", side_effect=AssertionError("compare must not contact server")):
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(["bench", "compare", str(baseline_path), str(candidate_path),
+ "--output", "json"])
+ self.assertEqual(code, 0)
+ comparison = json.loads(output.getvalue())["comparison"]
+ self.assertEqual(comparison["qualification"], "provisional")
+ self.assertTrue(comparison["workload_match"])
+ self.assertEqual(comparison["primary_phases"], 3)
+ self.assertIsNotNone(comparison["median_primary_metrics"]["p95_ttft_s"]["baseline"])
+ self.assertEqual(comparison["baseline"]["condition"], "baseline")
+ self.assertEqual(comparison["candidate"]["condition"], "monitor-default")
+ self.assertTrue(any("monitor attachment" in note for note in comparison["warnings"]))
+ self.assertEqual(before, [(path / "results.json").read_bytes()
+ for path in (baseline_path, candidate_path)])
+ self.assertIn("provisional comparison", bench.format_comparison(comparison))
+ missing = json.loads(json.dumps(candidate))
+ next(phase for phase in missing["phases"] if phase["kind"] == "mixed")["summary"]["p95_ttft_s"] = None
+ self.assertIsNone(bench.compare(baseline, missing)["median_primary_metrics"]["p95_ttft_s"]["candidate"])
+ next(phase for phase in missing["phases"] if phase["kind"] == "mixed")["summary"]["p95_ttft_s"] = 10 ** 400
+ self.assertIsNone(bench.compare(baseline, missing)["median_primary_metrics"]["p95_ttft_s"]["candidate"])
+
+ def test_comparison_rejects_workload_and_identity_mismatch(self):
+ first_path, second_path = self.root / "one", self.root / "two"
+ with redirect_stdout(io.StringIO()):
+ first = bench.run(self.inference, self.telemetry, first_path, concurrency=1)
+ second = bench.run(self.inference, self.telemetry, second_path, concurrency=2)
+ with self.assertRaisesRegex(ProfileError, "workload or concurrency differs"):
+ bench.compare(first, second)
+ second["phases"][2]["requested"] = first["phases"][2]["requested"]
+ second["phases"][2]["client_workers"] = first["phases"][2]["client_workers"]
+ second["phases"][2]["requests"] = first["phases"][2]["requests"]
+ second["environment"]["slots_effective"] = 999
+ with self.assertRaisesRegex(ProfileError, "reported environment differs: slots_effective"):
+ bench.compare(first, second)
+ second["environment"]["slots_effective"] = first["environment"]["slots_effective"]
+ first["profile_identity"] = {"source_sha256": "0" * 64}
+ second["profile_identity"] = {"source_sha256": "1" * 64}
+ with self.assertRaisesRegex(ProfileError, "source config digests differ"):
+ bench.compare(first, second)
+
+ def test_overload_suite_requires_bounded_admission_before_creating_output(self):
+ out = self.root / "overload"
+ with self.assertRaisesRegex(ProfileError, "max_queue and queue_timeout"):
+ bench.run(self.inference, self.telemetry, out, suite="parallel-overload-v1", concurrency=4)
+ self.assertFalse(out.exists())
+ self.service.max_queue = 1
+ self.service.queue_timeout_s = 0.1
+ with self.assertRaisesRegex(ProfileError, "must exceed the admission limit"):
+ bench.run(self.inference, self.telemetry, out, suite="parallel-overload-v1", concurrency=2)
+ self.assertFalse(out.exists())
+
+ def test_cancel_suite_requires_queue_capacity_and_disconnect_telemetry(self):
+ out = self.root / "cancel"
+ with self.assertRaisesRegex(ProfileError, "cancellation suite requires"):
+ bench.run(self.inference, self.telemetry, out, suite="parallel-cancel-v1", concurrency=1)
+ self.assertFalse(out.exists())
+ self.service.max_queue = 1
+ self.service.queue_timeout_s = 0.1
+ with self.assertRaisesRegex(ProfileError, "queue_timeout >= 2"):
+ bench.run(self.inference, self.telemetry, out, suite="parallel-cancel-v1", concurrency=1)
+ self.assertFalse(out.exists())
+
+ def test_prefill_cancel_requires_parallel_engine(self):
+ out = self.root / "prefill"
+ with self.assertRaisesRegex(ProfileError, "at least two effective slots"):
+ bench.run(self.inference, self.telemetry, out, suite="parallel-prefill-cancel-v1", concurrency=2)
+ self.assertFalse(out.exists())
+
+ def test_overload_suite_records_rejections_and_recovery_without_content(self):
+ self.service.max_queue = 1
+ self.service.queue_timeout_s = 0.1
+ self.service.engine.delay = 0.02
+ out = self.root / "overload"
+ with redirect_stdout(io.StringIO()):
+ report = bench.run(self.inference, self.telemetry, out, suite="parallel-overload-v1",
+ concurrency=6)
+ self.assertTrue(report["successful"])
+ self.assertEqual([phase["kind"] for phase in report["phases"]], ["warmup", "overload", "recovery"])
+ overload = report["phases"][1]
+ self.assertTrue(overload["passed"])
+ self.assertEqual(overload["requested"], 6)
+ self.assertGreaterEqual(overload["summary"]["expected_overload"], 1)
+ self.assertEqual(overload["summary"]["expected_overload"],
+ overload["summary"]["admission_full"] + overload["summary"]["queue_wait_timeout"])
+ self.assertEqual(overload["summary"]["failed"], 0)
+ self.assertIsNotNone(overload["summary"]["launch_spread_s"])
+ self.assertEqual(len([row["launch_offset_s"] for row in overload["requests"]]), 6)
+ self.assertTrue(all(row["error_code"] in (None, "admission_full", "queue_wait_timeout")
+ for row in overload["requests"]))
+ self.assertTrue(report["phases"][2]["passed"])
+ data = (out / "results.json").read_text(encoding="utf-8")
+ for secret in ("inference-test-secret", "monitor-test-secret", "Benchmark mock answer.",
+ "Answer in one sentence"):
+ self.assertNotIn(secret, data)
+ loaded = bench.load(out)
+ self.assertEqual(bench.summary(loaded)["phases"][1]["expected_overload"],
+ overload["summary"]["expected_overload"])
+ comparison_shape = json.loads(json.dumps(loaded))
+ comparison_shape["run_id"] = "f" * 32
+ same = bench.compare(loaded, comparison_shape)
+ self.assertEqual(same["primary_kind"], "overload")
+ self.assertIn("admission full", bench.format_comparison(same))
+ human = bench.format_summary(bench.summary(loaded))
+ self.assertIn("rejected", human)
+ self.assertIn("timed out", human)
+ self.assertIn("launch spread", human)
+ self.assertNotIn("Benchmark mock answer", human)
+
+ def test_cancel_suite_observes_active_and_queued_disconnect_and_recovery(self):
+ self.service.max_queue = 1
+ self.service.queue_timeout_s = 5
+ engine = self.service.engine
+ engine.script = engine.tok.encode("A" * 200, parse_special=True) + \
+ engine.tok.encode(IM_END, parse_special=True)
+ engine.delay = 0.01
+ out = self.root / "cancel"
+ with redirect_stdout(io.StringIO()):
+ report = bench.run(self.inference, self.telemetry, out, suite="parallel-cancel-v1",
+ concurrency=1, request_timeout=10)
+ self.assertTrue(report["successful"], bench.format_summary(bench.summary(report)))
+ self.assertEqual([phase["kind"] for phase in report["phases"]],
+ ["warmup", "cancel_active", "cancel_queued", "recovery"])
+ for phase in report["phases"][1:3]:
+ self.assertTrue(phase["passed"])
+ self.assertEqual(phase["summary"]["client_disconnect_delta"], 1)
+ self.assertTrue(phase["summary"]["settled"])
+ self.assertEqual(phase["summary"]["queue_timeouts_delta"], 0)
+ self.assertEqual(report["phases"][2]["summary"]["companion_successful"], 1)
+ data = (out / "results.json").read_text()
+ self.assertNotIn("A" * 50, data)
+ self.assertTrue(bench.load(out)["successful"])
+ comparison_shape = json.loads(json.dumps(report))
+ comparison_shape["run_id"] = "f" * 32
+ comparison = bench.compare(report, comparison_shape)
+ self.assertTrue(comparison["workload_match"])
+ self.assertEqual(comparison["primary_kind"], "cancel_active")
+ self.assertEqual(comparison["phases"][1]["metrics"]["client_disconnect_delta"]["baseline"], 1.0)
+ self.assertIn("disconnects", bench.format_comparison(comparison))
+ corrupt = json.loads(data)
+ corrupt["phases"][1]["summary"].pop("client_disconnect_delta")
+ (out / "results.json").write_text(json.dumps(corrupt))
+ with self.assertRaisesRegex(ProfileError, "unsupported benchmark report"):
+ bench.load(out)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/terminal/test_calibration.py b/tests/terminal/test_calibration.py
new file mode 100644
index 000000000..57186fd98
--- /dev/null
+++ b/tests/terminal/test_calibration.py
@@ -0,0 +1,712 @@
+"""Calibration report binding, review and atomic apply without a GPU."""
+
+import io
+import json
+import os
+import stat
+import subprocess
+import sys
+import tempfile
+import threading
+import unittest
+import uuid
+from contextlib import redirect_stdout
+from pathlib import Path
+from types import SimpleNamespace
+from unittest import mock
+
+from strata_cli.cli import main
+from strata_control import calibration, journal, management, profiles, runtime
+import setup
+
+
+class CalibrationFlowTests(unittest.TestCase):
+ def test_mac_ram_identity_is_available_without_proc_meminfo(self):
+ with mock.patch.object(setup, "WIN", False), \
+ mock.patch.object(setup.sys, "platform", "darwin"), \
+ mock.patch.object(setup.subprocess, "run",
+ return_value=SimpleNamespace(stdout="17179869184\n")):
+ self.assertEqual(setup.ram_gb(), 16.0)
+
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name)
+ patcher = mock.patch.dict(os.environ, {"STRATA_PROFILE_DIR": str(self.root / "profiles"),
+ "STRATA_RUNTIME_DIR": str(self.root / "runtime"),
+ "XDG_CONFIG_HOME": str(self.root / "settings"),
+ "STRATA_API_KEY": ""})
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ engine = self.root / "strata-engine"
+ engine.write_bytes(b"fake engine")
+ engine.chmod(0o700)
+ tokenizer = self.root / "tokenizer"
+ tokenizer.mkdir()
+ for name in ("vocab.json", "merges.txt", "token_type.json"):
+ (tokenizer / name).write_text("{}", encoding="utf-8")
+ (self.root / "pack").mkdir()
+ (self.root / "model.gguf").write_bytes(b"fake model")
+ self.config = self.root / "run.json"
+ self.config.write_text(json.dumps({"exe": str(engine), "tokenizer": str(tokenizer),
+ "args": ["--pack", str(self.root / "pack"),
+ "--native", str(self.root / "model.gguf")],
+ "cwd": str(self.root), "model_name": "test-model", "port": 8095}),
+ encoding="utf-8")
+ profiles.create("local", str(self.config))
+ hardware = mock.patch("strata_control.calibration._hardware_key", return_value="test-gpu|24GB|test-cpu")
+ hardware.start()
+ self.addCleanup(hardware.stop)
+ port = mock.patch("strata_control.calibration._port_active", return_value=False)
+ port.start()
+ self.addCleanup(port.stop)
+
+ def fake_result(self, cfg, say, **_):
+ say("measured fake decode workload")
+ return {"settings": {"--pcie-frac": "0.20"},
+ "report": {"default": {"pcie_frac": 0.55}, "confirm": {"default": [10.0, 10.2, 10.1],
+ "candidate": [12.0, 12.2, 12.1]},
+ "tok_s": 12.1, "seconds": 30}}
+
+ def test_desktop_calibration_receipts_recover_measure_apply_and_rollback(self):
+ def send(action, params):
+ return management.dispatch({"schema_version": 1, "action": action,
+ "profile": "local", "params": params})
+
+ path = self.root / "desktop-calibration.json"
+ plan = send("calibration.plan", {})["plan"]
+ reviewed = {"path": str(path), "exclusive_ack": True,
+ "if_profile_revision": plan["profile_revision"],
+ "if_source_sha256": plan["source_sha256"]}
+ measure_id = uuid.uuid4().hex
+ created = send("calibration.job.create", {"job_id": measure_id, "action": "measure",
+ "if_report_sha256": None, **reviewed})
+ self.assertEqual(created["job_id"], measure_id)
+ self.assertEqual(send("calibration.job", {"job_id": measure_id})["job"]["state"], "launching")
+ with mock.patch("tools.calibrate.run", side_effect=self.fake_result), \
+ mock.patch("strata_control.calibration._smoke", return_value=2):
+ measured = send("calibration.measure", {**reviewed, "job_id": measure_id})
+ self.assertEqual(measured["operation_id"], measure_id)
+ recovered = send("calibration.job", {"job_id": measure_id})["job"]
+ self.assertEqual(recovered["state"], "succeeded")
+ self.assertEqual(recovered["result"]["settings"], {"--pcie-frac": "0.20"})
+
+ apply_plan = send("calibration.apply.plan", {"path": str(path)})
+ apply = {**reviewed, "if_profile_revision": apply_plan["profile_revision"],
+ "if_source_sha256": apply_plan["source_sha256"],
+ "if_report_sha256": apply_plan["report_sha256"]}
+ apply_id = uuid.uuid4().hex
+ send("calibration.job.create", {"job_id": apply_id, "action": "apply", **apply})
+ with self.assertRaisesRegex(profiles.ProfileError, "only calibration measurement"):
+ send("calibration.cancel", {"job_id": apply_id})
+ self.assertEqual(send("calibration.apply", {**apply, "job_id": apply_id})["operation_id"], apply_id)
+ self.assertTrue(send("calibration.job", {"job_id": apply_id})["job"]["result"]["changed"])
+
+ rollback_plan = send("calibration.rollback.plan", {"path": str(path)})
+ rollback = {**reviewed, "if_profile_revision": rollback_plan["profile_revision"],
+ "if_source_sha256": rollback_plan["source_sha256"],
+ "if_report_sha256": rollback_plan["report_sha256"]}
+ rollback_id = uuid.uuid4().hex
+ send("calibration.job.create", {"job_id": rollback_id, "action": "rollback", **rollback})
+ self.assertEqual(send("calibration.rollback", {**rollback, "job_id": rollback_id})["operation_id"],
+ rollback_id)
+ self.assertTrue(send("calibration.job", {"job_id": rollback_id})["job"]["result"]["changed"])
+
+ def test_saved_measurement_reconciles_exact_unfinished_job(self):
+ def send(action, params):
+ return management.dispatch({"schema_version": 1, "action": action,
+ "profile": "local", "params": params})
+
+ path = self.root / "recovered-calibration.json"
+ plan = send("calibration.plan", {})["plan"]
+ job_id = uuid.uuid4().hex
+ reviewed = {"job_id": job_id, "action": "measure", "path": str(path),
+ "exclusive_ack": True, "if_profile_revision": plan["profile_revision"],
+ "if_source_sha256": plan["source_sha256"], "if_report_sha256": None}
+ send("calibration.job.create", reviewed)
+ with mock.patch("tools.calibrate.run", side_effect=self.fake_result):
+ calibration.measure("local", path, exclusive_ack=True, runner=self.fake_result,
+ say=lambda _: None, job_id=job_id)
+ recovered = send("calibration.job", {"job_id": job_id})["job"]
+ self.assertEqual(recovered["state"], "succeeded")
+ self.assertEqual(recovered["outcome"], "report_recovered")
+ self.assertEqual(journal.load("local", job_id)["state"], "succeeded")
+ result = subprocess.run([sys.executable, "-m", "strata_control.management"],
+ input=json.dumps({"schema_version": 1, "action": "calibration.job", "profile": "local",
+ "params": {"job_id": job_id}}), text=True, capture_output=True,
+ cwd=Path(__file__).resolve().parents[2], env=os.environ.copy(), check=True)
+ self.assertEqual(json.loads(result.stdout)["job"]["result"]["report_id"],
+ recovered["result"]["report_id"])
+ with self.assertRaisesRegex(profiles.ProfileError, "already finished"):
+ journal.finish("local", job_id, "failed", {"error_type": "wrong"})
+
+ def test_failed_desktop_calibration_preflight_finishes_receipt(self):
+ def send(action, params):
+ return management.dispatch({"schema_version": 1, "action": action,
+ "profile": "local", "params": params})
+
+ plan = send("calibration.plan", {})["plan"]
+ job_id = uuid.uuid4().hex
+ path = self.root / "failed-calibration.json"
+ reviewed = {"path": str(path), "exclusive_ack": True,
+ "if_profile_revision": plan["profile_revision"],
+ "if_source_sha256": plan["source_sha256"]}
+ send("calibration.job.create", {"job_id": job_id, "action": "measure",
+ "if_report_sha256": None, **reviewed})
+ self.config.write_text(self.config.read_text().replace("test-model", "changed-model"))
+ with self.assertRaisesRegex(profiles.ProfileError, "source changed"):
+ send("calibration.measure", {**reviewed, "job_id": job_id})
+ self.assertEqual(journal.load("local", job_id)["state"], "failed")
+ self.assertFalse(path.exists())
+
+ def test_unrelated_report_cannot_finish_calibration_receipt(self):
+ def send(action, params):
+ return management.dispatch({"schema_version": 1, "action": action,
+ "profile": "local", "params": params})
+
+ plan = send("calibration.plan", {})["plan"]
+ path = self.root / "unrelated-report.json"
+ job_id = uuid.uuid4().hex
+ send("calibration.job.create", {"job_id": job_id, "action": "measure",
+ "path": str(path), "exclusive_ack": True,
+ "if_profile_revision": plan["profile_revision"],
+ "if_source_sha256": plan["source_sha256"], "if_report_sha256": None})
+ calibration.measure("local", path, exclusive_ack=True, runner=self.fake_result,
+ say=lambda _: None, job_id=uuid.uuid4().hex)
+ self.assertEqual(send("calibration.job", {"job_id": job_id})["job"]["state"], "launching")
+ self.assertEqual(journal.load("local", job_id)["state"], "running")
+
+ def test_active_measurement_progress_and_exact_cancel(self):
+ from tools import calibrate as cal
+
+ def send(action, params):
+ return management.dispatch({"schema_version": 1, "action": action,
+ "profile": "local", "params": params})
+
+ path = self.root / "stopped-calibration.json"
+ plan = send("calibration.plan", {})["plan"]
+ job_id = uuid.uuid4().hex
+ reviewed = {"path": str(path), "exclusive_ack": True,
+ "if_profile_revision": plan["profile_revision"],
+ "if_source_sha256": plan["source_sha256"]}
+ send("calibration.job.create", {"job_id": job_id, "action": "measure",
+ "if_report_sha256": None, **reviewed})
+ started = threading.Event()
+ outcome = []
+ original = self.config.read_bytes()
+
+ def waiting(cfg, say, *, progress, cancel_event):
+ progress("pcie_share", 2, 21)
+ started.set()
+ if not cancel_event.wait(4):
+ raise AssertionError("operator cancellation did not reach the worker")
+ raise cal.CalibrationCancelled("operator requested stop")
+
+ def worker():
+ try:
+ send("calibration.measure", {**reviewed, "job_id": job_id})
+ except BaseException as exc:
+ outcome.append(exc)
+
+ def bridge(action):
+ request = {"schema_version": 1, "action": action, "profile": "local",
+ "params": {"job_id": job_id}}
+ child = subprocess.run([sys.executable, "-m", "strata_control.management"],
+ input=json.dumps(request), text=True, capture_output=True,
+ cwd=Path(__file__).resolve().parents[2], env=os.environ.copy(), check=True)
+ return json.loads(child.stdout)
+
+ with mock.patch("tools.calibrate.run", side_effect=waiting):
+ thread = threading.Thread(target=worker)
+ thread.start()
+ try:
+ self.assertTrue(started.wait(4))
+ active = send("calibration.job", {"job_id": job_id})["job"]
+ self.assertEqual(active["state"], "running")
+ self.assertEqual(active["activity"], "active")
+ self.assertEqual(active["progress"]["stage"], "pcie_share")
+ self.assertEqual(active["progress"]["completed"], 2)
+ fresh = bridge("calibration.job")["job"]
+ self.assertEqual(fresh["state"], "running")
+ self.assertEqual(fresh["progress"]["completed"], 2)
+ with self.assertRaisesRegex(profiles.ProfileError, "not found"):
+ send("calibration.cancel", {"job_id": uuid.uuid4().hex})
+ self.assertEqual(bridge("calibration.cancel")["state"], "cancel_requested")
+ finally:
+ thread.join(timeout=6)
+ self.assertFalse(thread.is_alive())
+ self.assertEqual(len(outcome), 1)
+ self.assertIsInstance(outcome[0], profiles.ProfileError)
+ self.assertEqual(outcome[0].exit_code, 130)
+ finished = send("calibration.job", {"job_id": job_id})["job"]
+ self.assertEqual(finished["state"], "cancelled")
+ self.assertTrue(finished["cancel_requested"])
+ self.assertFalse(path.exists())
+ self.assertEqual(self.config.read_bytes(), original)
+ with self.assertRaisesRegex(profiles.ProfileError, "not active"):
+ send("calibration.cancel", {"job_id": job_id})
+
+ def test_pruning_finished_receipt_removes_progress_and_cancel_marker(self):
+ from strata_control import calibration_jobs
+
+ def send(action, params):
+ return management.dispatch({"schema_version": 1, "action": action,
+ "profile": "local", "params": params})
+
+ plan = send("calibration.plan", {})["plan"]
+ shared = {"action": "measure", "exclusive_ack": True,
+ "if_profile_revision": plan["profile_revision"],
+ "if_source_sha256": plan["source_sha256"], "if_report_sha256": None}
+ first = uuid.uuid4().hex
+ send("calibration.job.create", {**shared, "job_id": first,
+ "path": str(self.root / "first.json")})
+ calibration_jobs._save_progress("local", first, "pcie_share", 2, 21)
+ marker = calibration_jobs._cancel_path("local", first)
+ marker.write_bytes(b"1")
+ marker.chmod(0o600)
+ journal.finish("local", first, "failed", {"cancelled": True})
+ with mock.patch.object(journal, "MAX_RECORDS", 1):
+ send("calibration.job.create", {**shared, "job_id": uuid.uuid4().hex,
+ "path": str(self.root / "second.json")})
+ self.assertFalse(calibration_jobs._progress_path("local", first).exists())
+ self.assertFalse(marker.exists())
+
+ def test_management_bridge_reviews_and_journals_exclusive_calibration(self):
+ def send(action, params):
+ return management.dispatch({"schema_version": 1, "action": action,
+ "profile": "local", "params": params})
+
+ report_path = self.root / "bridge-calibration.json"
+ initial = self.config.read_bytes()
+ plan = send("calibration.plan", {})["plan"]
+ self.assertEqual(plan["source_config"], str(self.config.resolve()))
+ self.assertTrue(plan["component_preflight"]["ok"])
+ source = {"if_profile_revision": plan["profile_revision"],
+ "if_source_sha256": plan["source_sha256"]}
+ measure = {"path": str(report_path), "exclusive_ack": True, **source}
+ with self.assertRaisesRegex(profiles.ProfileError, "exclusive-access"):
+ send("calibration.measure", {**measure, "exclusive_ack": False})
+ with self.assertRaisesRegex(profiles.ProfileError, "source changed"):
+ send("calibration.measure", {**measure, "if_source_sha256": "0" * 64})
+ self.assertEqual(journal.list_runs("local"), [])
+ with mock.patch("tools.calibrate.run", side_effect=self.fake_result), \
+ mock.patch("strata_control.calibration._smoke", return_value=3):
+ measured = send("calibration.measure", measure)
+ self.assertTrue(measured["ok"])
+ self.assertTrue(measured["applicable"])
+ self.assertEqual(self.config.read_bytes(), initial)
+ self.assertEqual(journal.load("local", measured["operation_id"])["state"], "succeeded")
+
+ apply_plan = send("calibration.apply.plan", {"path": str(report_path)})
+ self.assertTrue(apply_plan["plan"]["applicable"])
+ apply = {"path": str(report_path), "exclusive_ack": True,
+ "if_profile_revision": apply_plan["profile_revision"],
+ "if_source_sha256": apply_plan["source_sha256"],
+ "if_report_sha256": apply_plan["report_sha256"]}
+ with self.assertRaisesRegex(profiles.ProfileError, "report changed"):
+ send("calibration.apply", {**apply, "if_report_sha256": "0" * 64})
+ self.assertEqual(len(journal.list_runs("local")), 1)
+ applied = send("calibration.apply", apply)
+ self.assertTrue(applied["application"]["changed"])
+ self.assertTrue(Path(applied["application"]["application_record"]).is_file())
+
+ rollback_plan = send("calibration.rollback.plan", {"path": str(report_path)})
+ self.assertTrue(rollback_plan["plan"]["applicable"])
+ rolled = send("calibration.rollback", {"path": str(report_path),
+ "exclusive_ack": True, "if_profile_revision": rollback_plan["profile_revision"],
+ "if_source_sha256": rollback_plan["source_sha256"],
+ "if_report_sha256": rollback_plan["report_sha256"]})
+ self.assertTrue(rolled["rollback"]["changed"])
+ self.assertEqual(self.config.read_bytes(), initial)
+ self.assertEqual([row["kind"] for row in journal.list_runs("local")],
+ ["engine.calibrate.rollback", "engine.calibrate.apply",
+ "engine.calibrate.measure"])
+
+ def test_calibration_rechecks_reviewed_digests_inside_operation_lock(self):
+ report_path = self.root / "pinned-calibration.json"
+ with self.assertRaisesRegex(profiles.ProfileError, "source changed after review"):
+ calibration.measure("local", report_path, exclusive_ack=True,
+ runner=lambda *_args, **_kwargs: self.fail("runner must not start"),
+ expected_source_sha256="0" * 64)
+ self.assertFalse(report_path.exists())
+ report = calibration.measure("local", report_path, exclusive_ack=True,
+ runner=self.fake_result, say=lambda _: None)
+ source = self.config.read_bytes()
+ with self.assertRaisesRegex(profiles.ProfileError, "report changed after review"):
+ calibration.apply_result("local", report_path, exclusive_ack=True,
+ expected_report_sha256="0" * 64,
+ smoke=lambda *_args: self.fail("smoke must not start"))
+ self.assertEqual(self.config.read_bytes(), source)
+ calibration.apply_result("local", report_path, exclusive_ack=True,
+ expected_report_sha256=report["body_sha256"], smoke=lambda *_args: 2)
+ with self.assertRaisesRegex(profiles.ProfileError, "report changed after review"):
+ calibration.rollback_result("local", report_path, exclusive_ack=True,
+ expected_report_sha256="0" * 64,
+ smoke=lambda *_args: self.fail("smoke must not start"))
+
+ def test_measure_review_apply_and_setup_persistence(self):
+ before = self.config.read_bytes()
+ report_path = self.root / "calibration.json"
+ report = calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
+ self.assertEqual(self.config.read_bytes(), before)
+ self.assertTrue(report["applicable"])
+ self.assertEqual(report["settings"]["--pcie-frac"], "0.20")
+ if os.name != "nt":
+ self.assertEqual(stat.S_IMODE(report_path.stat().st_mode), 0o600)
+ preview = calibration.review("local", report_path)
+ self.assertTrue(preview["applicable"])
+ self.assertIn("--pcie-frac", preview["after_args"])
+ applied = calibration.apply_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 4)
+ self.assertTrue(applied["changed"])
+ self.assertEqual(applied["smoke_output_tokens"], 4)
+ self.assertEqual(Path(applied["backup"]).read_bytes(), before)
+ self.assertIn("--pcie-frac", json.loads(self.config.read_text())["args"])
+ settings = json.loads((self.root / "settings" / "strata" / "settings.json").read_text())
+ self.assertEqual(settings["calibration"]["test-gpu|24GB|test-cpu"]["settings"], report["settings"])
+ self.assertFalse(calibration.review("local", report_path)["applicable"])
+
+ def test_review_and_rollback_restore_config_and_absent_settings(self):
+ before = self.config.read_bytes()
+ report_path = self.root / "calibration.json"
+ calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
+ applied = calibration.apply_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 3)
+ self.assertTrue(Path(applied["application_record"]).is_file())
+ if os.name == "posix":
+ self.assertEqual(stat.S_IMODE(Path(applied["application_record"]).stat().st_mode), 0o600)
+ preview = calibration.review_rollback("local", report_path)
+ self.assertTrue(preview["applicable"], preview["reasons"])
+ self.assertTrue(preview["setup_settings_would_be_removed"])
+ restored = calibration.rollback_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
+ self.assertTrue(restored["changed"])
+ self.assertEqual(restored["smoke_output_tokens"], 2)
+ self.assertEqual(self.config.read_bytes(), before)
+ self.assertFalse((self.root / "settings" / "strata" / "settings.json").exists())
+ self.assertFalse(calibration.review_rollback("local", report_path)["applicable"])
+
+ @unittest.skipUnless(os.name == "posix", "managed activity lease is POSIX-only")
+ def test_managed_activity_lease_blocks_apply_and_rollback_smoke(self):
+ report_path = self.root / "calibration.json"
+
+ def assert_exclusive():
+ with self.assertRaisesRegex(profiles.ProfileError, "engine lease"):
+ runtime.acquire_activity_lease(shared=True)
+
+ def runner(cfg, say):
+ assert_exclusive()
+ return self.fake_result(cfg, say)
+
+ def smoke(cfg):
+ assert_exclusive()
+ return 2
+
+ calibration.measure("local", report_path, exclusive_ack=True,
+ runner=runner, say=lambda _: None)
+ before = self.config.read_bytes()
+ lease = runtime.acquire_activity_lease(shared=True)
+ try:
+ with self.assertRaisesRegex(profiles.ProfileError, "engine lease"):
+ calibration.apply_result("local", report_path, exclusive_ack=True,
+ smoke=lambda cfg: self.fail("apply smoke ran"))
+ finally:
+ os.close(lease)
+ self.assertEqual(self.config.read_bytes(), before)
+ calibration.apply_result("local", report_path, exclusive_ack=True, smoke=smoke)
+ applied = self.config.read_bytes()
+ lease = runtime.acquire_activity_lease(shared=True)
+ try:
+ with self.assertRaisesRegex(profiles.ProfileError, "engine lease"):
+ calibration.rollback_result("local", report_path, exclusive_ack=True,
+ smoke=lambda cfg: self.fail("rollback smoke ran"))
+ finally:
+ os.close(lease)
+ self.assertEqual(self.config.read_bytes(), applied)
+ with mock.patch("strata_control.calibration._port_active", return_value=True):
+ with self.assertRaisesRegex(profiles.ProfileError, "server is listening"):
+ calibration.rollback_result("local", report_path, exclusive_ack=True,
+ smoke=lambda cfg: self.fail("rollback smoke ran"))
+ self.assertEqual(self.config.read_bytes(), applied)
+ self.assertTrue(calibration.rollback_result("local", report_path, exclusive_ack=True,
+ smoke=smoke)["changed"])
+
+ def test_rollback_restores_existing_settings_exactly(self):
+ settings_path = self.root / "settings" / "strata" / "settings.json"
+ settings_path.parent.mkdir(parents=True)
+ original_settings = b'{"unrelated": "keep", "calibration": {"other-device": {"settings": {}}}}\n'
+ settings_path.write_bytes(original_settings)
+ original_config = self.config.read_bytes()
+ report_path = self.root / "calibration.json"
+ calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
+ applied = calibration.apply_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
+ self.assertEqual(Path(applied["settings_backup"]).read_bytes(), original_settings)
+ calibration.rollback_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
+ self.assertEqual(settings_path.read_bytes(), original_settings)
+ self.assertEqual(self.config.read_bytes(), original_config)
+
+ def test_rollback_refuses_stale_state_and_failed_smoke(self):
+ report_path = self.root / "calibration.json"
+ calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
+ calibration.apply_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
+ applied_config = self.config.read_bytes()
+ settings_path = self.root / "settings" / "strata" / "settings.json"
+ applied_settings = settings_path.read_bytes()
+ with self.assertRaisesRegex(profiles.ProfileError, "rollback smoke generation failed"):
+ calibration.rollback_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 1 / 0)
+ self.assertEqual(self.config.read_bytes(), applied_config)
+ settings_path.write_bytes(applied_settings + b" ")
+ preview = calibration.review_rollback("local", report_path)
+ self.assertIn("setup_settings_changed_after_apply", preview["reasons"])
+ with self.assertRaisesRegex(profiles.ProfileError, "rollback is stale"):
+ calibration.rollback_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
+ self.assertEqual(self.config.read_bytes(), applied_config)
+ settings_path.write_bytes(applied_settings)
+ self.config.write_bytes(applied_config + b" ")
+ preview = calibration.review_rollback("local", report_path)
+ self.assertIn("run_config_changed_after_apply", preview["reasons"])
+ with self.assertRaisesRegex(profiles.ProfileError, "rollback is stale"):
+ calibration.rollback_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
+
+ def test_rollback_detects_change_during_smoke(self):
+ report_path = self.root / "calibration.json"
+ calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
+ calibration.apply_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
+ applied_config = self.config.read_bytes()
+ settings_path = self.root / "settings" / "strata" / "settings.json"
+ applied_settings = settings_path.read_bytes()
+
+ def smoke(cfg):
+ settings_path.write_bytes(applied_settings + b" ")
+ return 2
+
+ with self.assertRaisesRegex(profiles.ProfileError, "changed during rollback smoke"):
+ calibration.rollback_result("local", report_path, exclusive_ack=True, smoke=smoke)
+ self.assertEqual(self.config.read_bytes(), applied_config)
+
+ def test_rollback_rejects_modified_backup(self):
+ report_path = self.root / "calibration.json"
+ calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
+ applied = calibration.apply_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
+ Path(applied["backup"]).write_bytes(b"{}")
+ preview = calibration.review_rollback("local", report_path)
+ self.assertIn("config_backup_changed", preview["reasons"])
+ with self.assertRaisesRegex(profiles.ProfileError, "rollback is stale"):
+ calibration.rollback_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
+
+ def test_rollback_requires_exclusive_acknowledgement(self):
+ report_path = self.root / "calibration.json"
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(["engine", "calibrate", "--profile", "local", "--rollback-result",
+ str(report_path), "--output", "json"])
+ self.assertEqual(code, 2)
+ self.assertFalse(json.loads(output.getvalue())["ok"])
+ with self.assertRaisesRegex(profiles.ProfileError, "exclusive-access"):
+ calibration.rollback_result("local", report_path)
+
+ @unittest.skipUnless(os.name == "posix", "symlink test requires POSIX")
+ def test_apply_refuses_symlinked_backup_directory(self):
+ report_path = self.root / "calibration.json"
+ calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
+ previous = self.config.read_bytes()
+ elsewhere = self.root / "elsewhere"
+ elsewhere.mkdir()
+ (self.root / ".strata-calibration-backups").symlink_to(elsewhere, target_is_directory=True)
+ with self.assertRaisesRegex(profiles.ProfileError, "owner-only and not a symlink"):
+ calibration.apply_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
+ self.assertEqual(self.config.read_bytes(), previous)
+ self.assertEqual(list(elsewhere.iterdir()), [])
+
+ def test_rollback_write_failure_restores_applied_state(self):
+ report_path = self.root / "calibration.json"
+ calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
+ calibration.apply_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
+ current_config = self.config.read_bytes()
+ settings_path = self.root / "settings" / "strata" / "settings.json"
+ current_settings = settings_path.read_bytes()
+ original_replace = calibration._replace_bytes
+ failures = 0
+
+ def fail_restore(path, payload):
+ nonlocal failures
+ if path == self.config.resolve() and failures == 0:
+ failures += 1
+ original_replace(path, payload)
+ raise OSError("simulated failure after config replacement")
+ return original_replace(path, payload)
+
+ with mock.patch("strata_control.calibration._replace_bytes", side_effect=fail_restore):
+ with self.assertRaisesRegex(profiles.ProfileError, "applied state restored"):
+ calibration.rollback_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
+ self.assertEqual(self.config.read_bytes(), current_config)
+ self.assertEqual(settings_path.read_bytes(), current_settings)
+
+ def test_failed_smoke_or_changed_config_never_applies(self):
+ report_path = self.root / "calibration.json"
+ calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
+ before = self.config.read_bytes()
+ with self.assertRaisesRegex(profiles.ProfileError, "smoke generation failed"):
+ calibration.apply_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 1 / 0)
+ self.assertEqual(self.config.read_bytes(), before)
+ self.config.write_bytes(before + b" ")
+ with self.assertRaisesRegex(profiles.ProfileError, "stale"):
+ calibration.apply_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 4)
+
+ def test_report_id_and_settings_are_validated_before_apply(self):
+ report_path = self.root / "calibration.json"
+ calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
+ report = json.loads(report_path.read_text())
+ report["report_id"] = "../../outside"
+ report_path.write_text(json.dumps(report), encoding="utf-8")
+ with self.assertRaisesRegex(profiles.ProfileError, "unsupported calibration report"):
+ calibration.review("local", report_path)
+ report["report_id"] = "0" * 32
+ report["settings"] = {"--pool-workers": "999999"}
+ report_path.write_text(json.dumps(report), encoding="utf-8")
+ with self.assertRaisesRegex(profiles.ProfileError, "positive whole number"):
+ calibration.review("local", report_path)
+ report["settings"] = {"--pcie-frac": "0.75"}
+ report_path.write_text(json.dumps(report), encoding="utf-8")
+ with self.assertRaisesRegex(profiles.ProfileError, "changed after measurement"):
+ calibration.review("local", report_path)
+
+ def test_machine_cli_measure_review_apply_emits_one_json_record(self):
+ report_path = self.root / "calibration.json"
+ with mock.patch("tools.calibrate.run", side_effect=self.fake_result), \
+ mock.patch("strata_control.calibration._smoke", return_value=3):
+ for args, expected_key in ((["--measure", "--out", str(report_path), "--exclusive"], "report"),
+ (["--review-result", str(report_path)], "review"),
+ (["--apply-result", str(report_path), "--exclusive"], "application"),
+ (["--review-rollback", str(report_path)], "rollback_review"),
+ (["--rollback-result", str(report_path), "--exclusive"], "rollback")):
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(["engine", "calibrate", "--profile", "local", *args, "--output", "json"])
+ self.assertEqual(code, 0)
+ parsed = json.loads(output.getvalue())
+ self.assertTrue(parsed["ok"])
+ self.assertIn(expected_key, parsed)
+ if expected_key in ("report", "application", "rollback"):
+ record = journal.load("local", parsed["operation_id"])
+ self.assertEqual(record["schema_version"], 2)
+ self.assertEqual(record["origin"], "direct")
+ self.assertEqual(record["state"], "succeeded")
+ self.assertNotIn("candidate", json.dumps(record))
+ else:
+ self.assertNotIn("operation_id", parsed)
+ self.assertEqual([row["kind"] for row in journal.list_runs("local")],
+ ["engine.calibrate.rollback", "engine.calibrate.apply", "engine.calibrate.measure"])
+
+ def test_explicit_run_config_path_retains_legacy_nonjournaled_calibration(self):
+ report_path = self.root / "calibration-path.json"
+ output = io.StringIO()
+ with mock.patch("tools.calibrate.run", side_effect=self.fake_result):
+ with redirect_stdout(output):
+ code = main(["engine", "calibrate", "--profile", str(self.config), "--measure",
+ "--exclusive", "--out", str(report_path), "--output", "json"])
+ self.assertEqual(code, 0)
+ self.assertNotIn("operation_id", json.loads(output.getvalue()))
+ self.assertEqual(journal.list_runs("local"), [])
+
+ def test_direct_apply_failure_is_a_compact_failed_operation(self):
+ report_path = self.root / "calibration.json"
+ calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
+ output = io.StringIO()
+ with mock.patch("strata_control.calibration._smoke", side_effect=OSError("private engine trace")):
+ with redirect_stdout(output):
+ code = main(["engine", "calibrate", "--profile", "local", "--apply-result",
+ str(report_path), "--exclusive", "--output", "json"])
+ self.assertEqual(code, 6)
+ self.assertFalse(json.loads(output.getvalue())["ok"])
+ record = journal.load("local", journal.list_runs("local")[0]["operation_id"])
+ self.assertEqual((record["kind"], record["state"]), ("engine.calibrate.apply", "failed"))
+ self.assertNotIn("private engine trace", json.dumps(record))
+
+ def test_measure_requires_exclusive_access_and_rejects_live_profile_port(self):
+ report_path = self.root / "calibration.json"
+ with self.assertRaisesRegex(profiles.ProfileError, "exclusive-access"):
+ calibration.measure("local", report_path, runner=self.fake_result)
+ with mock.patch("strata_control.calibration._port_active", return_value=True):
+ with self.assertRaisesRegex(profiles.ProfileError, "server is listening"):
+ calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result)
+ profiles.set_values("local", ["port=9123"])
+ with mock.patch("strata_control.calibration._port_active",
+ side_effect=lambda cfg: cfg.get("port") == 9123) as checked:
+ with self.assertRaisesRegex(profiles.ProfileError, "server is listening"):
+ calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result)
+ self.assertEqual([call.args[0]["port"] for call in checked.call_args_list], [8095, 9123])
+ self.assertFalse(report_path.exists())
+
+ def test_measure_and_smoke_use_saved_engine_overrides_without_writing_them(self):
+ profiles.set_values("local", ["parallel=8", "batch_groups=2"])
+ source = self.config.read_bytes()
+ report_path = self.root / "calibration.json"
+ seen = {}
+
+ def runner(cfg, say):
+ seen["measured"] = cfg
+ return self.fake_result(cfg, say)
+
+ def smoke(cfg):
+ seen["smoked"] = cfg
+ return 2
+
+ calibration.measure("local", report_path, exclusive_ack=True, runner=runner, say=lambda _: None)
+ self.assertEqual(seen["measured"]["parallel"], 8)
+ self.assertEqual(seen["measured"]["args"][-2:], ["--batch-groups", "2"])
+ self.assertEqual(self.config.read_bytes(), source)
+ calibration.apply_result("local", report_path, exclusive_ack=True, smoke=smoke)
+ self.assertEqual(seen["smoked"]["parallel"], 8)
+ self.assertIn("--batch-groups", seen["smoked"]["args"])
+ saved_args = json.loads(self.config.read_text())["args"]
+ self.assertNotIn("--batch-groups", saved_args)
+
+ def test_profile_edit_during_measurement_marks_report_stale(self):
+ report_path = self.root / "calibration.json"
+
+ def runner(cfg, say):
+ profiles.set_values("local", ["parallel=4"])
+ return self.fake_result(cfg, say)
+
+ report = calibration.measure("local", report_path, exclusive_ack=True, runner=runner, say=lambda _: None)
+ self.assertFalse(report["applicable"])
+ preview = calibration.review("local", report_path)
+ self.assertFalse(preview["applicable"])
+ self.assertIn("measurement_became_stale", preview["reasons"])
+
+ def test_profile_edit_during_smoke_prevents_apply(self):
+ report_path = self.root / "calibration.json"
+ calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
+ source = self.config.read_bytes()
+
+ def smoke(cfg):
+ profiles.set_values("local", ["parallel=4"])
+ return 2
+
+ with self.assertRaisesRegex(profiles.ProfileError, "changed during smoke"):
+ calibration.apply_result("local", report_path, exclusive_ack=True, smoke=smoke)
+ self.assertEqual(self.config.read_bytes(), source)
+
+ def test_settings_write_failure_restores_previous_run_config(self):
+ report_path = self.root / "calibration.json"
+ calibration.measure("local", report_path, exclusive_ack=True, runner=self.fake_result, say=lambda _: None)
+ source = self.config.read_bytes()
+ original_replace = calibration._replace_bytes
+ failures = 0
+
+ def fail_settings(path, payload):
+ nonlocal failures
+ if path.name == "settings.json":
+ failures += 1
+ if failures == 1:
+ original_replace(path, payload)
+ raise OSError("simulated failure after settings replacement")
+ return original_replace(path, payload)
+
+ with mock.patch("strata_control.calibration._replace_bytes", side_effect=fail_settings):
+ with self.assertRaisesRegex(profiles.ProfileError, "config restored"):
+ calibration.apply_result("local", report_path, exclusive_ack=True, smoke=lambda cfg: 2)
+ self.assertEqual(self.config.read_bytes(), source)
+ self.assertFalse((self.root / "settings" / "strata" / "settings.json").exists())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/terminal/test_connections.py b/tests/terminal/test_connections.py
new file mode 100644
index 000000000..9044a8b3e
--- /dev/null
+++ b/tests/terminal/test_connections.py
@@ -0,0 +1,324 @@
+"""Saved read-only connections work in both source and portable terminal clients."""
+
+import io
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import threading
+import unittest
+from contextlib import redirect_stdout
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from unittest import mock
+
+from strata_cli.cli import main
+from strata_cli import connections
+from strata_cli.client import ClientError, Endpoint, server_url
+from strata_cli.render import render_view
+
+
+ROOT = Path(__file__).resolve().parents[2]
+
+
+class ConnectionTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory(prefix="strata-connections-")
+ self.addCleanup(self.temp.cleanup)
+ self.directory = Path(self.temp.name) / "connections"
+ env = mock.patch.dict(os.environ, {"STRATA_CONNECTION_DIR": str(self.directory)}, clear=False)
+ env.start()
+ self.addCleanup(env.stop)
+
+ def _cli(self, *argv):
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(list(argv))
+ return code, json.loads(output.getvalue())
+
+ def test_create_edit_precedence_and_private_storage(self):
+ code, created = self._cli("connection", "create", "edge", "--url", "https://Example.COM:443",
+ "--prefix", "/proxy/strata", "--credential-env", "STRATA_READ_KEY",
+ "--output", "json")
+ self.assertEqual(code, 0)
+ self.assertEqual(created["connection"]["url"], "https://example.com:443")
+ self.assertEqual(created["connection"]["prefix"], "/proxy/strata")
+ saved = self.directory / "edge.json"
+ if os.name == "posix":
+ self.assertEqual(self.directory.stat().st_mode & 0o077, 0)
+ self.assertEqual(saved.stat().st_mode & 0o077, 0)
+ self.assertNotIn("test-secret", saved.read_text())
+ revision = created["revision"]
+ code, plan = self._cli("connection", "set", "edge", "prefix=/new", "--plan",
+ "--if-revision", revision, "--output", "json")
+ self.assertEqual(code, 0)
+ self.assertTrue(plan["would_save"])
+ self.assertEqual(connections.load("edge")[1], revision)
+ code, changed = self._cli("connection", "set", "edge", "prefix=/new",
+ "--if-revision", revision, "--output", "json")
+ self.assertEqual(code, 0)
+ self.assertNotEqual(changed["revision"], revision)
+ code, stale = self._cli("connection", "set", "edge", "prefix=/other",
+ "--if-revision", revision, "--output", "json")
+ self.assertEqual((code, stale["error"]["code"]), (6, 6))
+ self.assertEqual(connections.load("edge")[0]["prefix"], "/new")
+ with mock.patch.dict(os.environ, {"STRATA_CONNECTION": "edge", "STRATA_URL": "https://ignored.example",
+ "STRATA_READ_KEY": "test-secret"}):
+ code, effective = self._cli("config", "show", "--effective", "--output", "json")
+ self.assertEqual(code, 0)
+ self.assertEqual(effective["effective"]["url"], "https://example.com:443")
+ self.assertEqual(effective["effective"]["prefix"], "/new")
+ self.assertEqual(effective["effective"]["base_url"], "https://example.com:443/new")
+ self.assertEqual(effective["effective"]["origins"]["url"], "connection")
+ self.assertEqual(effective["effective"]["timeout_s"], 3.0)
+ self.assertEqual(effective["effective"]["origins"]["timeout_s"], "default")
+ self.assertTrue(effective["effective"]["credential_present"])
+ self.assertNotIn("test-secret", json.dumps(effective))
+ code, override = self._cli("config", "show", "--url", "https://other.example",
+ "--credential-env", "OTHER_KEY", "--timeout", "4.5",
+ "--output", "json")
+ self.assertEqual(code, 0)
+ self.assertEqual(override["effective"]["url"], "https://other.example")
+ self.assertEqual(override["effective"]["prefix"], "")
+ self.assertEqual(override["effective"]["credential_env"], "OTHER_KEY")
+ self.assertEqual(override["effective"]["origins"]["url"], "flag")
+ self.assertEqual(override["effective"]["origins"]["timeout_s"], "flag")
+ self.assertEqual(override["effective"]["timeout_s"], 4.5)
+ code, conflict = self._cli("config", "show", "--url", "https://other.example",
+ "--connection", "edge", "--output", "json")
+ self.assertEqual((code, conflict["error"]["code"]), (2, 2))
+
+ def test_connection_and_config_json_aliases(self):
+ code, listed = self._cli("connection", "list", "--json")
+ self.assertEqual(code, 0)
+ self.assertEqual(listed["connections"], [])
+ code, effective = self._cli("config", "show", "--url", "http://127.0.0.1:8095", "--json")
+ self.assertEqual(code, 0)
+ self.assertTrue(effective["ok"])
+ self.assertEqual(effective["effective"]["url"], "http://127.0.0.1:8095")
+
+ def test_interactive_monitor_rejects_json_output_before_connecting(self):
+ for output_flag in (("--output", "json"), ("--json",)):
+ with self.subTest(output_flag=output_flag), mock.patch(
+ "strata_cli.monitor_commands.Endpoint") as endpoint:
+ code, response = self._cli("monitor", "--url", "http://127.0.0.1:1",
+ *output_flag)
+ self.assertEqual((code, response["error"]["code"]), (2, 2))
+ self.assertIn("requires --once", response["error"]["message"])
+ endpoint.assert_not_called()
+ bundle = Path(self.temp.name) / "strata-monitor.pyz"
+ subprocess.run([sys.executable, str(ROOT / "packaging/monitor_bundle.py"),
+ "build", str(bundle)], capture_output=True, text=True, check=True)
+ portable = subprocess.run([sys.executable, "-S", str(bundle), "monitor", "--url",
+ "http://127.0.0.1:1", "--output", "json"],
+ cwd=self.temp.name, capture_output=True, text=True)
+ self.assertEqual(portable.returncode, 2)
+ self.assertIn("requires --once", json.loads(portable.stdout)["error"]["message"])
+ self.assertEqual(portable.stderr, "")
+
+ def test_quiet_connection_and_status_keep_machine_records(self):
+ output = io.StringIO()
+ with redirect_stdout(output):
+ self.assertEqual(main(["connection", "list", "--quiet"]), 0)
+ self.assertEqual(output.getvalue(), "")
+ code, listed = self._cli("connection", "list", "--quiet", "--json")
+ self.assertEqual(code, 0)
+ self.assertEqual(listed["connections"], [])
+ with mock.patch("strata_cli.monitor_commands.Endpoint") as endpoint:
+ endpoint.return_value.snapshot.return_value = {"schema_version": 1}
+ output = io.StringIO()
+ with redirect_stdout(output):
+ self.assertEqual(main(["status", "--url", "http://127.0.0.1:8095", "--quiet"]), 0)
+ self.assertEqual(output.getvalue(), "")
+ with redirect_stdout(output):
+ self.assertEqual(main(["status", "--url", "http://127.0.0.1:8095",
+ "--quiet", "--json"]), 0)
+ self.assertTrue(json.loads(output.getvalue())["ok"])
+
+ def test_invalid_prefix_credentials_and_file_permissions_fail_closed(self):
+ for prefix in ("//proxy", "/a/../b", "/a?key=secret", "/a//b", "https://host/path"):
+ with self.assertRaises(connections.ConnectionError):
+ connections.prefix_path(prefix)
+ with self.assertRaises(ValueError):
+ server_url("http://@127.0.0.1:8095")
+ with self.assertRaises(connections.ConnectionError):
+ connections.credential_name("BAD-NAME")
+ connections.create("local", "http://127.0.0.1:8095")
+ with self.assertRaises(connections.ConnectionError):
+ connections.create("local", "http://127.0.0.1:8095")
+ if os.name == "posix":
+ record = self.directory / "local.json"
+ record.chmod(0o644)
+ with self.assertRaisesRegex(connections.ConnectionError, "private regular"):
+ connections.load("local")
+ record.chmod(0o600)
+ record = self.directory / "local.json"
+ corrupted = json.loads(record.read_text())
+ corrupted["url"] = 42
+ record.write_text(json.dumps(corrupted))
+ code, response = self._cli("config", "show", "--connection", "local", "--output", "json")
+ self.assertEqual((code, response["error"]["code"]), (5, 5))
+
+ def test_proxy_prefix_and_credential_reference_work_in_portable_bundle(self):
+ seen = []
+ snapshot = {"schema_version": 1, "instance": {"id": "from-proxy"},
+ "model": {"id": "fixture", "loaded": True}, "work": {"active": 3}}
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ seen.append((self.path, self.headers.get("Authorization")))
+ if self.path != "/proxy/v1/telemetry":
+ self.send_error(404)
+ return
+ body = json.dumps(snapshot).encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *_args):
+ pass
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ root = f"http://127.0.0.1:{server.server_port}"
+ connections.create("proxied", root, prefix="/proxy", credential_env="STRATA_READ_KEY")
+ with mock.patch.dict(os.environ, {"STRATA_READ_KEY": "test-secret"}):
+ code, source = self._cli("status", "--connection", "proxied", "--json")
+ self.assertEqual(code, 0)
+ self.assertEqual(source["snapshot"]["work"]["active"], 3)
+ bundle = Path(self.temp.name) / "strata-monitor.pyz"
+ subprocess.run([sys.executable, str(ROOT / "packaging/monitor_bundle.py"),
+ "build", str(bundle)], capture_output=True, text=True, check=True)
+ portable = subprocess.run([sys.executable, "-S", str(bundle), "status", "--connection",
+ "proxied", "--json"], env=os.environ.copy(), cwd=self.temp.name,
+ capture_output=True, text=True, check=True)
+ self.assertEqual(json.loads(portable.stdout), source)
+ portable_config = subprocess.run([sys.executable, "-S", str(bundle), "config", "show",
+ "--connection", "proxied", "--output", "json"],
+ env=os.environ.copy(), cwd=self.temp.name,
+ capture_output=True, text=True, check=True)
+ self.assertEqual(json.loads(portable_config.stdout)["effective"]["prefix"], "/proxy")
+ self.assertNotIn("test-secret", portable_config.stdout)
+ subprocess.run([sys.executable, "-S", str(bundle), "connection", "create", "second",
+ "--url", root, "--output", "json"], env=os.environ.copy(),
+ cwd=self.temp.name, capture_output=True, text=True, check=True)
+ self.assertEqual(connections.load("second")[0]["url"], root)
+ self.assertEqual(seen, [("/proxy/v1/telemetry", "Bearer test-secret")] * 2)
+ self.assertEqual(Endpoint(root, prefix="/proxy").base_url, root + "/proxy")
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=2)
+
+ def test_deeply_nested_telemetry_returns_one_redacted_error(self):
+ body = b"[" * 1100 + b"0" + b"]" * 1100
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *_args):
+ pass
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ root = f"http://127.0.0.1:{server.server_port}"
+ with self.assertRaisesRegex(ClientError, "malformed JSON telemetry"):
+ Endpoint(root).snapshot()
+ code, response = self._cli("status", "--url", root, "--json")
+ self.assertEqual(code, 3)
+ self.assertEqual(response["error"]["message"], "server returned malformed JSON telemetry")
+ bundle = Path(self.temp.name) / "deep-json-monitor.pyz"
+ subprocess.run([sys.executable, str(ROOT / "packaging/monitor_bundle.py"),
+ "build", str(bundle)], capture_output=True, text=True, check=True)
+ portable = subprocess.run([sys.executable, "-I", "-S", str(bundle), "status",
+ "--url", root, "--json"], cwd=self.temp.name,
+ capture_output=True, text=True, check=False)
+ self.assertEqual(portable.returncode, 3)
+ self.assertFalse(portable.stderr)
+ self.assertEqual(json.loads(portable.stdout)["error"]["message"],
+ "server returned malformed JSON telemetry")
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=2)
+
+ def test_status_only_fallback_labels_missing_telemetry_without_inventing_work(self):
+ paths = []
+ metrics_status = [404]
+ status = {"service": "strata", "model": "loaded-model", "loaded": True,
+ "started": 1_790_000_000, "concurrency": {"serving": 8}}
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ paths.append(self.path)
+ if self.path == "/metrics" and metrics_status[0] == 401:
+ self.send_error(401)
+ return
+ if self.path != "/v1/status":
+ self.send_error(404)
+ return
+ body = json.dumps(status).encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *_args):
+ pass
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ root = f"http://127.0.0.1:{server.server_port}"
+ snapshot = Endpoint(root).snapshot()
+ self.assertEqual(paths, ["/v1/telemetry", "/metrics", "/v1/status"])
+ self.assertEqual(snapshot["source"], "status-only")
+ self.assertEqual(snapshot["quality"]["telemetry"], "unavailable")
+ self.assertEqual(snapshot["model"], {"id": "loaded-model", "loaded": True, "context": None})
+ self.assertEqual(snapshot["work"]["slots_effective"], 8)
+ self.assertIsNone(snapshot["work"]["active"])
+ self.assertIsNone(snapshot["rates"]["answer_tok_s"])
+ display = render_view(snapshot, "overview", 80, 24)
+ self.assertIn("[NO TELEMETRY]", display)
+ self.assertIn("Telemetry unavailable; status only", display)
+ self.assertIn("Sample age", render_view(snapshot, "overview", 40, 12))
+ self.assertIn("In flight --", display)
+ code, source = self._cli("status", "--url", root, "--json")
+ self.assertEqual(code, 0)
+ self.assertEqual(source["snapshot"]["quality"]["telemetry"], "unavailable")
+ bundle = Path(self.temp.name) / "status-only.pyz"
+ subprocess.run([sys.executable, str(ROOT / "packaging/monitor_bundle.py"),
+ "build", str(bundle)], capture_output=True, text=True, check=True)
+ portable = subprocess.run([sys.executable, "-S", str(bundle), "status", "--url", root,
+ "--json"], capture_output=True, text=True, check=True)
+ portable_snapshot = json.loads(portable.stdout)["snapshot"]
+ self.assertEqual(portable_snapshot["source"], "status-only")
+ self.assertIsNone(portable_snapshot["work"]["active"])
+ metrics_status[0] = 401
+ paths.clear()
+ with self.assertRaises(ClientError) as denied:
+ Endpoint(root).snapshot()
+ self.assertEqual(denied.exception.exit_code, 4)
+ self.assertEqual(paths, ["/v1/telemetry", "/metrics"])
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=2)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/terminal/test_drain.py b/tests/terminal/test_drain.py
new file mode 100644
index 000000000..01bdd1de0
--- /dev/null
+++ b/tests/terminal/test_drain.py
@@ -0,0 +1,67 @@
+"""Opt-in serving drain: reject new work, finish owned calls, cancel on deadline."""
+
+import json
+import threading
+import time
+import unittest
+import urllib.error
+import urllib.request
+from pathlib import Path
+
+from serve.frontend import ChatTemplate
+from serve.server import ByteTokenizer, MockEngine, Service, serve
+from strata_cli.client import Endpoint
+from strata_cli.render import render_view
+
+
+class DrainTests(unittest.TestCase):
+ def setUp(self):
+ tok = ByteTokenizer()
+ self.svc = Service(MockEngine(tok, "Hello.", max_context=4096), tok,
+ ChatTemplate(Path(__file__).resolve().parents[2] / "serve/chat_template.jinja"))
+ self.httpd = serve(self.svc, port=0)
+ self.addCleanup(self.httpd.server_close)
+ self.addCleanup(self.httpd.shutdown)
+ self.url = f"http://127.0.0.1:{self.httpd.server_address[1]}"
+
+ def test_drain_rejects_new_inference_and_reports_state(self):
+ self.assertEqual(self.svc.begin_drain(), 0)
+ request = urllib.request.Request(self.url + "/v1/chat/completions", method="POST",
+ headers={"Content-Type": "application/json"},
+ data=json.dumps({"messages": [{"role": "user", "content": "Hi"}]}).encode())
+ with self.assertRaises(urllib.error.HTTPError) as captured:
+ urllib.request.urlopen(request, timeout=3)
+ with captured.exception as response:
+ self.assertEqual(response.status, 503)
+ self.assertEqual(json.loads(response.read())["error"]["code"], "server_draining")
+ snapshot = Endpoint(self.url).snapshot()
+ self.assertEqual(snapshot["instance"]["state"], "draining")
+ self.assertIn("DRAINING", render_view(snapshot, "overview", 80, 24))
+ self.assertEqual(self.svc.admission_rejected, 0)
+
+ def test_drain_waits_for_reserved_call_then_releases(self):
+ self.assertTrue(self.svc.reserve_inference())
+ self.assertEqual(self.svc.begin_drain(), 1)
+ self.assertIsNone(self.svc.reserve_inference())
+ timer = threading.Timer(0.08, self.svc.release_inference)
+ timer.start()
+ self.addCleanup(timer.join)
+ start = time.monotonic()
+ self.assertEqual(self.svc.wait_for_drain(1), 0)
+ self.assertGreaterEqual(time.monotonic() - start, 0.05)
+
+ def test_deadline_and_owned_cancellation(self):
+ self.assertTrue(self.svc.reserve_inference())
+ cancel = threading.Event()
+ with self.svc.status_lock:
+ self.svc.active_cancels.add(cancel)
+ self.svc.begin_drain()
+ self.assertEqual(self.svc.wait_for_drain(0), 1)
+ self.assertEqual(self.svc.cancel_owned_requests(), 1)
+ self.assertTrue(cancel.is_set())
+ self.svc.release_inference()
+ self.assertEqual(self.svc.wait_for_drain(0), 0)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/terminal/test_launch_identity.py b/tests/terminal/test_launch_identity.py
new file mode 100644
index 000000000..b56459723
--- /dev/null
+++ b/tests/terminal/test_launch_identity.py
@@ -0,0 +1,54 @@
+"""An owned server attests the bytes and arguments it actually received."""
+
+import json
+import unittest
+from unittest import mock
+
+from serve.launch_identity import attestation
+from strata_control import readiness
+
+
+class LaunchIdentityTests(unittest.TestCase):
+ def test_attestation_changes_with_source_args_and_key(self):
+ key = bytes(range(32))
+ cfg = b'{"api_key":"a private setting","model_name":"fake"}'
+ args = ["--config", "/tmp/run.json", "--parallel", "4"]
+ value = attestation(key, cfg, args)
+ self.assertEqual(len(value), 64)
+ self.assertEqual(value, attestation(key, cfg, args))
+ self.assertNotEqual(value, attestation(key, cfg + b" ", args))
+ self.assertNotEqual(value, attestation(key, cfg, [*args, "--batch-telemetry"]))
+ self.assertNotEqual(value, attestation(bytes(reversed(key)), cfg, args))
+ self.assertNotIn("private", value)
+
+ def test_wrong_or_absent_server_attestation_rejects_readiness_before_generation(self):
+ ready = {"bound_host": "127.0.0.1", "bound_port": 1234,
+ "model_id": "fake", "model_state": "ready"}
+ cfg = json.dumps({"model_name": "fake"}).encode()
+ for reported in (None, "0" * 64):
+ with self.subTest(reported=reported), mock.patch.object(readiness, "_request") as request:
+ request.return_value = {"instance": {"id": "one", "launch_attestation": reported},
+ "model": {"id": "fake", "loaded": True}}
+ with self.assertRaisesRegex(readiness.ReadinessError,
+ "probe_launch_attestation_mismatch"):
+ readiness.verify(ready, cfg, expected_host="127.0.0.1",
+ expected_instance="one", expected_attestation="f" * 64,
+ timeout=1)
+ self.assertEqual(request.call_count, 1)
+
+ def test_attested_lazy_model_reports_unloaded_without_generation(self):
+ ready = {"bound_host": "127.0.0.1", "bound_port": 1234,
+ "model_id": "fake", "model_state": "unloaded"}
+ with mock.patch.object(readiness, "_request", return_value={
+ "instance": {"id": "one", "launch_attestation": "f" * 64},
+ "model": {"id": "fake", "loaded": False}}) as request:
+ result = readiness.verify(ready, b'{"model_name":"fake"}',
+ expected_host="127.0.0.1", expected_instance="one",
+ expected_attestation="f" * 64, timeout=1)
+ self.assertTrue(result["launch_attested"])
+ self.assertFalse(result["generation_ready"])
+ self.assertEqual(request.call_count, 1)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/terminal/test_logs.py b/tests/terminal/test_logs.py
new file mode 100644
index 000000000..a0a5e2efb
--- /dev/null
+++ b/tests/terminal/test_logs.py
@@ -0,0 +1,158 @@
+"""Read-only activity CLI contract, including retention gaps and portable parity."""
+
+import io
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import threading
+import unittest
+from contextlib import redirect_stdout
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from unittest import mock
+
+from strata_cli.cli import main
+from strata_cli.client import sanitize_telemetry
+from strata_cli.logs import ActivityContinuity, activity_delta
+
+
+ROOT = Path(__file__).resolve().parents[2]
+
+
+def sample(instance, last, seqs):
+ raw = {"schema_version": 1, "instance": {"id": instance, "state": "ready"},
+ "activity": {"last_seq": last, "events": [
+ {"seq": seq, "at": 1_790_000_000.0, "request_id": f"{seq:012x}",
+ "event": "queued", "prompt": "private"} for seq in seqs]}}
+ return sanitize_telemetry(raw)
+
+
+class LogsTests(unittest.TestCase):
+ def test_monitor_continuity_reports_only_observed_gaps_and_resets_on_restart(self):
+ tracker = ActivityContinuity()
+ tracker.add(sample("instance-a", 35, [33, 34, 35]))
+ self.assertEqual(tracker.status(), {"gap": None, "restarted": False, "regressed": False})
+ tracker.add(sample("instance-a", 38, [34, 37, 38]))
+ self.assertEqual(tracker.status()["gap"], {"from_seq": 36, "to_seq": 36})
+ tracker.add(sample("instance-a", 39, [38, 39]))
+ self.assertEqual(tracker.status()["gap"], {"from_seq": 36, "to_seq": 36})
+ tracker.add(sample("instance-b", 2, [1, 2]))
+ self.assertEqual(tracker.status(), {"gap": None, "restarted": True, "regressed": False})
+ tracker.add(sample("instance-b", 40, [38, 39, 40]))
+ self.assertEqual(tracker.status()["gap"], {"from_seq": 3, "to_seq": 37})
+ tracker.add(sample("instance-b", 39, [38, 39]))
+ self.assertTrue(tracker.status()["regressed"])
+
+ def test_quiet_logs_keep_activity_rows_and_json(self):
+ endpoint = mock.Mock()
+ endpoint.snapshot.return_value = sample("quiet-instance", 1, [1])
+ output = io.StringIO()
+ with mock.patch("strata_cli.monitor_commands.Endpoint", return_value=endpoint), \
+ redirect_stdout(output):
+ self.assertEqual(main(["logs", "--quiet"]), 0)
+ self.assertNotIn("Recent request activity", output.getvalue())
+ self.assertIn("queued", output.getvalue())
+ output = io.StringIO()
+ with mock.patch("strata_cli.monitor_commands.Endpoint", return_value=endpoint), \
+ redirect_stdout(output):
+ self.assertEqual(main(["logs", "--quiet", "--json"]), 0)
+ self.assertEqual(json.loads(output.getvalue())["events"][0]["event"], "queued")
+
+ def test_delta_reports_missing_sequences_and_restart_without_duplicates(self):
+ first = sample("instance-a", 35, [33, 34, 35])
+ rows, instance, cursor = activity_delta(first, None, None)
+ self.assertEqual([(r["type"], r.get("from_seq"), r.get("to_seq")) for r in rows],
+ [("gap", 1, 32), ("activity", None, None),
+ ("activity", None, None), ("activity", None, None)])
+ self.assertEqual(activity_delta(first, instance, cursor)[0], [])
+ rows, instance, cursor = activity_delta(sample("instance-a", 39, [35, 38, 39]), instance, cursor)
+ self.assertEqual([(r["type"], r.get("from_seq"), r.get("to_seq")) for r in rows],
+ [("gap", 36, 37), ("activity", None, None), ("activity", None, None)])
+ rows, instance, cursor = activity_delta(sample("instance-b", 2, [1, 2]), instance, cursor)
+ self.assertEqual([r["type"] for r in rows], ["instance_change", "activity", "activity"])
+ self.assertEqual((instance, cursor), ("instance-b", 2))
+
+ def test_follow_jsonl_deduplicates_and_reports_gaps(self):
+ snapshots = [sample("a", 2, [1, 2]), sample("a", 2, [1, 2]),
+ sample("a", 5, [2, 4, 5]), sample("b", 1, [1])]
+ endpoint = mock.Mock()
+ endpoint.snapshot.side_effect = snapshots
+ stdout = io.StringIO()
+ with mock.patch("strata_cli.monitor_commands.Endpoint", return_value=endpoint), \
+ mock.patch("strata_cli.logs.time.sleep", side_effect=[None, None, None, KeyboardInterrupt]), \
+ redirect_stdout(stdout):
+ self.assertEqual(main(["logs", "--follow", "--output", "jsonl"]), 0)
+ records = [json.loads(line) for line in stdout.getvalue().splitlines()]
+ self.assertEqual([r["type"] for r in records],
+ ["activity", "activity", "gap", "activity", "activity", "instance_change", "activity"])
+ self.assertEqual((records[2]["from_seq"], records[2]["to_seq"]), (3, 3))
+ self.assertTrue(all(r["schema_version"] == 1 for r in records))
+ self.assertNotIn("private", stdout.getvalue())
+
+ def test_unsupported_sources_modes_and_absent_activity(self):
+ for args, expected in ((["logs", "--source", "harness", "--output", "json"], 5),
+ (["logs", "--follow", "--output", "json"], 2),
+ (["logs", "--follow", "--json"], 2),
+ (["logs", "--output", "jsonl"], 2),
+ (["logs", "--interval", "0.1", "--output", "json"], 2)):
+ with self.subTest(args=args), redirect_stdout(io.StringIO()) as stream:
+ self.assertEqual(main(args), expected)
+ self.assertEqual(json.loads(stream.getvalue())["error"]["code"], expected)
+ endpoint = mock.Mock()
+ endpoint.snapshot.return_value = sanitize_telemetry({"schema_version": 1, "instance": {"id": "old"}})
+ with mock.patch("strata_cli.monitor_commands.Endpoint", return_value=endpoint), \
+ redirect_stdout(io.StringIO()) as stream:
+ self.assertEqual(main(["logs", "--output", "json"]), 5)
+ self.assertIn("unavailable", json.loads(stream.getvalue())["error"]["message"])
+
+ def test_one_shot_source_and_portable_use_read_only_key(self):
+ requests = []
+ raw = {"schema_version": 1, "instance": {"id": "fixture"},
+ "activity": {"last_seq": 1, "events": [
+ {"seq": 1, "at": 1_790_000_000, "request_id": "000000000001",
+ "event": "finished", "outcome": "stop", "prompt": "private"}]}}
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ requests.append((self.path, self.headers.get("Authorization")))
+ if self.headers.get("Authorization") != "Bearer read-key":
+ self.send_error(403)
+ return
+ body = json.dumps(raw).encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *_args):
+ pass
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ worker = threading.Thread(target=server.serve_forever, daemon=True)
+ worker.start()
+ try:
+ url = f"http://127.0.0.1:{server.server_port}"
+ with tempfile.TemporaryDirectory() as directory:
+ bundle = Path(directory) / "strata-monitor.pyz"
+ subprocess.run([sys.executable, str(ROOT / "packaging/monitor_bundle.py"), "build", str(bundle)],
+ check=True, capture_output=True, text=True)
+ clean_env = {k: v for k, v in os.environ.items() if k not in ("PYTHONPATH", "PYTHONHOME")}
+ clean_env["STRATA_TELEMETRY_KEY"] = "read-key"
+ with mock.patch.dict(os.environ, {"STRATA_TELEMETRY_KEY": "read-key"}), \
+ redirect_stdout(io.StringIO()) as source:
+ self.assertEqual(main(["logs", "--url", url, "--credential-env",
+ "STRATA_TELEMETRY_KEY", "--json"]), 0)
+ portable = subprocess.run([sys.executable, "-S", str(bundle), "logs", "--url", url,
+ "--credential-env", "STRATA_TELEMETRY_KEY", "--output", "json"],
+ cwd=directory, env=clean_env, check=True, capture_output=True, text=True)
+ self.assertEqual(json.loads(source.getvalue()), json.loads(portable.stdout))
+ self.assertEqual(json.loads(portable.stdout)["events"][0]["event"], "finished")
+ self.assertNotIn("private", portable.stdout)
+ self.assertEqual(requests, [("/v1/telemetry", "Bearer read-key")] * 2)
+ finally:
+ server.shutdown()
+ server.server_close()
+ worker.join(timeout=2)
diff --git a/tests/terminal/test_models.py b/tests/terminal/test_models.py
new file mode 100644
index 000000000..a7aad4769
--- /dev/null
+++ b/tests/terminal/test_models.py
@@ -0,0 +1,329 @@
+"""Read-only local inventory of setup-written model run configs."""
+
+import io
+import json
+import os
+import struct
+import tempfile
+import threading
+import unittest
+from contextlib import redirect_stdout
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from unittest import mock
+
+from strata_cli.cli import main
+
+
+def gguf_fixture(*, architecture="qwen4exp", tokenizer=True, expert_type=42,
+ overlapping_tensors=False) -> bytes:
+ def string(value):
+ raw = value.encode()
+ return struct.pack("<Q", len(raw)) + raw
+
+ pairs = [("general.architecture", 8, string(architecture))]
+ if tokenizer:
+ pairs += [("tokenizer.ggml.model", 8, string("gpt2")),
+ ("tokenizer.ggml.tokens", 9, struct.pack("<IQ", 8, 1) + string("a")),
+ ("tokenizer.ggml.merges", 9, struct.pack("<IQ", 8, 1) + string("a b"))]
+ header = (b"GGUF" + struct.pack("<IQQ", 3, 2 if overlapping_tensors else 1, len(pairs)) +
+ b"".join(string(key) + struct.pack("<I", kind) + value for key, kind, value in pairs))
+ elements, payload_bytes = (64, 18) if expert_type == 42 else (256, 144)
+ header += string("blk.0.ffn_gate_exps.weight") + struct.pack(
+ "<IQIQ", 1, elements, expert_type, 0)
+ if overlapping_tensors:
+ header += string("blk.1.ffn_gate_exps.weight") + struct.pack(
+ "<IQIQ", 1, elements, expert_type, 0)
+ return header + b"\x00" * (-len(header) % 32) + b"\x00" * payload_bytes
+
+
+class ModelInventoryTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name)
+ engine = self.root / "engine"
+ engine.write_bytes(b"fake engine")
+ engine.chmod(0o700)
+ tokenizer = self.root / "tokenizer"
+ tokenizer.mkdir()
+ for name in ("vocab.json", "merges.txt", "token_type.json"):
+ (tokenizer / name).write_bytes(b"placeholder")
+ pack = self.root / "pack"
+ pack.mkdir()
+ self.config = self.root / "strata-demo.json"
+ self.config.write_text(json.dumps({
+ "exe": str(engine), "tokenizer": str(tokenizer),
+ "args": ["--pack", str(pack), "--max-context", "32768"],
+ "backend": "cuda", "model_name": "Demo model", "api_key": "do-not-disclose",
+ }), encoding="utf-8")
+
+ def command(self, *args):
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(["models", *args, "--install-dir", str(self.root), "--output", "json"])
+ raw = output.getvalue()
+ self.assertNotIn("do-not-disclose", raw)
+ return code, json.loads(raw)
+
+ def test_list_and_inspect_are_read_only_and_do_not_claim_compatibility(self):
+ (self.root / "strata-demo.shared-settings.json").write_text("{}", encoding="utf-8")
+ before = {path.name: (path.read_bytes(), path.stat().st_mtime_ns)
+ for path in self.root.iterdir() if path.is_file()}
+ code, listed = self.command("list", "--installed")
+ self.assertEqual(code, 0)
+ self.assertEqual(listed["model_count"], 1)
+ item = listed["models"][0]
+ self.assertEqual(item["id"], "demo")
+ self.assertEqual(item["component_status"], "present")
+ self.assertEqual(item["context_tokens"], 32768)
+ self.assertEqual(item["execution_compatibility"], "unverified")
+ self.assertNotIn("args", item)
+ code, inspected = self.command("inspect", "demo")
+ self.assertEqual(code, 0)
+ self.assertEqual(inspected["model"]["source_sha256"], item["source_sha256"])
+ self.assertTrue(inspected["components"]["ok"])
+ after = {path.name: (path.read_bytes(), path.stat().st_mtime_ns)
+ for path in self.root.iterdir() if path.is_file()}
+ self.assertEqual(after, before)
+
+ def test_missing_and_malformed_components_are_distinguished(self):
+ (self.root / "tokenizer" / "vocab.json").unlink()
+ code, listed = self.command("list", "--installed")
+ self.assertEqual(code, 0)
+ self.assertEqual(listed["models"][0]["component_status"], "missing_or_invalid")
+ self.assertIn("COMPONENT_MISSING", listed["models"][0]["issue_codes"])
+ (self.root / "strata-broken.json").write_text("{broken", encoding="utf-8")
+ code, listed = self.command("list", "--installed")
+ self.assertEqual(code, 0)
+ self.assertEqual(listed["model_count"], 2)
+ self.assertEqual(listed["models"][0]["component_status"], "invalid")
+ code, error = self.command("inspect", "broken")
+ self.assertEqual(code, 5)
+ self.assertFalse(error["ok"])
+
+ def test_invalid_ids_and_symlink_configs_are_rejected(self):
+ code, error = self.command("inspect", "../demo")
+ self.assertEqual(code, 2)
+ self.assertFalse(error["ok"])
+ if os.name == "posix":
+ (self.root / "strata-link.json").symlink_to(self.config)
+ code, listed = self.command("list", "--installed")
+ self.assertEqual(code, 0)
+ self.assertEqual(next(row for row in listed["models"] if row["id"] == "link")
+ ["component_status"], "invalid")
+ code, error = self.command("inspect", "link")
+ self.assertEqual(code, 5)
+ self.assertFalse(error["ok"])
+
+ def test_install_dir_must_be_absolute(self):
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(["models", "list", "--installed", "--install-dir", "relative", "--output", "json"])
+ self.assertEqual(code, 5)
+ self.assertFalse(json.loads(output.getvalue())["ok"])
+
+ def test_served_inventory_uses_read_only_telemetry_connection(self):
+ snapshot = {"model": {"id": "served-demo", "loaded": True},
+ "instance": {"id": "instance-123"}}
+ output = io.StringIO()
+ with mock.patch("strata_cli.client.Endpoint.snapshot", return_value=snapshot) as fetch, \
+ redirect_stdout(output):
+ code = main(["models", "list", "--served", "--url", "http://127.0.0.1:8095",
+ "--output", "json"])
+ result = json.loads(output.getvalue())
+ self.assertEqual(code, 0)
+ self.assertEqual(result["scope"], "served_current_instance")
+ self.assertEqual(result["models"], [{"id": "served-demo", "loaded": True,
+ "instance_id": "instance-123",
+ "execution_compatibility": "unverified"}])
+ fetch.assert_called_once_with()
+ output = io.StringIO()
+ with mock.patch("strata_cli.client.Endpoint.snapshot", return_value={
+ "model": {"id": None, "loaded": None}, "instance": {"id": "i"}}), \
+ redirect_stdout(output):
+ code = main(["models", "list", "--served", "--url", "http://127.0.0.1:8095",
+ "--output", "json"])
+ self.assertEqual(code, 0)
+ self.assertEqual(json.loads(output.getvalue())["models"], [])
+
+ def test_served_inventory_reaches_telemetry_with_read_only_key(self):
+ seen = []
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ seen.append((self.path, self.headers.get("Authorization")))
+ if self.path != "/v1/telemetry" or self.headers.get("Authorization") != "Bearer read-only":
+ self.send_error(403)
+ return
+ body = json.dumps({"schema_version": 1,
+ "instance": {"id": "mock-1", "state": "ready"},
+ "model": {"id": "example", "loaded": False}}).encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *args):
+ pass
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ output = io.StringIO()
+ with mock.patch.dict(os.environ, {"STRATA_TELEMETRY_KEY": "read-only"}), \
+ redirect_stdout(output):
+ code = main(["models", "list", "--served", "--url",
+ f"http://127.0.0.1:{server.server_port}",
+ "--credential-env", "STRATA_TELEMETRY_KEY", "--output", "json"])
+ self.assertEqual(code, 0)
+ self.assertEqual(json.loads(output.getvalue())["models"][0]["loaded"], False)
+ self.assertEqual(seen, [("/v1/telemetry", "Bearer read-only")])
+ self.assertNotIn("read-only", output.getvalue())
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=2)
+
+ def test_connection_flags_require_served_scope(self):
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(["models", "list", "--installed", "--url", "https://example.invalid",
+ "--output", "json"])
+ self.assertEqual(code, 2)
+ self.assertFalse(json.loads(output.getvalue())["ok"])
+
+ def test_import_plan_inspects_shards_without_adopting_or_copying(self):
+ source = self.root / "source"
+ source.mkdir()
+ first = source / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf"
+ second = source / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf"
+ for path in (first, second):
+ path.write_bytes(gguf_fixture(tokenizer=path == first))
+ (source / "mmproj-Qwen3.8-Flash-Next-BF16.gguf").write_bytes(b"auxiliary")
+ before = {path.name: (path.read_bytes(), path.stat().st_mtime_ns)
+ for path in source.iterdir()}
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(["models", "import", str(source), "--plan", "--output", "json"])
+ self.assertEqual(code, 0)
+ plan = json.loads(output.getvalue())["plan"]
+ self.assertEqual(plan["file_count"], 2)
+ self.assertEqual(plan["file_set_status"], "plausible")
+ self.assertFalse(plan["would_write"])
+ self.assertEqual(plan["execution_compatibility"], "unverified")
+ self.assertEqual(plan["metadata"]["architecture"], "qwen4exp")
+ self.assertEqual(plan["metadata"]["tokenizer_model"], "gpt2")
+ self.assertTrue(plan["metadata"]["payload_extent_valid"])
+ self.assertEqual(plan["metadata"]["tensor_types"], {"Q2_0": 1})
+ self.assertEqual(plan["observed_expert_types"], ["Q2_0"])
+ self.assertEqual(plan["candidate_selection"]["family"], "qwen")
+ self.assertEqual(plan["candidate_selection"]["model"], "Q2_0")
+ self.assertEqual(len(plan["ignored_auxiliary_files"]), 1)
+ self.assertEqual({path.name: (path.read_bytes(), path.stat().st_mtime_ns)
+ for path in source.iterdir()}, before)
+ second.unlink()
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(["models", "import", str(first), "--plan", "--output", "json"])
+ self.assertEqual(code, 5)
+ self.assertFalse(json.loads(output.getvalue())["ok"])
+ self.assertEqual(json.loads(output.getvalue())["plan"]["file_set_status"],
+ "invalid_or_incomplete")
+
+ def test_import_plan_rejects_symlink_and_wrong_magic(self):
+ wrong = self.root / "bad.gguf"
+ wrong.write_bytes(b"NOTG\x03\x00\x00\x00")
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(["models", "import", str(wrong), "--plan", "--output", "json"])
+ self.assertEqual(code, 5)
+ self.assertFalse(json.loads(output.getvalue())["ok"])
+ self.assertEqual(json.loads(output.getvalue())["plan"]["file_set_status"],
+ "invalid_or_incomplete")
+ if os.name == "posix":
+ link = self.root / "link.gguf"
+ link.symlink_to(wrong)
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(["models", "import", str(link), "--plan", "--output", "json"])
+ self.assertEqual(code, 5)
+ self.assertFalse(json.loads(output.getvalue())["ok"])
+
+ def test_import_plan_rejects_other_architecture_and_bounded_metadata(self):
+ candidate = self.root / "other.gguf"
+ candidate.write_bytes(gguf_fixture(architecture="llama"))
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(["models", "import", str(candidate), "--plan", "--output", "json"])
+ self.assertEqual(code, 5)
+ self.assertIn("unsupported_or_missing_architecture", json.loads(output.getvalue())["plan"]["issues"])
+ # A malicious metadata count must fail before allocating or reading tensor data.
+ candidate.write_bytes(b"GGUF" + struct.pack("<IQQ", 3, 1, 1_000_000_000))
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(["models", "import", str(candidate), "--plan", "--output", "json"])
+ self.assertEqual(code, 5)
+ self.assertEqual(json.loads(output.getvalue())["plan"]["file_set_status"], "invalid_or_incomplete")
+ key = b"tokenizer.ggml.tokens"
+ candidate.write_bytes(b"GGUF" + struct.pack("<IQQ", 3, 1, 1) +
+ struct.pack("<Q", len(key)) + key +
+ struct.pack("<IIQ", 9, 8, 500_001))
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(["models", "import", str(candidate), "--plan", "--output", "json"])
+ self.assertEqual(code, 5)
+ self.assertIn("inspection limit", json.dumps(json.loads(output.getvalue())["plan"]["issues"]))
+
+ def test_import_plan_rejects_truncated_tensor_payload(self):
+ candidate = self.root / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf"
+ candidate.write_bytes(gguf_fixture()[:-4])
+ other = self.root / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf"
+ other.write_bytes(gguf_fixture(tokenizer=False))
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(["models", "import", str(candidate), "--plan", "--output", "json"])
+ self.assertEqual(code, 5)
+ self.assertIn("payload is shorter", json.dumps(json.loads(output.getvalue())["plan"]["issues"]))
+
+ def test_import_plan_rejects_unexpected_expert_quantization(self):
+ source = self.root / "quant"
+ source.mkdir()
+ names = [source / f"Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-{i:05d}-of-00002.gguf" for i in (1, 2)]
+ names[0].write_bytes(gguf_fixture(expert_type=12)) # Q4_K under a Q2_0 filename
+ names[1].write_bytes(gguf_fixture(tokenizer=False))
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(["models", "import", str(source), "--plan", "--output", "json"])
+ self.assertEqual(code, 5)
+ self.assertIn("missing_or_unexpected_expert_quantization",
+ json.loads(output.getvalue())["plan"]["issues"])
+
+ def test_import_plan_rejects_overlapping_tensor_ranges(self):
+ source = self.root / "overlap"
+ source.mkdir()
+ first = source / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf"
+ second = source / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf"
+ first.write_bytes(gguf_fixture(overlapping_tensors=True))
+ second.write_bytes(gguf_fixture(tokenizer=False))
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(["models", "import", str(source), "--plan", "--output", "json"])
+ self.assertEqual(code, 5)
+ self.assertIn("byte ranges overlap", json.dumps(json.loads(output.getvalue())["plan"]["issues"]))
+
+ def test_import_plan_does_not_advertise_setup_unsupported_variant(self):
+ source = self.root / "unsupported"
+ source.mkdir()
+ for index in (1, 2):
+ (source / f"Swift-Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-{index:05d}-of-00002.gguf").write_bytes(
+ gguf_fixture(tokenizer=index == 1))
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(["models", "import", str(source), "--plan", "--output", "json"])
+ self.assertEqual(code, 5)
+ plan = json.loads(output.getvalue())["plan"]
+ self.assertIsNone(plan["candidate_selection"])
+ self.assertIn("unrecognized_or_unsupported_model_variant", plan["issues"])
diff --git a/tests/terminal/test_monitor_bundle.py b/tests/terminal/test_monitor_bundle.py
new file mode 100644
index 000000000..9bfe139f2
--- /dev/null
+++ b/tests/terminal/test_monitor_bundle.py
@@ -0,0 +1,434 @@
+"""Packaged client smoke test without site packages, engine files or model weights."""
+
+import io
+import hashlib
+import importlib.util
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import threading
+import unittest
+import zipfile
+from contextlib import redirect_stdout
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from unittest import mock
+
+from strata_cli.cli import main as source_main
+
+
+ROOT = Path(__file__).resolve().parents[2]
+BUILDER = ROOT / "packaging/monitor_bundle.py"
+SPEC = importlib.util.spec_from_file_location("strata_monitor_bundle_builder", BUILDER)
+assert SPEC is not None and SPEC.loader is not None
+BUILDER_MODULE = importlib.util.module_from_spec(SPEC)
+SPEC.loader.exec_module(BUILDER_MODULE)
+build = BUILDER_MODULE.build
+install = BUILDER_MODULE.install
+uninstall = BUILDER_MODULE.uninstall
+update = BUILDER_MODULE.update
+rollback = BUILDER_MODULE.rollback
+commit = BUILDER_MODULE.commit
+verify = BUILDER_MODULE.verify
+
+
+class MonitorBundleTests(unittest.TestCase):
+ @staticmethod
+ def _candidate(source: Path, destination: Path) -> Path:
+ destination.parent.mkdir()
+ destination.write_bytes(source.read_bytes())
+ with zipfile.ZipFile(destination, "a") as archive:
+ archive.comment = b"candidate client revision"
+ report = json.loads(source.with_name(source.name + ".manifest.json").read_text())
+ report["bundle"] = destination.name
+ report["sha256"] = hashlib.sha256(destination.read_bytes()).hexdigest()
+ destination.with_name(destination.name + ".manifest.json").write_text(json.dumps(report))
+ verify(destination)
+ return destination
+
+ def test_update_rollback_and_commit_keep_one_verified_previous_copy(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ first = root / "first" / "monitor.pyz"
+ first.parent.mkdir()
+ old = build(first)
+ candidate = self._candidate(first, root / "second" / "next-monitor.pyz")
+ next_sha = verify(candidate)["sha256"]
+ target = root / "optional-monitor"
+ install(first, target, if_candidate_sha256=old["sha256"])
+ preview_run = subprocess.run([sys.executable, str(BUILDER), "update", str(candidate),
+ "--target", str(target), "--plan"],
+ capture_output=True, text=True, check=True)
+ preview = json.loads(preview_run.stdout)
+ self.assertEqual((preview["current_sha256"], preview["candidate_sha256"]),
+ (old["sha256"], next_sha))
+ self.assertTrue(preview["would_update"])
+ with self.assertRaisesRegex(ValueError, "preview again"):
+ update(candidate, target, if_current_sha256=old["sha256"],
+ if_candidate_sha256="0" * 64)
+ self.assertFalse((root / "optional-monitor.previous").exists())
+ changed = subprocess.run([sys.executable, str(BUILDER), "update", str(candidate),
+ "--target", str(target), "--if-current-sha256", old["sha256"],
+ "--if-candidate-sha256", next_sha],
+ capture_output=True, text=True, check=True)
+ result = json.loads(changed.stdout)
+ self.assertTrue(result["updated"])
+ previous = root / "optional-monitor.previous"
+ self.assertEqual(verify(target / "next-monitor.pyz")["sha256"], next_sha)
+ self.assertEqual(verify(previous / "monitor.pyz")["sha256"], old["sha256"])
+ with self.assertRaisesRegex(FileExistsError, "previous"):
+ update(candidate, target, plan=True)
+ preview_run = subprocess.run([sys.executable, str(BUILDER), "rollback", "--target",
+ str(target), "--plan"], capture_output=True, text=True, check=True)
+ preview = json.loads(preview_run.stdout)
+ self.assertTrue(preview["would_rollback"])
+ with self.assertRaisesRegex(ValueError, "preview again"):
+ rollback(target, if_active_sha256=old["sha256"], if_rollback_sha256=old["sha256"])
+ original = os.rename
+ calls = 0
+
+ def fail_last_exchange(source, destination):
+ nonlocal calls
+ calls += 1
+ if calls == 3:
+ raise OSError("final exchange failed")
+ return original(source, destination)
+
+ with mock.patch.object(BUILDER_MODULE.os, "rename", side_effect=fail_last_exchange):
+ with self.assertRaisesRegex(OSError, "final exchange failed"):
+ rollback(target, if_active_sha256=next_sha, if_rollback_sha256=old["sha256"])
+ self.assertEqual(verify(target / "next-monitor.pyz")["sha256"], next_sha)
+ self.assertEqual(verify(previous / "monitor.pyz")["sha256"], old["sha256"])
+ self.assertFalse(list(root.glob(".strata-monitor-swap-*")))
+ restored = subprocess.run([sys.executable, str(BUILDER), "rollback", "--target", str(target),
+ "--if-active-sha256", next_sha,
+ "--if-rollback-sha256", old["sha256"]],
+ capture_output=True, text=True, check=True)
+ result = json.loads(restored.stdout)
+ self.assertTrue(result["rolled_back"])
+ self.assertEqual(verify(target / "monitor.pyz")["sha256"], old["sha256"])
+ self.assertEqual(verify(previous / "next-monitor.pyz")["sha256"], next_sha)
+ with self.assertRaisesRegex(ValueError, "commit or rollback"):
+ uninstall(target)
+ planned = commit(target, plan=True)
+ self.assertTrue(planned["would_commit"])
+ accepted = subprocess.run([sys.executable, str(BUILDER), "commit", "--target", str(target),
+ "--if-active-sha256", old["sha256"],
+ "--if-previous-sha256", next_sha],
+ capture_output=True, text=True, check=True)
+ self.assertTrue(json.loads(accepted.stdout)["committed"])
+ self.assertFalse(previous.exists())
+ self.assertTrue(uninstall(target, if_active_sha256=old["sha256"])["removed"])
+
+ def test_update_activation_failure_restores_installed_client(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ first = root / "first" / "monitor.pyz"
+ first.parent.mkdir()
+ old = build(first)
+ candidate = self._candidate(first, root / "second" / "monitor.pyz")
+ next_sha = verify(candidate)["sha256"]
+ target = root / "optional-monitor"
+ install(first, target, if_candidate_sha256=old["sha256"])
+ original = os.rename
+ calls = 0
+
+ def fail_activation(source, destination):
+ nonlocal calls
+ calls += 1
+ if calls == 2:
+ raise OSError("activation failed")
+ return original(source, destination)
+
+ with mock.patch.object(BUILDER_MODULE.os, "rename", side_effect=fail_activation):
+ with self.assertRaisesRegex(OSError, "activation failed"):
+ update(candidate, target, if_current_sha256=old["sha256"],
+ if_candidate_sha256=next_sha)
+ self.assertEqual(verify(target / "monitor.pyz")["sha256"], old["sha256"])
+ self.assertFalse((root / "optional-monitor.previous").exists())
+ self.assertFalse(list(root.glob(".strata-monitor-install-*")))
+
+ original_stage = BUILDER_MODULE._stage_copy
+
+ def change_active_during_copy(bundle, report, destination):
+ stage = original_stage(bundle, report, destination)
+ active_bundle = destination / "monitor.pyz"
+ with zipfile.ZipFile(active_bundle, "a") as archive:
+ archive.comment = b"external owner edit"
+ manifest = active_bundle.with_name(active_bundle.name + ".manifest.json")
+ current = json.loads(manifest.read_text())
+ current["sha256"] = hashlib.sha256(active_bundle.read_bytes()).hexdigest()
+ manifest.write_text(json.dumps(current))
+ return stage
+
+ with mock.patch.object(BUILDER_MODULE, "_stage_copy", side_effect=change_active_during_copy):
+ with self.assertRaisesRegex(ValueError, "changed during copy"):
+ update(candidate, target, if_current_sha256=old["sha256"],
+ if_candidate_sha256=next_sha)
+ self.assertNotEqual(verify(target / "monitor.pyz")["sha256"], old["sha256"])
+ self.assertFalse((root / "optional-monitor.previous").exists())
+ self.assertFalse(list(root.glob(".strata-monitor-install-*")))
+
+ def test_offline_install_plan_and_remove_touch_only_monitor_files(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ bundle = root / "portable-client.pyz"
+ built = build(bundle)
+ target = root / "optional-monitor"
+ preview = subprocess.run([sys.executable, str(BUILDER), "install", str(bundle),
+ "--target", str(target), "--plan"],
+ capture_output=True, text=True, check=True)
+ planned = json.loads(preview.stdout)
+ self.assertTrue(planned["would_install"])
+ self.assertFalse(target.exists())
+ with self.assertRaisesRegex(ValueError, "preview again"):
+ install(bundle, target)
+ with self.assertRaisesRegex(ValueError, "preview again"):
+ install(bundle, target, if_candidate_sha256="0" * 64)
+ self.assertFalse(target.exists())
+ installed_run = subprocess.run([sys.executable, str(BUILDER), "install", str(bundle),
+ "--target", str(target),
+ "--if-candidate-sha256", planned["sha256"]],
+ capture_output=True, text=True, check=True)
+ installed = json.loads(installed_run.stdout)
+ self.assertTrue(installed["installed"])
+ self.assertEqual(verify(target / bundle.name)["sha256"], built["sha256"])
+ self.assertEqual({p.name for p in target.iterdir()},
+ {bundle.name, bundle.name + ".manifest.json"})
+ if os.name == "posix":
+ self.assertEqual(target.stat().st_mode & 0o077, 0)
+ self.assertEqual((target / bundle.name).stat().st_mode & 0o077, 0)
+ portable = subprocess.run([sys.executable, "-I", str(target / bundle.name), "logs", "--help"],
+ cwd=directory, capture_output=True, text=True, check=True)
+ self.assertIn("--follow", portable.stdout)
+ extra = target / "user-notes.txt"
+ extra.write_text("keep me")
+ with self.assertRaisesRegex(ValueError, "unexpected"):
+ uninstall(target)
+ self.assertTrue(extra.exists())
+ extra.unlink()
+ preview_remove = subprocess.run([sys.executable, str(BUILDER), "uninstall",
+ "--target", str(target), "--plan"],
+ capture_output=True, text=True, check=True)
+ self.assertTrue(json.loads(preview_remove.stdout)["would_remove"])
+ self.assertTrue(target.exists())
+ with self.assertRaisesRegex(ValueError, "preview again"):
+ uninstall(target)
+ with self.assertRaisesRegex(ValueError, "preview again"):
+ uninstall(target, if_active_sha256="0" * 64)
+ self.assertTrue(target.exists())
+ removal = subprocess.run([sys.executable, str(BUILDER), "uninstall", "--target",
+ str(target), "--if-active-sha256",
+ json.loads(preview_remove.stdout)["sha256"]],
+ capture_output=True, text=True, check=True)
+ self.assertTrue(json.loads(removal.stdout)["removed"])
+ self.assertFalse(target.exists())
+
+ def test_failed_copy_leaves_no_partial_install(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ bundle = root / "monitor.pyz"
+ built = build(bundle)
+ target = root / "optional-monitor"
+ with mock.patch.object(BUILDER_MODULE.shutil, "copyfile", side_effect=OSError("disk full")):
+ with self.assertRaisesRegex(OSError, "disk full"):
+ install(bundle, target, if_candidate_sha256=built["sha256"])
+ self.assertFalse(target.exists())
+ self.assertFalse(list(root.glob(".strata-monitor-install-*")))
+
+ def test_bundle_verification_rejects_large_or_linked_input(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ bundle = root / "monitor.pyz"
+ build(bundle)
+ linked = root / "linked.pyz"
+ linked.symlink_to(bundle)
+ with self.assertRaisesRegex(ValueError, "bounded regular"):
+ verify(linked)
+ with bundle.open("ab") as stream:
+ stream.write(b"x" * (1024 * 1024))
+ with self.assertRaisesRegex(ValueError, "bounded regular"):
+ verify(bundle)
+ bundle = root / "unsigned.pyz"
+ build(bundle)
+ manifest = bundle.with_name(bundle.name + ".manifest.json")
+ forged = json.loads(manifest.read_text())
+ forged["publisher_signature"] = "pretend-signed"
+ manifest.write_text(json.dumps(forged))
+ with self.assertRaisesRegex(ValueError, "manifest or SHA-256"):
+ verify(bundle)
+ manifest.write_text("[]")
+ with self.assertRaisesRegex(ValueError, "manifest or SHA-256"):
+ verify(bundle)
+
+ def test_versioned_manifest_keeps_legacy_update_and_rollback_available(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ current = root / "monitor.pyz"
+ modern = root / "next-monitor.pyz"
+ previous = root / "previous-monitor.pyz"
+ build(modern)
+ old_visual = root / "visual-monitor.pyz"
+ for old_bundle, version in ((current, 1), (previous, 2), (old_visual, 3)):
+ with zipfile.ZipFile(modern) as source, zipfile.ZipFile(old_bundle, "w", zipfile.ZIP_DEFLATED) as legacy:
+ for item in source.infolist():
+ if item.filename != "strata_cli/detail_dashboard.py" and \
+ (version >= 3 or item.filename != "strata_cli/dashboard.py") and \
+ (version != 1 or item.filename != "LICENSE"):
+ legacy.writestr(item, source.read(item.filename))
+ report = json.loads((root / "next-monitor.pyz.manifest.json").read_text())
+ report["schema_version"] = version
+ report["bundle"] = old_bundle.name
+ report["sha256"] = hashlib.sha256(old_bundle.read_bytes()).hexdigest()
+ del report["files"]["strata_cli/detail_dashboard.py"]
+ if version < 3:
+ del report["files"]["strata_cli/dashboard.py"]
+ if version == 1:
+ del report["files"]["LICENSE"]
+ for field in ("compatibility", "license", "license_file"):
+ del report[field]
+ old_bundle.with_name(old_bundle.name + ".manifest.json").write_text(json.dumps(report))
+ self.assertEqual(verify(current)["schema_version"], 1)
+ self.assertEqual(verify(previous)["schema_version"], 2)
+ self.assertEqual(verify(old_visual)["schema_version"], 3)
+ self.assertEqual(verify(modern)["schema_version"], 4)
+ with zipfile.ZipFile(modern) as archive:
+ self.assertIn(b"MIT License", archive.read("LICENSE"))
+ self.assertIn(b"render_dashboard", archive.read("strata_cli/dashboard.py"))
+ self.assertIn(b"render_detail_dashboard", archive.read("strata_cli/detail_dashboard.py"))
+ target = root / "optional-monitor"
+ install(current, target, if_candidate_sha256=verify(current)["sha256"])
+ preview = update(modern, target, plan=True)
+ self.assertTrue(preview["would_update"])
+ self.assertTrue(update(modern, target, if_current_sha256=preview["current_sha256"],
+ if_candidate_sha256=preview["candidate_sha256"])["updated"])
+ self.assertEqual(verify(target / modern.name)["schema_version"], 4)
+ self.assertEqual(verify(root / "optional-monitor.previous" / current.name)["schema_version"], 1)
+ planned = rollback(target, plan=True)
+ self.assertTrue(rollback(target, if_active_sha256=planned["active_sha256"],
+ if_rollback_sha256=planned["rollback_sha256"])["rolled_back"])
+ self.assertEqual(verify(target / current.name)["schema_version"], 1)
+ second_target = root / "optional-monitor-from-v2"
+ install(previous, second_target, if_candidate_sha256=verify(previous)["sha256"])
+ preview = update(modern, second_target, plan=True)
+ self.assertTrue(update(modern, second_target,
+ if_current_sha256=preview["current_sha256"],
+ if_candidate_sha256=preview["candidate_sha256"])["updated"])
+ self.assertEqual(verify(second_target / modern.name)["schema_version"], 4)
+ planned = rollback(second_target, plan=True)
+ self.assertTrue(rollback(second_target, if_active_sha256=planned["active_sha256"],
+ if_rollback_sha256=planned["rollback_sha256"])["rolled_back"])
+ self.assertEqual(verify(second_target / previous.name)["schema_version"], 2)
+ third_target = root / "optional-monitor-from-v3"
+ install(old_visual, third_target, if_candidate_sha256=verify(old_visual)["sha256"])
+ preview = update(modern, third_target, plan=True)
+ self.assertTrue(update(modern, third_target,
+ if_current_sha256=preview["current_sha256"],
+ if_candidate_sha256=preview["candidate_sha256"])["updated"])
+ planned = rollback(third_target, plan=True)
+ self.assertTrue(rollback(third_target, if_active_sha256=planned["active_sha256"],
+ if_rollback_sha256=planned["rollback_sha256"])["rolled_back"])
+ self.assertEqual(verify(third_target / old_visual.name)["schema_version"], 3)
+
+ def test_manifest_compatibility_and_license_notice_are_checked(self):
+ with tempfile.TemporaryDirectory() as directory:
+ bundle = Path(directory) / "monitor.pyz"
+ built = build(bundle)
+ self.assertEqual(built["compatibility"], {"python_min": "3.10", "telemetry_schema": [1]})
+ self.assertEqual(built["license_file"], "LICENSE")
+ manifest = bundle.with_name(bundle.name + ".manifest.json")
+ edited = json.loads(manifest.read_text())
+ edited["compatibility"]["telemetry_schema"] = [2]
+ manifest.write_text(json.dumps(edited))
+ with self.assertRaisesRegex(ValueError, "compatibility or license"):
+ verify(bundle)
+ edited["schema_version"] = True
+ manifest.write_text(json.dumps(edited))
+ with self.assertRaisesRegex(ValueError, "manifest or SHA-256"):
+ verify(bundle)
+
+ def test_thin_bundle_and_source_share_one_shot_contract(self):
+ snapshot = {"schema_version": 1, "source": "test-server", "sampled_at": 1_790_000_000,
+ "instance": {"id": "test-instance", "state": "ready"},
+ "model": {"id": "fixture-model", "loaded": True},
+ "work": {"active": 2, "queued": 1, "slots_effective": 4,
+ "requests": [{"id": "r1", "state": "reading", "slot": 0,
+ "prompt_tokens": 200, "prompt_read": 50}]}}
+ paths = []
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_GET(self):
+ paths.append(self.path)
+ body = json.dumps(snapshot).encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *_args):
+ pass
+
+ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ with tempfile.TemporaryDirectory() as directory:
+ bundle = Path(directory) / "strata-monitor.pyz"
+ subprocess.run([sys.executable, str(BUILDER), "build", str(bundle)], check=True,
+ capture_output=True, text=True)
+ subprocess.run([sys.executable, str(BUILDER), "verify", str(bundle)], check=True,
+ capture_output=True, text=True)
+ self.assertLess(bundle.stat().st_size, 64 * 1024)
+ with zipfile.ZipFile(bundle) as archive:
+ self.assertIn(b"MIT License", archive.read("LICENSE"))
+ self.assertIn("strata_cli/dashboard.py", archive.namelist())
+ if importlib.util.find_spec("textual") is not None:
+ import_check = subprocess.run(
+ [sys.executable, "-I", "-c",
+ "import sys; sys.path.insert(0, " + repr(str(bundle)) + "); "
+ "from strata_cli.monitor import MonitorApp; print(MonitorApp.__name__)"],
+ cwd=directory, capture_output=True, text=True, check=True)
+ self.assertEqual(import_check.stdout.strip(), "MonitorApp")
+ url = f"http://127.0.0.1:{server.server_port}"
+ source_output = io.StringIO()
+ with redirect_stdout(source_output):
+ self.assertEqual(source_main(["monitor", "--once", "--json", "--url", url]), 0)
+ clean_env = {k: v for k, v in os.environ.items() if k not in ("PYTHONPATH", "PYTHONHOME")}
+ clean_env["STRATA_CONNECTION_DIR"] = str(Path(directory) / "connections")
+ portable = subprocess.run([sys.executable, "-S", str(bundle), "monitor", "--once", "--json",
+ "--url", url], cwd=directory, env=clean_env, check=True,
+ capture_output=True, text=True)
+ self.assertEqual(json.loads(portable.stdout), json.loads(source_output.getvalue()))
+ bare_source = subprocess.run([sys.executable, "-S", str(ROOT / "strata.py"), "monitor",
+ "--once", "--json", "--url", url], cwd=directory, env=clean_env,
+ check=True, capture_output=True, text=True)
+ self.assertEqual(json.loads(bare_source.stdout), json.loads(portable.stdout))
+ status = subprocess.run([sys.executable, "-S", str(bundle), "status", "--json", "--url", url],
+ cwd=directory, env=clean_env, check=True, capture_output=True, text=True)
+ self.assertEqual(json.loads(status.stdout)["snapshot"]["work"]["active"], 2)
+ saved = subprocess.run([sys.executable, "-S", str(bundle), "connection", "list", "--json"],
+ cwd=directory, env=clean_env, check=True, capture_output=True, text=True)
+ self.assertEqual(json.loads(saved.stdout)["connections"], [])
+ quiet_saved = subprocess.run([sys.executable, "-S", str(bundle), "connection", "list", "--quiet"],
+ cwd=directory, env=clean_env, check=True,
+ capture_output=True, text=True)
+ self.assertEqual((quiet_saved.stdout, quiet_saved.stderr), ("", ""))
+ quiet_json = subprocess.run([sys.executable, "-S", str(bundle), "connection", "list",
+ "--quiet", "--json"], cwd=directory, env=clean_env,
+ check=True, capture_output=True, text=True)
+ self.assertEqual(json.loads(quiet_json.stdout)["connections"], [])
+ self.assertEqual(paths, ["/v1/telemetry"] * 4)
+ data = bytearray(bundle.read_bytes())
+ data[-1] ^= 1
+ bundle.write_bytes(data)
+ broken = subprocess.run([sys.executable, str(BUILDER), "verify", str(bundle)],
+ capture_output=True, text=True)
+ self.assertEqual(broken.returncode, 1)
+ self.assertIn("SHA-256 mismatch", broken.stderr)
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=2)
diff --git a/tests/terminal/test_owner_transport.py b/tests/terminal/test_owner_transport.py
new file mode 100644
index 000000000..17ac08f73
--- /dev/null
+++ b/tests/terminal/test_owner_transport.py
@@ -0,0 +1,236 @@
+"""Owner transport contract tests.
+
+These run on every platform and assert the properties the runtime depends on, rather than asserting
+that a particular syscall was used. The Windows path is exercised on POSIX too: the loopback-TCP
+listener and the state-file validation are ordinary Python and can be tested anywhere, so the
+platform branch is not left unverified until someone has a Windows machine.
+
+What is NOT tested here, and cannot be, is whether a Windows named pipe with an owner-only ACL
+behaves as intended — because that implementation does not exist yet. `docs/work/IMPLEMENTATION_STATUS.md`
+records that as the honest difference between the platforms rather than pretending the loopback
+transport is equivalent to it.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import socket
+import stat
+import sys
+import tempfile
+import threading
+import time
+import unittest
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from strata_control import owner_transport as ot # noqa: E402
+
+
+class TestAddressing(unittest.TestCase):
+ def test_unix_address_fits_the_sun_path_limit(self):
+ """A long home directory must not produce an address the kernel rejects."""
+ long_dir = Path("/Users/someone-with-a-very-long-account-name/Documents/deepseek-harness/state")
+ addr = ot.address_for(long_dir, "default")
+ self.assertLessEqual(len(addr.encode()), 90)
+ if ot.WINDOWS:
+ self.assertTrue(addr.startswith("tcp:"))
+ else:
+ self.assertTrue(addr.endswith(".sock"))
+
+ def test_address_is_stable_for_the_same_inputs(self):
+ d = Path("/tmp/strata-runtime")
+ self.assertEqual(ot.address_for(d, "default"), ot.address_for(d, "default"))
+ self.assertNotEqual(ot.address_for(d, "default"), ot.address_for(d, "other"))
+
+
[email protected](ot.WINDOWS, "POSIX socket binding")
+class TestPosixListener(unittest.TestCase):
+ def setUp(self):
+ self.tmp = Path(tempfile.mkdtemp(prefix="strata-transport-"))
+
+ def tearDown(self):
+ import shutil
+ shutil.rmtree(self.tmp, ignore_errors=True)
+
+ def test_round_trip_and_private_permissions(self):
+ addr = ot.address_for(self.tmp, "default")
+ with ot.Listener(addr, timeout=2) as listener:
+ mode = stat.S_IMODE(os.stat(listener.address).st_mode)
+ self.assertEqual(mode, 0o600, "the owner socket must not be reachable by other users")
+
+ received: list[bytes] = []
+
+ def server():
+ conn = listener.accept()
+ assert conn is not None, "the listener timed out"
+ with conn:
+ received.append(conn.recv(4096))
+
+ t = threading.Thread(target=server)
+ t.start()
+ with ot.connect(listener.address, timeout=2) as client:
+ client.sendall(json.dumps({"hello": "owner"}).encode() + b"\n")
+ t.join(timeout=5)
+ self.assertEqual([json.loads(received[0])], [{"hello": "owner"}])
+
+ def test_the_socket_path_is_removed_on_close(self):
+ addr = ot.address_for(self.tmp, "default")
+ listener = ot.Listener(addr)
+ listener.bind()
+ self.assertTrue(Path(listener.address).exists())
+ listener.close()
+ self.assertFalse(Path(listener.address).exists(),
+ "a stale socket path would block the next owner from binding")
+
+ def test_accept_returns_none_on_timeout_rather_than_raising(self):
+ """The owner polls, so a quiet channel must not look like an error."""
+ addr = ot.address_for(self.tmp, "default")
+ with ot.Listener(addr, timeout=0.2) as listener:
+ self.assertIsNone(listener.accept())
+
+ def test_connect_to_a_dead_address_raises_oserror(self):
+ addr = ot.address_for(self.tmp, "nothing-here")
+ with self.assertRaises(OSError):
+ ot.connect(addr, timeout=1)
+
+
+class TestLoopbackTransport(unittest.TestCase):
+ """The Windows branch, exercised on every platform.
+
+ This is the same code Windows runs; only the socket family differs, and `socket.AF_INET` works
+ everywhere. Testing it here means the transport is verified rather than deferred.
+ """
+
+ def setUp(self):
+ self.tmp = Path(tempfile.mkdtemp(prefix="strata-transport-tcp-"))
+
+ def tearDown(self):
+ import shutil
+ shutil.rmtree(self.tmp, ignore_errors=True)
+
+ def _bind_loopback(self) -> ot.Listener:
+ """Bind the way the Windows branch does, regardless of host platform."""
+ original = ot.WINDOWS
+ ot.WINDOWS = True
+ try:
+ listener = ot.Listener("tcp:127.0.0.1:0", timeout=2)
+ listener.bind()
+ return listener
+ finally:
+ ot.WINDOWS = original
+
+ def test_loopback_binds_and_round_trips(self):
+ listener = self._bind_loopback()
+ try:
+ self.assertTrue(listener.address.startswith("tcp:127.0.0.1:"),
+ "the owner must never bind a wildcard address")
+ port = int(listener.address.rsplit(":", 1)[1])
+ self.assertGreater(port, 0)
+ got: list[bytes] = []
+
+ def server():
+ conn = listener.accept()
+ assert conn is not None
+ with conn:
+ got.append(conn.recv(1024))
+
+ t = threading.Thread(target=server)
+ t.start()
+ original = ot.WINDOWS
+ ot.WINDOWS = True
+ try:
+ with ot.connect(listener.address, timeout=2) as client:
+ client.sendall(b"token-check\n")
+ finally:
+ ot.WINDOWS = original
+ t.join(timeout=5)
+ self.assertEqual(got, [b"token-check\n"])
+ finally:
+ listener.close()
+
+ def test_two_owners_cannot_share_the_port(self):
+ """A second owner must fail to bind rather than silently share the channel."""
+ listener = self._bind_loopback()
+ try:
+ port = int(listener.address.rsplit(":", 1)[1])
+ clash = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ try:
+ clash.bind(("127.0.0.1", port))
+ # If the platform allows the rebind, the port is not exclusively held, which would
+ # let a second owner hijack the channel. Fail loudly.
+ self.fail("a second listener bound the owner's port")
+ except OSError:
+ pass
+ finally:
+ clash.close()
+ finally:
+ listener.close()
+
+ def test_it_binds_loopback_only(self):
+ """The listener must not be reachable from another interface."""
+ listener = self._bind_loopback()
+ try:
+ port = int(listener.address.rsplit(":", 1)[1])
+ # Connecting to a non-loopback local address on that port must fail: nothing is bound
+ # there. 203.0.113.0/24 is TEST-NET-3 and is never a local address.
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ s.settimeout(0.5)
+ try:
+ with self.assertRaises(OSError):
+ s.connect(("203.0.113.1", port))
+ finally:
+ s.close()
+ finally:
+ listener.close()
+
+
+class TestStateFileValidation(unittest.TestCase):
+ """A client must refuse a state file it cannot trust."""
+
+ def setUp(self):
+ self.tmp = Path(tempfile.mkdtemp(prefix="strata-state-"))
+ self.path = self.tmp / "default.json"
+ self.path.write_text('{"token": "x"}')
+ os.chmod(self.path, 0o600)
+
+ def tearDown(self):
+ import shutil
+ shutil.rmtree(self.tmp, ignore_errors=True)
+
+ def test_a_private_regular_file_is_accepted(self):
+ ot.check_state_file(self.path)
+
+ @unittest.skipIf(ot.WINDOWS, "POSIX permission bits")
+ def test_a_world_readable_state_file_is_refused(self):
+ os.chmod(self.path, 0o644)
+ with self.assertRaises(ot.TransportError):
+ ot.check_state_file(self.path)
+
+ @unittest.skipIf(ot.WINDOWS, "POSIX symlinks")
+ def test_a_symlink_is_refused(self):
+ link = self.tmp / "link.json"
+ link.symlink_to(self.path)
+ with self.assertRaises(ot.TransportError):
+ ot.check_state_file(link)
+
+ def test_a_directory_is_refused(self):
+ with self.assertRaises(ot.TransportError):
+ ot.check_state_file(self.tmp)
+
+ def test_an_implausibly_large_state_file_is_refused(self):
+ big = self.tmp / "big.json"
+ big.write_bytes(b"x" * (17 * 1024))
+ os.chmod(big, 0o600)
+ with self.assertRaises(ot.TransportError):
+ ot.check_state_file(big)
+
+ def test_a_missing_file_raises_oserror(self):
+ with self.assertRaises(OSError):
+ ot.check_state_file(self.tmp / "nope.json")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/terminal/test_profiles.py b/tests/terminal/test_profiles.py
new file mode 100644
index 000000000..469769348
--- /dev/null
+++ b/tests/terminal/test_profiles.py
@@ -0,0 +1,448 @@
+"""Local profile and component workflows without a GPU or network service."""
+
+import io
+import json
+import os
+import subprocess
+import tempfile
+import unittest
+from contextlib import redirect_stderr, redirect_stdout
+from pathlib import Path
+from unittest import mock
+
+from strata_cli.cli import main
+from strata_control import doctor, profiles, runtime
+
+
+class OperatorProfileTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name)
+ self.env = mock.patch.dict(os.environ, {"STRATA_PROFILE_DIR": str(self.root / "profiles"),
+ "STRATA_RUNTIME_DIR": str(self.root / "runtime"),
+ "STRATA_API_KEY": ""})
+ self.env.start()
+ self.addCleanup(self.env.stop)
+ engine = self.root / "engine"
+ engine.write_text("engine placeholder", encoding="utf-8")
+ engine.chmod(0o700)
+ tokenizer = self.root / "tokenizer"
+ tokenizer.mkdir()
+ for name in ("vocab.json", "merges.txt", "token_type.json"):
+ (tokenizer / name).write_text("{}", encoding="utf-8")
+ pack = self.root / "pack"
+ pack.mkdir()
+ shard = self.root / "model.gguf"
+ shard.write_bytes(b"model placeholder")
+ self.shard = shard
+ self.config = self.root / "run.json"
+ self.config.write_text(json.dumps({"exe": str(engine), "args": ["--pack", str(pack), "--native", str(shard)],
+ "cwd": str(self.root), "tokenizer": str(tokenizer),
+ "model_name": "test-model", "port": 8095}), encoding="utf-8")
+
+ def command(self, *args):
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(list(args))
+ return code, json.loads(output.getvalue())
+
+ def test_saved_overrides_drive_serve_plan_without_rewriting_run_config_or_starting(self):
+ before = self.config.read_bytes()
+ code, created = self.command("profile", "create", "four-gpu", "--from-config", str(self.config),
+ "--output", "json")
+ self.assertEqual(code, 0)
+ self.assertEqual(created["profile"]["overrides"], {})
+ code, changed = self.command("profile", "set", "four-gpu", "parallel=8", "batch_groups=2",
+ "max_queue=32", "queue_timeout=12.5", "batch_telemetry=true",
+ "--output", "json")
+ self.assertEqual(code, 0)
+ self.assertNotEqual(changed["revision"], created["revision"])
+ with mock.patch("serve.server.main", side_effect=AssertionError("server started")):
+ code, planned = self.command("serve", "--profile", "four-gpu", "--plan", "--output", "json")
+ self.assertEqual(code, 0)
+ plan = planned["plan"]
+ self.assertEqual(plan["effective"]["parallel"], 8)
+ self.assertEqual(plan["effective"]["batch_groups"], 2)
+ self.assertEqual(plan["effective"]["max_queue"], 32)
+ self.assertEqual(plan["effective"]["queue_timeout"], 12.5)
+ self.assertTrue(plan["effective"]["batch_telemetry"])
+ self.assertEqual(plan["origin"]["parallel"], "saved_profile")
+ self.assertEqual(plan["engine_argv"][-4:], ["--batch-groups", "2", "--batch", "8"])
+ self.assertIn("--max-queue", plan["server_argv"])
+ self.assertIn("--batch-telemetry", plan["server_argv"])
+ self.assertEqual(plan["server_argv"][plan["server_argv"].index("--queue-timeout") + 1], "12.5")
+ self.assertEqual(self.config.read_bytes(), before)
+ self.assertEqual(len(list((self.root / "profiles" / ".history" / "four-gpu").glob("*.json"))), 1)
+
+ def test_saved_profile_is_used_by_actual_foreground_serve_call(self):
+ profiles.create("local", str(self.config))
+ profiles.set_values("local", ["parallel=4", "max_queue=7"])
+ with mock.patch("serve.server.main", return_value=0) as server:
+ self.assertEqual(main(["serve", "--profile", "local"]), 0)
+ argv = server.call_args.args[0]
+ self.assertEqual(server.call_args.kwargs["interrupt_exit_code"], 130)
+ self.assertIn(str(self.config.resolve()), argv)
+ self.assertEqual(argv[argv.index("--parallel") + 1], "4")
+ self.assertEqual(argv[argv.index("--max-queue") + 1], "7")
+
+ def test_json_alias_is_one_shot_and_keeps_machine_errors(self):
+ code, listed = self.command("profile", "list", "--json")
+ self.assertEqual(code, 0)
+ self.assertTrue(listed["ok"])
+ self.assertEqual(listed["profiles"], [])
+ with mock.patch("serve.server.main", side_effect=AssertionError("server started")):
+ code, planned = self.command("serve", "--profile", str(self.config), "--plan", "--json")
+ self.assertEqual(code, 0)
+ self.assertTrue(planned["ok"])
+ self.assertIn("plan", planned)
+ code, no_plan = self.command("serve", "--profile", str(self.config), "--json")
+ self.assertEqual(code, 2)
+ self.assertEqual(no_plan["error"]["code"], 2)
+ code, stream = self.command("serve", "--profile", str(self.config), "--json",
+ "--output", "jsonl")
+ self.assertEqual(code, 2)
+ self.assertEqual(stream["event"], "failed")
+ code, harness = self.command("code", "sessions", "list", "--json")
+ self.assertEqual(code, 5)
+ self.assertEqual(harness["error"]["code"], 5)
+
+ def test_quiet_suppresses_human_success_but_preserves_errors_and_json(self):
+ output, diagnostics = io.StringIO(), io.StringIO()
+ with redirect_stdout(output), redirect_stderr(diagnostics):
+ self.assertEqual(main(["profile", "list", "--quiet"]), 0)
+ self.assertEqual(main(["serve", "--profile", str(self.config), "--plan", "--quiet"]), 0)
+ self.assertEqual((output.getvalue(), diagnostics.getvalue()), ("", ""))
+ with redirect_stdout(output), redirect_stderr(diagnostics):
+ self.assertEqual(main(["profile", "list", "--quiet", "--json"]), 0)
+ self.assertTrue(json.loads(output.getvalue())["ok"])
+ output, diagnostics = io.StringIO(), io.StringIO()
+ with redirect_stdout(output), redirect_stderr(diagnostics):
+ self.assertNotEqual(main(["profile", "show", "missing", "--quiet"]), 0)
+ self.assertEqual(output.getvalue(), "")
+ self.assertIn("strata:", diagnostics.getvalue())
+ output, diagnostics = io.StringIO(), io.StringIO()
+ def failed_operation(_a):
+ print("x" * 70_000)
+ print("failure detail")
+ return 5
+ with mock.patch("strata_cli.cli._profile_command", side_effect=failed_operation):
+ with redirect_stdout(output), redirect_stderr(diagnostics):
+ self.assertEqual(main(["profile", "list", "--quiet"]), 5)
+ self.assertEqual(output.getvalue(), "")
+ self.assertLess(len(diagnostics.getvalue()), 66_000)
+ self.assertIn("earlier human output omitted", diagnostics.getvalue())
+ self.assertIn("failure detail", diagnostics.getvalue())
+
+ def test_quiet_foreground_serve_hides_human_banner(self):
+ output = io.StringIO()
+ with mock.patch("serve.server.main", side_effect=lambda *_args, **_kwargs: print("ready banner") or 0):
+ with redirect_stdout(output):
+ self.assertEqual(main(["serve", "--profile", str(self.config), "--quiet"]), 0)
+ self.assertEqual(output.getvalue(), "")
+ output, diagnostics = io.StringIO(), io.StringIO()
+ with mock.patch("serve.server.main", return_value=8):
+ with redirect_stdout(output), redirect_stderr(diagnostics):
+ self.assertEqual(main(["serve", "--profile", str(self.config), "--quiet"]), 8)
+ self.assertEqual(output.getvalue(), "")
+ self.assertIn("drain deadline expired", diagnostics.getvalue())
+
+ def test_foreground_jsonl_rejects_plan_and_bad_profile_as_events(self):
+ code, invalid = self.command("serve", "--profile", str(self.config), "--plan",
+ "--output", "jsonl")
+ self.assertEqual(code, 2)
+ self.assertEqual(invalid["event"], "failed")
+ self.assertEqual(invalid["exit_code"], 2)
+ code, missing = self.command("serve", "--profile", "missing-profile",
+ "--output", "jsonl")
+ self.assertNotEqual(code, 0)
+ self.assertEqual(missing["event"], "failed")
+ self.assertEqual(missing["exit_code"], code)
+
+ def test_foreground_jsonl_reports_startup_failure_without_human_stdout(self):
+ output, diagnostics = io.StringIO(), io.StringIO()
+ with mock.patch("serve.server.main", side_effect=SystemExit("engine refused to start")):
+ with redirect_stdout(output), redirect_stderr(diagnostics):
+ code = main(["serve", "--profile", str(self.config), "--output", "jsonl"])
+ rows = [json.loads(line) for line in output.getvalue().splitlines()]
+ self.assertEqual(code, 6)
+ self.assertEqual([row["event"] for row in rows], ["starting", "failed"])
+ self.assertEqual(rows[-1]["phase"], "startup")
+ self.assertNotIn("engine refused to start", output.getvalue())
+ self.assertIn("startup failed", diagnostics.getvalue())
+
+ @unittest.skipUnless(os.name == "posix", "managed activity lease is POSIX-only")
+ def test_foreground_serve_holds_shared_lease_until_server_returns(self):
+ profiles.create("local", str(self.config))
+
+ def running_server(argv, **_kwargs):
+ with self.assertRaisesRegex(profiles.ProfileError, "engine lease"):
+ runtime.acquire_activity_lease(shared=False)
+ return 0
+
+ with mock.patch("serve.server.main", side_effect=running_server):
+ self.assertEqual(main(["serve", "--profile", "local"]), 0)
+ exclusive = runtime.acquire_activity_lease(shared=False)
+ os.close(exclusive)
+
+ def test_batch_telemetry_precedence_can_disable_a_run_config(self):
+ cfg = json.loads(self.config.read_text())
+ cfg["batch_telemetry"] = True
+ self.config.write_text(json.dumps(cfg))
+ profiles.create("local", str(self.config))
+ code, inherited = self.command("serve", "--profile", "local", "--plan", "--output", "json")
+ self.assertEqual(code, 0)
+ self.assertTrue(inherited["plan"]["effective"]["batch_telemetry"])
+ self.assertEqual(inherited["plan"]["origin"]["batch_telemetry"], "run_config")
+ profiles.set_values("local", ["batch_telemetry=false"])
+ code, disabled = self.command("serve", "--profile", "local", "--plan", "--output", "json")
+ self.assertEqual(code, 0)
+ self.assertFalse(disabled["plan"]["effective"]["batch_telemetry"])
+ self.assertIn("--no-batch-telemetry", disabled["plan"]["server_argv"])
+ code, enabled = self.command("serve", "--profile", "local", "--batch-telemetry",
+ "--plan", "--output", "json")
+ self.assertEqual(code, 0)
+ self.assertEqual(enabled["plan"]["origin"]["batch_telemetry"], "command")
+ self.assertIn("--batch-telemetry", enabled["plan"]["server_argv"])
+
+ def test_serve_plan_validates_ready_file_without_writing_it(self):
+ profiles.create("local", str(self.config))
+ ready = self.root / "ready.json"
+ code, result = self.command("serve", "--profile", "local", "--ready-file", str(ready),
+ "--plan", "--output", "json")
+ self.assertEqual(code, 0)
+ self.assertEqual(result["plan"]["ready_file"], str(ready))
+ self.assertFalse(ready.exists())
+ ready.write_text("stale", encoding="utf-8")
+ code, result = self.command("serve", "--profile", "local", "--ready-file", str(ready),
+ "--plan", "--output", "json")
+ self.assertEqual(code, 2)
+ self.assertFalse(result["ok"])
+
+ def test_stale_edit_rejected_and_bad_editor_content_keeps_saved_revision(self):
+ profiles.create("local", str(self.config))
+ current, old_revision = profiles.load("local")
+ profiles.set_values("local", ["parallel=4"])
+ with self.assertRaisesRegex(profiles.ProfileError, "changed during edit"):
+ profiles.save("local", current, expected_revision=old_revision)
+ _, current_revision = profiles.load("local")
+
+ def corrupt(command, check):
+ Path(command[-1]).write_text("{invalid", encoding="utf-8")
+ return mock.Mock(returncode=0)
+
+ with mock.patch.dict(os.environ, {"EDITOR": "fake-editor", "VISUAL": ""}), \
+ mock.patch("strata_control.profiles.subprocess.run", side_effect=corrupt):
+ code, result = self.command("profile", "edit", "local", "--output", "json")
+ self.assertEqual(code, 2)
+ self.assertFalse(result["ok"])
+ draft_path = Path(result["error"]["message"].split("draft kept at ", 1)[1])
+ self.assertTrue(draft_path.is_file())
+ self.assertEqual(draft_path.read_text(encoding="utf-8"), "{invalid")
+ self.assertEqual(profiles.load("local")[1], current_revision)
+
+ def test_plan_then_history_and_rollback_restore_saved_settings_only(self):
+ before = self.config.read_bytes()
+ profiles.create("local", str(self.config))
+ _, first = profiles.load("local")
+ code, planned = self.command("profile", "set", "local", "parallel=8", "--plan", "--output", "json")
+ self.assertEqual(code, 0)
+ self.assertTrue(planned["would_save"])
+ self.assertEqual(planned["changes"]["parallel"], {"before": None, "after": 8})
+ self.assertEqual(profiles.load("local")[1], first)
+ code, changed = self.command("profile", "set", "local", "parallel=8", "--output", "json")
+ self.assertEqual(code, 0)
+ code, listing = self.command("profile", "history", "local", "--output", "json")
+ self.assertEqual(code, 0)
+ self.assertEqual(listing["history"][0]["revision"], changed["revision"])
+ self.assertIn(first, [item["revision"] for item in listing["history"]])
+ code, restored = self.command("profile", "rollback", "local", "--to", first, "--output", "json")
+ self.assertEqual(code, 0)
+ self.assertEqual(restored["revision"], first)
+ self.assertEqual(restored["profile"]["overrides"], {})
+ self.assertEqual(self.config.read_bytes(), before)
+
+ def test_use_config_previews_and_saves_a_new_model_source_without_editing_either_config(self):
+ profiles.create("local", str(self.config))
+ old_profile, old_revision = profiles.load("local")
+ next_config = self.root / "next.json"
+ next_value = json.loads(self.config.read_text(encoding="utf-8"))
+ next_value["model_name"] = "next-model"
+ next_config.write_text(json.dumps(next_value), encoding="utf-8")
+ before = (self.config.read_bytes(), next_config.read_bytes())
+ code, preview = self.command("profile", "use-config", "local", "--from-config",
+ str(next_config), "--plan", "--output", "json")
+ self.assertEqual(code, 0)
+ self.assertTrue(preview["would_save"])
+ self.assertEqual(preview["revision"], old_revision)
+ self.assertEqual(preview["model_name"], "next-model")
+ self.assertEqual(profiles.load("local"), (old_profile, old_revision))
+ code, unavailable = self.command("profile", "use-config", "local", "--from-config",
+ str(self.root / "missing.json"), "--output", "json")
+ self.assertEqual(code, 5)
+ self.assertFalse(unavailable["ok"])
+ self.assertEqual(profiles.load("local"), (old_profile, old_revision))
+ code, stale = self.command("profile", "use-config", "local", "--from-config",
+ str(next_config), "--if-revision", "0" * 16, "--output", "json")
+ self.assertEqual(code, 6)
+ self.assertFalse(stale["ok"])
+ code, saved = self.command("profile", "use-config", "local", "--from-config",
+ str(next_config), "--if-revision", old_revision, "--output", "json")
+ self.assertEqual(code, 0)
+ self.assertEqual(saved["profile"]["source_config"], str(next_config.resolve()))
+ self.assertNotEqual(saved["revision"], old_revision)
+ self.assertEqual((self.config.read_bytes(), next_config.read_bytes()), before)
+ self.assertIn(old_revision, [row["revision"] for row in profiles.history("local")])
+
+ def test_doctor_distinguishes_required_missing_from_unverified_optional(self):
+ profiles.create("local", str(self.config))
+ code, result = self.command("doctor", "--profile", "local", "--components", "--output", "json")
+ self.assertEqual(code, 0)
+ self.assertTrue(result["report"]["ok"])
+ self.assertEqual(result["report"]["integrity"], "unverified_no_manifest_hashes")
+ self.shard.unlink()
+ code, result = self.command("components", "verify", "--profile", "local", "--output", "json")
+ self.assertEqual(code, 5)
+ self.assertFalse(result["report"]["ok"])
+ self.assertTrue(any(i["component"] == "native" for i in result["report"]["issues"]))
+
+ def test_monitor_inventory_checks_the_optional_pinned_version(self):
+ pinned = (Path(__file__).resolve().parents[2] / "requirements-monitor.txt").read_text()
+ self.assertIn(f"textual=={doctor.MONITOR_TEXTUAL_VERSION}", pinned)
+ with mock.patch.object(doctor.util, "find_spec", return_value=None):
+ missing = doctor._monitor_component()
+ self.assertEqual(missing["status"], "optional_missing")
+ with mock.patch.object(doctor.util, "find_spec", return_value=object()), \
+ mock.patch.object(doctor.metadata, "version", return_value="8.2.8"):
+ present = doctor._monitor_component()
+ self.assertEqual(present["status"], "ok")
+ self.assertEqual(present["check"], "package_version_only")
+ with mock.patch.object(doctor.util, "find_spec", return_value=object()), \
+ mock.patch.object(doctor.metadata, "version", return_value="9.0.0"):
+ changed = doctor._monitor_component()
+ self.assertEqual(changed["status"], "unverified")
+ self.assertEqual(changed["version"], "9.0.0")
+ with mock.patch.object(doctor.util, "find_spec", return_value=object()), \
+ mock.patch.object(doctor.metadata, "version",
+ side_effect=doctor.metadata.PackageNotFoundError("textual")):
+ unknown = doctor._monitor_component()
+ self.assertEqual(unknown["status"], "unverified")
+
+ output = io.StringIO()
+ with mock.patch.object(doctor, "_monitor_component", return_value=changed), redirect_stdout(output):
+ code = main(["doctor"])
+ self.assertEqual(code, 0) # an optional version does not stop serving
+ self.assertIn("interactive monitor was qualified with Textual 8.2.8", output.getvalue())
+
+ def test_live_doctor_checks_four_selected_nvidia_cards_without_starting_engine(self):
+ config = json.loads(self.config.read_text(encoding="utf-8"))
+ config["gpu"] = [0, 1, 2, 3]
+ config["backend"] = "cuda"
+ self.config.write_text(json.dumps(config), encoding="utf-8")
+ profiles.create("four-gpu", str(self.config))
+ cards = "\n".join(f"{i}, RTX 6000 test {i}, GPU-test-{i}, 49140, 580.95" for i in range(4))
+ with mock.patch("strata_control.doctor.shutil.which", return_value="/fake/nvidia-smi"), \
+ mock.patch("strata_control.doctor.subprocess.run",
+ return_value=mock.Mock(returncode=0, stdout=cards)) as probe:
+ code, result = self.command("doctor", "--profile", "four-gpu", "--live", "--output", "json")
+ self.assertEqual(code, 0)
+ self.assertEqual(result["report"]["live_gpu_probe"]["status"], "ok")
+ self.assertEqual(result["report"]["live_gpu_probe"]["selected_indices"], [0, 1, 2, 3])
+ self.assertEqual(len(result["report"]["live_gpu_probe"]["cards"]), 4)
+ self.assertEqual(probe.call_args.kwargs["timeout"], 5)
+ self.assertFalse(probe.call_args.kwargs.get("shell", False))
+
+ with mock.patch("strata_control.doctor.shutil.which", return_value="/fake/nvidia-smi"), \
+ mock.patch("strata_control.doctor.subprocess.run",
+ return_value=mock.Mock(returncode=0, stdout=cards.rsplit("\n", 1)[0])):
+ code, result = self.command("components", "verify", "--profile", "four-gpu", "--live",
+ "--output", "json")
+ self.assertEqual(code, 5)
+ self.assertEqual(result["report"]["live_gpu_probe"]["status"], "missing_selected")
+ self.assertTrue(any(i["code"] == "GPU_NOT_VISIBLE" for i in result["report"]["issues"]))
+
+ def test_live_probe_failure_and_unsupported_hip_are_explicit(self):
+ config = json.loads(self.config.read_text(encoding="utf-8"))
+ config["gpu"] = [0, 1]
+ config["backend"] = "cuda"
+ self.config.write_text(json.dumps(config), encoding="utf-8")
+ profiles.create("local", str(self.config))
+ with mock.patch("strata_control.doctor.shutil.which", return_value=None):
+ code, result = self.command("doctor", "--profile", "local", "--live", "--output", "json")
+ self.assertEqual(code, 5)
+ self.assertEqual(result["report"]["live_gpu_probe"]["status"], "unavailable")
+ self.assertTrue(any(i["code"] == "LIVE_GPU_PROBE_UNAVAILABLE" for i in result["report"]["issues"]))
+
+ config["backend"] = "hip"
+ self.config.write_text(json.dumps(config), encoding="utf-8")
+ with mock.patch("strata_control.doctor.subprocess.run",
+ side_effect=AssertionError("NVIDIA probe must not run for HIP")):
+ code, result = self.command("doctor", "--profile", "local", "--live", "--output", "json")
+ self.assertEqual(code, 5)
+ self.assertEqual(result["report"]["live_gpu_probe"]["status"], "unverified")
+
+ def test_doctor_default_does_not_run_host_probe(self):
+ profiles.create("local", str(self.config))
+ with mock.patch("strata_control.doctor.subprocess.run",
+ side_effect=AssertionError("default doctor must be offline")):
+ code, result = self.command("doctor", "--profile", "local", "--output", "json")
+ self.assertEqual(code, 0)
+ self.assertIsNone(result["report"]["live_gpu_probe"])
+ with mock.patch("strata_control.doctor.subprocess.run",
+ side_effect=AssertionError("a profile is required for live probes")):
+ code, missing = self.command("doctor", "--live", "--output", "json")
+ self.assertEqual(code, 5)
+ self.assertTrue(any(i["code"] == "PROFILE_NOT_SELECTED_FOR_LIVE_PROBE"
+ for i in missing["report"]["issues"]))
+
+ def test_live_probe_rejects_untrusted_card_output_and_timeouts(self):
+ config = json.loads(self.config.read_text(encoding="utf-8"))
+ config["gpu"] = 0
+ config["backend"] = "cuda"
+ self.config.write_text(json.dumps(config), encoding="utf-8")
+ profiles.create("local", str(self.config))
+ for output in ("0, GPU\x1b[31m, GPU-0, 1000, 580.95",
+ "0, GPU, GPU-0, 1000, 580.95\n0, GPU, GPU-0, 1000, 580.95",
+ "0, GPU, GPU-0, not-a-number, 580.95"):
+ with self.subTest(output=output), \
+ mock.patch("strata_control.doctor.shutil.which", return_value="/fake/nvidia-smi"), \
+ mock.patch("strata_control.doctor.subprocess.run",
+ return_value=mock.Mock(returncode=0, stdout=output)):
+ code, result = self.command("doctor", "--profile", "local", "--live", "--output", "json")
+ self.assertEqual(code, 5)
+ self.assertEqual(result["report"]["live_gpu_probe"]["status"], "unavailable")
+ with mock.patch("strata_control.doctor.shutil.which", return_value="/fake/nvidia-smi"), \
+ mock.patch("strata_control.doctor.subprocess.run",
+ side_effect=subprocess.TimeoutExpired("nvidia-smi", 5)):
+ code, result = self.command("doctor", "--profile", "local", "--live", "--output", "json")
+ self.assertEqual(code, 5)
+ self.assertEqual(result["report"]["live_gpu_probe"]["status"], "unavailable")
+
+ def test_calibration_preview_has_no_engine_or_config_side_effects(self):
+ profiles.create("local", str(self.config))
+ before = self.config.read_bytes()
+ with mock.patch("serve.server.StrataEngine", side_effect=AssertionError("engine started")), \
+ mock.patch("tools.calibrate.run", side_effect=AssertionError("measurement started")):
+ code, result = self.command("engine", "calibrate", "--profile", "local", "--plan", "--output", "json")
+ self.assertEqual(code, 0)
+ self.assertFalse(result["plan"]["would_start_engine"])
+ self.assertFalse(result["plan"]["would_write_config"])
+ self.assertEqual(self.config.read_bytes(), before)
+
+ def test_invalid_profile_names_and_types_do_not_escape_store(self):
+ for name in ("../outside", "UPPER", "a/b", ".hidden"):
+ with self.assertRaises(profiles.ProfileError):
+ profiles.create(name, str(self.config))
+ profiles.create("local", str(self.config))
+ for assignment in ("parallel=0", "max_queue=99999", "queue_timeout=nan",
+ "queue_timeout=0", "offline=yes", "batch_telemetry=yes", "host=bad host"):
+ with self.assertRaises(profiles.ProfileError):
+ profiles.set_values("local", [assignment])
+ profiles.set_values("local", ["queue_timeout=5"])
+ with self.assertRaisesRegex(profiles.ProfileError, "requires max_queue"):
+ from strata_cli.cli import _launch_plan
+ _launch_plan("local")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/terminal/test_ready.py b/tests/terminal/test_ready.py
new file mode 100644
index 000000000..efcfa6970
--- /dev/null
+++ b/tests/terminal/test_ready.py
@@ -0,0 +1,69 @@
+"""Ready-file lifecycle checked against a live mock Strata API process."""
+
+import json
+import os
+import signal
+import stat
+import subprocess
+import sys
+import tempfile
+import time
+import unittest
+from pathlib import Path
+
+from serve.ready import preflight, publish, remove_if_owned
+
+
+class ReadyFileTests(unittest.TestCase):
+ def test_owner_only_file_is_never_removed_for_another_instance(self):
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "ready.json"
+ self.assertEqual(preflight(str(path)), path)
+ publish(path, {"schema_version": 1, "instance_id": "one", "pid": os.getpid()})
+ if os.name != "nt":
+ self.assertEqual(stat.S_IMODE(path.stat().st_mode), 0o600)
+ with self.assertRaisesRegex(ValueError, "already exists"):
+ preflight(str(path))
+ remove_if_owned(path, "other")
+ self.assertTrue(path.exists())
+ remove_if_owned(path, "one")
+ self.assertFalse(path.exists())
+
+ @unittest.skipIf(os.name == "nt", "Windows console stop needs a platform-specific integration runner")
+ def test_mock_server_publishes_bound_port_and_cleans_on_sigterm(self):
+ root = Path(__file__).resolve().parents[2]
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "ready.json"
+ env = os.environ.copy()
+ env.pop("STRATA_API_KEY", None)
+ env.pop("STRATA_TELEMETRY_KEY", None)
+ process = subprocess.Popen([sys.executable, "-m", "serve.server", "--engine", "mock", "--port", "0",
+ "--ready-file", str(path)], cwd=root, env=env,
+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
+ try:
+ deadline = time.monotonic() + 10
+ record = None
+ while time.monotonic() < deadline and process.poll() is None:
+ try:
+ record = json.loads(path.read_text(encoding="utf-8"))
+ break
+ except (FileNotFoundError, json.JSONDecodeError):
+ time.sleep(0.05)
+ self.assertIsNotNone(record, process.stderr.read().decode("utf-8", "replace") if process.poll() is not None else "")
+ self.assertEqual(record["pid"], process.pid)
+ self.assertEqual(record["api_state"], "ready")
+ self.assertEqual(record["model_state"], "ready")
+ self.assertGreater(record["bound_port"], 0)
+ self.assertNotIn("key", json.dumps(record).lower())
+ process.send_signal(signal.SIGTERM)
+ self.assertEqual(process.wait(timeout=10), 0)
+ self.assertFalse(path.exists())
+ finally:
+ if process.poll() is None:
+ process.kill()
+ process.wait(timeout=5)
+ process.stderr.close()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/terminal/test_recipes.py b/tests/terminal/test_recipes.py
new file mode 100644
index 000000000..c652f5b4c
--- /dev/null
+++ b/tests/terminal/test_recipes.py
@@ -0,0 +1,353 @@
+"""Owner-editable typed operations; previews never run or write an operation."""
+
+import io
+import json
+import os
+import stat
+import subprocess
+import sys
+import tempfile
+import unittest
+from contextlib import redirect_stdout
+from pathlib import Path
+from unittest import mock
+
+from strata_cli.cli import main
+from strata_control import journal, profiles, recipes
+
+
+class RecipeTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name)
+ environment = mock.patch.dict(os.environ, {"STRATA_PROFILE_DIR": str(self.root / "profiles"),
+ "XDG_CONFIG_HOME": str(self.root / "settings")})
+ environment.start()
+ self.addCleanup(environment.stop)
+ engine = self.root / "engine"
+ engine.write_bytes(b"fake engine")
+ engine.chmod(0o700)
+ tokenizer = self.root / "tokenizer"
+ tokenizer.mkdir()
+ for name in ("vocab.json", "merges.txt", "token_type.json"):
+ (tokenizer / name).write_text("{}", encoding="utf-8")
+ self.config = self.root / "run.json"
+ self.config.write_text(json.dumps({"exe": str(engine), "tokenizer": str(tokenizer),
+ "args": [], "cwd": str(self.root), "model_name": "fake",
+ "host": "127.0.0.1", "port": 0}), encoding="utf-8")
+ profiles.create("local", str(self.config))
+
+ def _cli(self, *args):
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(["ops", *args, "--profile", "local", "--output", "json"])
+ return code, json.loads(output.getvalue())
+
+ def test_benchmark_job_receipt_is_readable_by_new_owner_bridge_process(self):
+ _, revision = profiles.load("local")
+ job_id = "a" * 32
+ intent = {"path": str(self.root / "future-benchmark"), "suite": "serving-smoke",
+ "concurrency": 2, "repeat": 1, "request_timeout": 30,
+ "condition": "baseline", "if_profile_revision": revision,
+ "if_source_sha256": "b" * 64,
+ "if_owner_id": "c" * 32, "if_instance_id": "d" * 32}
+ journal.begin_direct("local", "bench.run", revision, intent, operation_id=job_id)
+ request = {"schema_version": 1, "action": "bench.job", "profile": "local",
+ "params": {"job_id": job_id}}
+ process = subprocess.run([sys.executable, "-m", "strata_control.management"],
+ input=json.dumps(request), text=True, capture_output=True,
+ cwd=Path(__file__).resolve().parents[2], timeout=10, check=True)
+ response = json.loads(process.stdout)
+ self.assertTrue(response["ok"])
+ self.assertEqual(response["job"]["job_id"], job_id)
+ self.assertEqual(response["job"]["state"], "launching")
+ self.assertIsNone(response["job"]["result"])
+
+ def test_init_set_plan_and_run_are_typed_and_machine_clean(self):
+ self.assertEqual(self._cli("list")[1]["recipes"], [])
+ self.assertFalse((profiles.profile_dir() / ".ops").exists())
+ code, initialized = self._cli("init")
+ self.assertEqual(code, 0)
+ self.assertEqual(initialized["created"], ["restart", "calibrate", "check"])
+ self.assertEqual(self._cli("init")[1]["created"], [])
+ self.assertEqual(len(self._cli("list")[1]["recipes"]), 3)
+ before, revision = recipes.load("local", "restart")
+ code, preview = self._cli("set", "restart", "startup_wait_s=45", "--plan")
+ self.assertEqual(code, 0)
+ self.assertTrue(preview["would_save"])
+ self.assertEqual(recipes.load("local", "restart"), (before, revision))
+ self.assertEqual(self._cli("set", "restart", "startup_wait_s=45")[0], 0)
+ self.assertFalse(self._cli("set", "restart", "startup_wait_s=45", "--plan")[1]["would_save"])
+ with mock.patch("strata_control.runtime.plan_restart", return_value={"ok": True,
+ "state": "ready", "would_drain": False}), \
+ mock.patch("strata_control.runtime.restart", return_value={"ok": True,
+ "state": "ready", "instance_id": "next"}) as restart:
+ code, planned = self._cli("plan", "restart")
+ self.assertEqual(code, 0)
+ self.assertFalse(planned["plan"]["would_execute"])
+ self.assertEqual(planned["plan"]["operation"]["startup_wait_s"], 45)
+ self.assertTrue(planned["plan"]["operation"]["run_effects"]["drain_current_instance"])
+ restart.assert_not_called()
+ code, ran = self._cli("run", "restart")
+ self.assertEqual(code, 0)
+ self.assertEqual(ran["operation"]["result"]["instance_id"], "next")
+ restart.assert_called_once_with("local", startup_wait=45)
+ self.assertEqual(self._cli("run", "check")[0], 0)
+ with mock.patch("strata_control.runtime.restart") as restart:
+ code, invalid = self._cli("run", "restart", "--exclusive")
+ self.assertEqual(code, 2)
+ self.assertFalse(invalid["ok"])
+ restart.assert_not_called()
+
+ def test_calibration_requires_fresh_exclusivity_and_uses_new_report_path(self):
+ recipes.initialize("local")
+ source = self.config.read_bytes()
+ report_dir = self.root / "reports"
+ self.assertEqual(self._cli("set", "calibrate", f"report_dir={report_dir}")[0], 0)
+ code, result = self._cli("plan", "calibrate")
+ self.assertEqual(code, 0)
+ self.assertFalse(result["plan"]["would_execute"])
+ self.assertTrue(result["plan"]["operation"]["run_effects"]["start_engine_for_decode_sweep"])
+ self.assertFalse(result["plan"]["operation"]["run_effects"]["change_run_config"])
+ self.assertFalse(report_dir.exists())
+ code, denied = self._cli("run", "calibrate")
+ self.assertEqual(code, 2)
+ self.assertFalse(denied["ok"])
+
+ def fake_runner(cfg, say):
+ return {"settings": {"--pcie-frac": "0.20"},
+ "report": {"default": {"pcie_frac": 0.55},
+ "confirm": {"default": [10.0, 10.2, 10.1],
+ "candidate": [12.0, 12.2, 12.1]},
+ "tok_s": 12.1, "seconds": 30}}
+
+ with mock.patch("tools.calibrate.run", side_effect=fake_runner), \
+ mock.patch("strata_control.calibration._hardware_key", return_value="fake-gpu"), \
+ mock.patch("strata_control.calibration._port_active", return_value=False):
+ first = self._cli("run", "calibrate", "--exclusive")
+ second = self._cli("run", "calibrate", "--exclusive")
+ self.assertEqual(first[0], 0)
+ self.assertEqual(second[0], 0)
+ first_path = Path(first[1]["operation"]["result"]["report_path"])
+ second_path = Path(second[1]["operation"]["result"]["report_path"])
+ self.assertNotEqual(first_path, second_path)
+ self.assertTrue(first_path.is_file())
+ self.assertTrue(second_path.is_file())
+ self.assertEqual(self.config.read_bytes(), source)
+ if os.name == "posix":
+ self.assertEqual(stat.S_IMODE(first_path.stat().st_mode), 0o600)
+
+ def test_component_recipe_can_enable_a_typed_live_card_check(self):
+ cfg = json.loads(self.config.read_text(encoding="utf-8"))
+ cfg["gpu"] = [0, 1, 2, 3]
+ cfg["backend"] = "cuda"
+ self.config.write_text(json.dumps(cfg), encoding="utf-8")
+ recipes.initialize("local")
+ code, proposed = self._cli("set", "check", "live=true", "--plan")
+ self.assertEqual(code, 0)
+ self.assertTrue(proposed["would_save"])
+ self.assertEqual(recipes.load("local", "check")[0]["params"], {})
+ self.assertEqual(self._cli("set", "check", "live=true")[0], 0)
+ cards = "\n".join(f"{i}, RTX 6000 test, GPU-test-{i}, 49140, 580.95" for i in range(4))
+ with mock.patch("strata_control.doctor.shutil.which", return_value="/fake/nvidia-smi"), \
+ mock.patch("strata_control.doctor.subprocess.run",
+ return_value=mock.Mock(returncode=0, stdout=cards)) as probe:
+ code, preview = self._cli("plan", "check")
+ self.assertEqual(code, 0)
+ self.assertTrue(preview["plan"]["operation"]["run_effects"]["query_host_gpus"])
+ self.assertEqual(preview["plan"]["operation"]["preflight"]["live_gpu_probe"]["status"], "ok")
+ code, executed = self._cli("run", "check", "--if-revision", preview["plan"]["recipe_revision"])
+ self.assertEqual(code, 0)
+ self.assertEqual(executed["operation"]["result"]["report"]["live_gpu_probe"]["status"], "ok")
+ self.assertEqual(probe.call_count, 2)
+ record = journal.load("local", executed["operation"]["operation_id"])
+ self.assertEqual(record["intent"], {"live": True})
+ with self.assertRaisesRegex(profiles.ProfileError, "parameter is not supported"):
+ recipes.propose_value("local", "check", "live=maybe")
+
+ def test_invalid_edit_keeps_draft_and_saved_recipe(self):
+ recipes.initialize("local")
+ before = recipes.load("local", "check")
+ editor = self.root / "bad_editor.py"
+ editor.write_text("import pathlib, sys\npathlib.Path(sys.argv[1]).write_text('{}')\n")
+ with mock.patch.dict(os.environ, {"VISUAL": f"{sys.executable} {editor}"}):
+ code, result = self._cli("edit", "check")
+ self.assertEqual(code, 2)
+ self.assertFalse(result["ok"])
+ self.assertEqual(recipes.load("local", "check"), before)
+ self.assertEqual(len(list((profiles.profile_dir() / ".ops" / "local").glob(".check-edit-*.json"))), 1)
+
+ def test_history_rollback_and_stale_edit(self):
+ recipes.initialize("local")
+ original, first = recipes.load("local", "restart")
+ proposed, revision = recipes.propose_value("local", "restart", "startup_wait_s=60")
+ recipes.save("local", "restart", proposed, revision)
+ with mock.patch("strata_control.runtime.restart") as restart:
+ code, stale = self._cli("run", "restart", "--if-revision", first)
+ self.assertEqual(code, 6)
+ self.assertFalse(stale["ok"])
+ restart.assert_not_called()
+ with self.assertRaisesRegex(profiles.ProfileError, "changed during edit"):
+ recipes.save("local", "restart", original, first)
+ entries = recipes.history("local", "restart")
+ self.assertEqual(entries[1]["revision"], first)
+ code, restored = self._cli("rollback", "restart", "--to", first)
+ self.assertEqual(code, 0)
+ self.assertEqual(restored["recipe"]["params"]["startup_wait_s"], 300)
+ self.assertEqual(recipes.load("local", "restart")[0], original)
+
+ def test_recipe_file_cannot_inject_shell_kind_or_symlink(self):
+ recipes.initialize("local")
+ path = profiles.profile_dir() / ".ops" / "local" / "restart.json"
+ original = path.read_bytes()
+ path.write_text(json.dumps({"schema_version": 1, "profile": "local", "id": "restart",
+ "kind": "shell.exec", "params": {"command": "rm -rf /"}}))
+ with self.assertRaisesRegex(profiles.ProfileError, "unsupported"):
+ recipes.load("local", "restart")
+ path.unlink()
+ outside = self.root / "outside.json"
+ outside.write_bytes(original)
+ path.symlink_to(outside)
+ with self.assertRaisesRegex(profiles.ProfileError, "regular file"):
+ recipes.load("local", "restart")
+
+ def test_init_rejects_conflicting_default_name_before_other_writes(self):
+ recipes.create("local", "check", "runtime.restart")
+ with self.assertRaisesRegex(profiles.ProfileError, "different kind"):
+ recipes.initialize("local")
+ self.assertEqual([item["id"] for item in recipes.list_recipes("local")], ["check"])
+
+ def test_operation_journal_records_compact_success_and_is_read_only_to_list(self):
+ recipes.initialize("local")
+ self.assertEqual(self._cli("runs")[1]["runs"], [])
+ self.assertFalse((profiles.profile_dir() / ".ops" / "local" / ".runs").exists())
+ code, executed = self._cli("run", "check")
+ self.assertEqual(code, 0)
+ operation_id = executed["operation"]["operation_id"]
+ code, listed = self._cli("runs")
+ self.assertEqual(code, 0)
+ self.assertEqual(listed["runs"][0]["operation_id"], operation_id)
+ code, shown = self._cli("result", operation_id)
+ self.assertEqual(code, 0)
+ record = shown["record"]
+ self.assertEqual(record["state"], "succeeded")
+ self.assertEqual(record["intent"], {})
+ self.assertEqual([event["state"] for event in record["events"]], ["running", "succeeded"])
+ self.assertEqual(set(record["result"]), {"ok", "issue_codes"})
+ path = profiles.profile_dir() / ".ops" / "local" / ".runs" / f"{operation_id}.json"
+ if os.name == "posix":
+ self.assertEqual(stat.S_IMODE(path.stat().st_mode), 0o600)
+
+ def test_failed_and_uncertain_runs_keep_distinct_journal_states_without_raw_result(self):
+ recipes.initialize("local")
+ with mock.patch("strata_control.runtime.restart", return_value={"ok": False,
+ "state": "ready", "error": "new_instance_failed", "exit_code": 6,
+ "private_trace": "TOPSECRET"}):
+ code, executed = self._cli("run", "restart")
+ self.assertEqual(code, 6)
+ failed = journal.load("local", executed["operation"]["operation_id"])
+ self.assertEqual(failed["state"], "failed")
+ self.assertNotIn("TOPSECRET", json.dumps(failed))
+ with mock.patch("strata_control.runtime.restart",
+ side_effect=profiles.ProfileError("runtime operation wait expired", 8)):
+ code, timed_out = self._cli("run", "restart")
+ self.assertEqual(code, 8)
+ self.assertFalse(timed_out["ok"])
+ newest = journal.list_runs("local")[0]
+ uncertain = journal.load("local", newest["operation_id"])
+ self.assertEqual(uncertain["state"], "completion_unknown")
+ self.assertEqual(uncertain["result"]["exit_code"], 8)
+ with mock.patch("strata_control.runtime.restart", side_effect=KeyboardInterrupt):
+ code, interrupted = self._cli("run", "restart")
+ self.assertEqual(code, 130)
+ self.assertFalse(interrupted["ok"])
+ newest = journal.list_runs("local")[0]
+ self.assertEqual(journal.load("local", newest["operation_id"])["state"], "completion_unknown")
+
+ def test_broken_machine_output_detaches_without_reporting_local_file_failure(self):
+ recipes.initialize("local")
+
+ class ClosedPipe(io.StringIO):
+ def write(self, text):
+ raise BrokenPipeError("consumer closed")
+
+ with redirect_stdout(ClosedPipe()):
+ self.assertEqual(main(["ops", "list", "--profile", "local", "--output", "json"]), 0)
+
+ def test_journal_prunes_old_terminal_records_but_not_running_work(self):
+ recipes.initialize("local")
+ with mock.patch.object(journal, "MAX_RECORDS", 2):
+ ids = []
+ for _ in range(3):
+ code, executed = self._cli("run", "check")
+ self.assertEqual(code, 0)
+ ids.append(executed["operation"]["operation_id"])
+ self.assertEqual(len(journal.list_runs("local")), 2)
+ with self.assertRaisesRegex(profiles.ProfileError, "not found"):
+ journal.load("local", ids[0])
+ # Two unfinished records exhaust the cap; neither may be discarded.
+ directory = profiles.profile_dir() / ".ops" / "local" / ".runs"
+ for path in directory.glob("*.json"):
+ path.unlink()
+ first = journal.begin("local", "check", "components.verify", "0" * 16, "0" * 16)
+ second = journal.begin("local", "check", "components.verify", "0" * 16, "0" * 16)
+ with self.assertRaisesRegex(profiles.ProfileError, "journal is full"):
+ journal.begin("local", "check", "components.verify", "0" * 16, "0" * 16)
+ self.assertEqual(journal.load("local", first["operation_id"])["state"], "running")
+ self.assertTrue(journal.load("local", first["operation_id"])["completion_unverified"])
+ self.assertEqual(journal.load("local", second["operation_id"])["state"], "running")
+
+ def test_invalid_journal_event_is_reported_without_rendering_record_content(self):
+ recipes.initialize("local")
+ operation_id = self._cli("run", "check")[1]["operation"]["operation_id"]
+ path = profiles.profile_dir() / ".ops" / "local" / ".runs" / f"{operation_id}.json"
+ record = json.loads(path.read_text())
+ record["events"][-1]["state"] = "\x1b[31mforged\x1b[0m"
+ path.write_text(json.dumps(record))
+ with self.assertRaisesRegex(profiles.ProfileError, "invalid events"):
+ journal.load("local", operation_id)
+ code, listed = self._cli("runs")
+ self.assertEqual(code, 0)
+ self.assertIn("error", listed["runs"][0])
+ self.assertNotIn("forged", json.dumps(listed))
+
+ def test_direct_journal_is_typed_compact_and_keeps_uncertain_interruptions(self):
+ revision = profiles.load("local")[1]
+ operation_id, result = journal.run_direct("local", "runtime.restart", revision,
+ {"wait_s": 20, "startup_wait_s": 10, "expected_profile_revision": revision},
+ lambda: {"ok": False, "state": "ready", "error": "activation_failed", "exit_code": 6,
+ "private_trace": "TOPSECRET"})
+ self.assertFalse(result["ok"])
+ record = journal.load("local", operation_id)
+ self.assertEqual(record["schema_version"], 2)
+ self.assertEqual(record["origin"], "direct")
+ self.assertEqual(record["state"], "failed")
+ self.assertNotIn("TOPSECRET", json.dumps(record))
+ deadline_id, _ = journal.run_direct("local", "runtime.stop", revision, {"wait_s": 12},
+ lambda: {"ok": False, "state": "stopping", "exit_code": 8})
+ self.assertEqual(journal.load("local", deadline_id)["state"], "completion_unknown")
+ with self.assertRaises(KeyboardInterrupt):
+ journal.run_direct("local", "runtime.stop", revision, {"wait_s": 12},
+ lambda: (_ for _ in ()).throw(KeyboardInterrupt()))
+ latest = journal.list_runs("local")[0]
+ uncertain = journal.load("local", latest["operation_id"])
+ self.assertEqual(uncertain["state"], "completion_unknown")
+ with self.assertRaisesRegex(profiles.ProfileError, "unsupported fields"):
+ journal.begin_direct("local", "runtime.stop", revision,
+ {"wait_s": 12, "shell": "rm -rf /"})
+ self.assertEqual(len(journal.list_runs("local")), 3)
+
+ def test_direct_journal_rejects_tampered_origin(self):
+ revision = profiles.load("local")[1]
+ record = journal.begin_direct("local", "runtime.stop", revision, {"wait_s": 12})
+ path = profiles.profile_dir() / ".ops" / "local" / ".runs" / f"{record['operation_id']}.json"
+ forged = json.loads(path.read_text())
+ forged["origin"] = "remote"
+ path.write_text(json.dumps(forged))
+ with self.assertRaisesRegex(profiles.ProfileError, "unsupported intent"):
+ journal.load("local", record["operation_id"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/terminal/test_runtime.py b/tests/terminal/test_runtime.py
new file mode 100644
index 000000000..7c00aa659
--- /dev/null
+++ b/tests/terminal/test_runtime.py
@@ -0,0 +1,1024 @@
+"""Managed local instance lifecycle with an owned fake engine process."""
+
+import io
+import hashlib
+import json
+import os
+import queue
+import signal
+import socket
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+import unittest
+import urllib.request
+from contextlib import redirect_stdout
+from pathlib import Path
+from unittest import mock
+
+from strata_cli.cli import main
+from strata_cli import bench
+from strata_cli.client import Endpoint
+from strata_control import calibration, journal, management, profiles, recipes, runtime
+
+
[email protected](os.name == "posix", "owner-only Unix socket transport is POSIX-only")
+class RuntimeTests(unittest.TestCase):
+ def setUp(self):
+ self.temp = tempfile.TemporaryDirectory(prefix="strata-runtime-test-")
+ self.addCleanup(self.temp.cleanup)
+ self.root = Path(self.temp.name)
+ env = mock.patch.dict(os.environ, {"STRATA_PROFILE_DIR": str(self.root / "profiles"),
+ "STRATA_RUNTIME_DIR": str(self.root / "runtime")})
+ env.start()
+ self.addCleanup(env.stop)
+ previous_key = os.environ.pop("STRATA_API_KEY", None)
+ self.addCleanup(lambda: os.environ.__setitem__("STRATA_API_KEY", previous_key)
+ if previous_key is not None else os.environ.pop("STRATA_API_KEY", None))
+ engine = self.root / "engine.py"
+ engine.write_text("#!" + sys.executable + "\nimport sys\nfrom pathlib import Path\n"
+ "if '--batch' in sys.argv: print('INFO batch_slots=2', flush=True)\n"
+ "print('READY 4096 stop', flush=True)\n"
+ "for line in sys.stdin:\n"
+ " if line.strip() == 'QUIT': break\n"
+ " if line.startswith(('GEN ', 'BGEN ')):\n"
+ " slot = int(line.split()[1]) if line.startswith('BGEN ') else None\n"
+ " if Path('fail-generation').exists():\n"
+ " print('ERR generation-failed', flush=True)\n"
+ " continue\n"
+ " if Path('empty-generation').exists():\n"
+ " print('DONE 0 1 1.0 0.0 stop 0 0 0', flush=True)\n"
+ " if slot is not None: print(f'BADM {slot} 0', flush=True)\n"
+ " continue\n"
+ " print('T 97', flush=True)\n"
+ " print('DONE 1 1 1.0 1.0 length 0 0 0', flush=True)\n"
+ " if slot is not None: print(f'BADM {slot} 0', flush=True)\n", encoding="utf-8")
+ engine.chmod(0o700)
+ from tools.strata_tokenizer import BYTE_TO_UNICODE
+ tokenizer = self.root / "tokenizer"
+ tokenizer.mkdir()
+ tokens = [BYTE_TO_UNICODE[i] for i in range(256)] + [
+ "ab", "<|im_start|>", "<|im_end|>", "<|endoftext|>"]
+ (tokenizer / "vocab.json").write_text(json.dumps({token: i for i, token in enumerate(tokens)}))
+ (tokenizer / "merges.txt").write_text("a b")
+ (tokenizer / "token_type.json").write_text(json.dumps([0] * 257 + [3, 3, 3]))
+ self.config = self.root / "run.json"
+ self.config.write_text(json.dumps({"exe": str(engine), "tokenizer": str(tokenizer),
+ "args": [], "cwd": str(self.root), "model_name": "fake",
+ "host": "127.0.0.1", "port": 0}), encoding="utf-8")
+ profiles.create("local", str(self.config))
+ self.addCleanup(self._stop)
+
+ def _stop(self):
+ try:
+ if runtime._read_state("local") is not None:
+ runtime.stop("local", timeout=12)
+ except (OSError, profiles.ProfileError):
+ pass
+
+ def _cli(self, *args):
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(["runtime", *args, "--output", "json"])
+ return code, json.loads(output.getvalue())
+
+ def test_component_inspection_bridge_is_read_only_and_reports_missing_files(self):
+ command = [sys.executable, "-m", "strata_control.management"]
+ root = Path(__file__).resolve().parents[2]
+
+ def send(live):
+ request = {"schema_version": 1, "action": "components.inspect",
+ "profile": "local", "params": {"live": live}}
+ completed = subprocess.run(command, input=json.dumps(request), text=True,
+ capture_output=True, cwd=root, env=os.environ.copy(), timeout=15)
+ return completed.returncode, json.loads(completed.stdout)
+
+ code, result = send(False)
+ self.assertEqual(code, 0)
+ self.assertTrue(result["ok"])
+ self.assertTrue(result["report"]["ok"])
+ self.assertEqual(result["report"]["profile"], "local")
+ self.assertEqual(Path(result["report"]["source_config"]), self.config.resolve())
+ self.assertIsNone(result["report"]["live_gpu_probe"])
+ self.assertEqual(journal.list_runs("local"), [])
+ self.assertEqual(runtime.status("local")["state"], "stopped")
+
+ code, invalid = send("true")
+ self.assertEqual((code, invalid["ok"]), (2, False))
+ self.assertIn("live must be true or false", invalid["error"])
+ engine = self.root / "engine.py"
+ engine.unlink()
+ code, missing = send(False)
+ self.assertEqual((code, missing["ok"], missing["report"]["ok"]), (0, True, False))
+ self.assertIn("engine", [row["name"] for row in missing["report"]["components"]
+ if row["status"] == "missing"])
+ self.assertEqual(journal.list_runs("local"), [])
+
+ def test_profile_change_bridge_reviews_revision_source_and_typed_overrides(self):
+ command = [sys.executable, "-m", "strata_control.management"]
+ root = Path(__file__).resolve().parents[2]
+
+ def send(action, params):
+ request = {"schema_version": 1, "action": action, "profile": "local", "params": params}
+ completed = subprocess.run(command, input=json.dumps(request), text=True,
+ capture_output=True, cwd=root, env=os.environ.copy(), timeout=15)
+ return completed.returncode, json.loads(completed.stdout)
+
+ other = self.root / "strata-other.json"
+ other.write_text(self.config.read_text().replace('"fake"', '"other"'), encoding="utf-8")
+ with mock.patch.dict(os.environ, {"STRATA_INSTALL_DIR": str(self.root)}):
+ code, listed = send("models.installed", {})
+ inspect_code, inspected = send("models.inspect", {"model_id": "other"})
+ self.assertEqual(code, 0)
+ self.assertIn("other", [item["id"] for item in listed["inventory"]["models"]])
+ self.assertEqual((inspect_code, inspected["ok"]), (0, True))
+ self.assertEqual(inspected["inspection"]["model"]["id"], "other")
+ self.assertEqual(journal.list_runs("local"), [])
+ candidate = self.root / "candidate.gguf"
+ candidate.write_bytes(b"GGUF" + (3).to_bytes(4, "little"))
+ code, import_plan = send("models.import.plan", {"path": str(candidate)})
+ self.assertEqual((code, import_plan["ok"]), (0, True))
+ self.assertFalse(import_plan["plan"]["would_write"])
+ self.assertEqual(import_plan["plan"]["execution_compatibility"], "unverified")
+ code, invalid_import = send("models.import.plan", {"path": "relative.gguf"})
+ self.assertEqual((code, invalid_import["ok"]), (2, False))
+ code, current = send("profile.inspect", {})
+ self.assertEqual((code, current["ok"], current["profile"]["id"]), (0, True, "local"))
+ self.assertEqual(current["profile"]["overrides"], {})
+ edits = {"overrides": {"parallel": 4, "batch_groups": "auto", "max_queue": 8,
+ "queue_timeout": 2.5}, "source_config": str(other)}
+ code, plan = send("profile.change.plan", {**edits, "if_revision": current["revision"]})
+ self.assertEqual((code, plan["ok"], plan["plan"]["would_save"]), (0, True, True))
+ self.assertEqual(plan["plan"]["revision"], current["revision"])
+ self.assertEqual(plan["plan"]["effective"]["parallel"], 4)
+ self.assertEqual(plan["plan"]["source_config_after"], str(other.resolve()))
+ self.assertEqual(profiles.load("local")[0]["source_config"], str(self.config.resolve()))
+ self.assertEqual(journal.list_runs("local"), [])
+
+ execute = {**edits, "if_revision": plan["plan"]["revision"],
+ "if_source_sha256": plan["plan"]["source_sha256"]}
+ profiles.set_values("local", ["max_queue=1"])
+ code, stale = send("profile.change", execute)
+ self.assertEqual((code, stale["ok"]), (6, False))
+ self.assertIn("changed after review", stale["error"])
+ code, stale_plan = send("profile.change.plan", {**edits, "if_revision": current["revision"]})
+ self.assertEqual((code, stale_plan["ok"]), (6, False))
+ code, plan = send("profile.change.plan", {**edits,
+ "if_revision": profiles.load("local")[1]})
+ execute.update(if_revision=plan["plan"]["revision"],
+ if_source_sha256=plan["plan"]["source_sha256"])
+ other.write_text(other.read_text() + "\n", encoding="utf-8")
+ code, changed_source = send("profile.change", execute)
+ self.assertEqual((code, changed_source["ok"]), (6, False))
+ code, plan = send("profile.change.plan", {**edits,
+ "if_revision": profiles.load("local")[1]})
+ execute.update(if_revision=plan["plan"]["revision"],
+ if_source_sha256=plan["plan"]["source_sha256"])
+ code, saved = send("profile.change", execute)
+ self.assertEqual((code, saved["ok"], saved["saved"]), (0, True, True))
+ self.assertEqual(profiles.load("local")[0]["source_config"], str(other.resolve()))
+ self.assertEqual(profiles.load("local")[0]["overrides"], edits["overrides"])
+ self.assertEqual(runtime.status("local")["state"], "stopped")
+ self.assertEqual(journal.list_runs("local"), [])
+
+ code, invalid = send("profile.change.plan", {"overrides": {"parallel": True},
+ "source_config": str(other), "if_revision": profiles.load("local")[1]})
+ self.assertEqual((code, invalid["ok"]), (2, False))
+
+ started = runtime.start("local", wait=12)
+ self.assertTrue(started["ok"], started)
+ running = runtime.status("local")
+ self.assertEqual(running["state"], "ready")
+ running_revision = running["profile_revision"]
+ next_edit = {"overrides": {**edits["overrides"], "parallel": 6},
+ "source_config": str(other.resolve())}
+ code, next_plan = send("profile.change.plan", {**next_edit,
+ "if_revision": profiles.load("local")[1]})
+ self.assertEqual((code, next_plan["ok"]), (0, True))
+ code, next_saved = send("profile.change", {**next_edit,
+ "if_revision": next_plan["plan"]["revision"],
+ "if_source_sha256": next_plan["plan"]["source_sha256"]})
+ self.assertEqual((code, next_saved["ok"]), (0, True))
+ still_running = runtime.status("local")
+ self.assertEqual(still_running["instance_id"], running["instance_id"])
+ self.assertEqual(still_running["profile_revision"], running_revision)
+ restart_plan = runtime.plan_restart("local")
+ self.assertTrue(restart_plan["ok"], restart_plan)
+ self.assertEqual(restart_plan["candidate_profile_revision"], next_saved["revision"])
+ self.assertNotEqual(restart_plan["candidate_profile_revision"], running_revision)
+
+ def test_local_management_bridge_and_cli_share_owner_and_journal(self):
+ command = [sys.executable, "-m", "strata_control.management"]
+ root = Path(__file__).resolve().parents[2]
+
+ def send(action, params):
+ request = {"schema_version": 1, "action": action, "profile": "local", "params": params}
+ completed = subprocess.run(command, input=json.dumps(request), text=True,
+ capture_output=True, cwd=root, env=os.environ.copy(), timeout=20)
+ return completed.returncode, json.loads(completed.stdout)
+
+ code, invalid = send("runtime.start", {"wait_s": True, "shutdown_timeout_s": 2,
+ "if_profile_revision": None,
+ "if_source_sha256": None})
+ self.assertEqual((code, invalid["ok"]), (2, False))
+ self.assertEqual(runtime.status("local")["state"], "stopped")
+ self.assertEqual(journal.list_runs("local"), [])
+ code, preview = send("runtime.start.plan", {"shutdown_timeout_s": 2})
+ self.assertEqual(code, 0)
+ self.assertFalse(preview["plan"]["would_start"])
+ self.assertEqual(runtime.status("local")["state"], "stopped")
+ start_params = {"wait_s": 10, "shutdown_timeout_s": 2,
+ "if_profile_revision": preview["plan"]["launch"]["profile_revision"],
+ "if_source_sha256": preview["plan"]["source_sha256"]}
+ self.assertEqual(preview["plan"]["source_sha256"], hashlib.sha256(self.config.read_bytes()).hexdigest())
+ code, missing = send("runtime.start", {**start_params, "if_source_sha256": None})
+ self.assertEqual((code, missing["ok"]), (2, False))
+ self.config.write_bytes(self.config.read_bytes() + b" ")
+ code, stale_source = send("runtime.start", start_params)
+ self.assertEqual((code, stale_source["error"]), (6, "source_changed_after_start_plan"))
+ self.assertEqual(journal.list_runs("local"), [])
+ self.config.write_bytes(self.config.read_bytes()[:-1])
+ profiles.set_values("local", ["max_queue=32"])
+ code, stale_profile = send("runtime.start", start_params)
+ self.assertEqual((code, stale_profile["error"]), (6, "profile_changed_after_start_plan"))
+ self.assertEqual(journal.list_runs("local"), [])
+ code, preview = send("runtime.start.plan", {"shutdown_timeout_s": 2})
+ self.assertEqual(code, 0)
+ start_params.update(if_profile_revision=preview["plan"]["launch"]["profile_revision"],
+ if_source_sha256=preview["plan"]["source_sha256"])
+
+ code, started = send("runtime.start", start_params)
+ self.assertEqual(code, 0, started)
+ self.assertTrue(started["ok"])
+ start_record = journal.load("local", started["operation_id"])
+ self.assertEqual(start_record["kind"], "runtime.start")
+ self.assertEqual(start_record["intent"]["expected_source_sha256"], start_params["if_source_sha256"])
+ cli_code, current = self._cli("status", "--profile", "local")
+ self.assertEqual((cli_code, current["instance_id"]), (0, started["instance_id"]))
+ code, verify_plan = send("runtime.verify.plan", {"load": False})
+ self.assertEqual((code, verify_plan["ok"]), (0, True))
+ self.assertEqual(verify_plan["plan"]["owner_id"], started["owner_id"])
+ self.assertEqual(verify_plan["plan"]["instance_id"], started["instance_id"])
+ self.assertFalse(verify_plan["plan"]["would_verify"])
+ verify_params = {"wait_s": 10, "load": False,
+ "if_owner_id": verify_plan["plan"]["owner_id"],
+ "if_instance_id": verify_plan["plan"]["instance_id"]}
+ count = len(journal.list_runs("local"))
+ code, missing_verify = send("runtime.verify", {**verify_params, "if_owner_id": None})
+ self.assertEqual((code, missing_verify["ok"]), (2, False))
+ code, stale_verify_owner = send("runtime.verify", {**verify_params,
+ "if_owner_id": "0" * 32})
+ self.assertEqual((code, stale_verify_owner["error"]),
+ (6, "owner_changed_after_verify_plan"))
+ code, stale_verify_instance = send("runtime.verify", {**verify_params,
+ "if_instance_id": "0" * 32})
+ self.assertEqual((code, stale_verify_instance["error"]),
+ (6, "instance_changed_after_verify_plan"))
+ self.assertEqual(len(journal.list_runs("local")), count)
+ host_denied = runtime._rpc("local", "verify", params={
+ "wait": 10, "load": False, "expected_owner_id": "0" * 32,
+ "expected_instance_id": started["instance_id"]})
+ self.assertEqual(host_denied["error"], "owner_changed_after_verify_plan")
+ host_denied = runtime._rpc("local", "verify", params={
+ "wait": 10, "load": False, "expected_owner_id": started["owner_id"],
+ "expected_instance_id": "0" * 32})
+ self.assertEqual(host_denied["error"], "instance_changed_after_verify_plan")
+ code, verified = send("runtime.verify", verify_params)
+ self.assertEqual((code, verified["ok"], verified["verified_now"]), (0, True, True))
+ self.assertEqual(verified["instance_id"], started["instance_id"])
+ verify_record = journal.load("local", verified["operation_id"])
+ self.assertEqual(verify_record["intent"]["expected_instance_id"], started["instance_id"])
+ cli_code, cli_verify_plan = self._cli("verify", "--profile", "local", "--plan")
+ self.assertEqual((cli_code, cli_verify_plan["plan"]["instance_id"]),
+ (0, started["instance_id"]))
+ code, old_stop_plan = send("runtime.stop.plan", {})
+ self.assertEqual((code, old_stop_plan["ok"]), (0, True))
+ self.assertEqual(old_stop_plan["plan"]["instance_id"], started["instance_id"])
+ code, restart_plan = send("runtime.restart.plan", {"allow_source_switch": False,
+ "allow_source_migration": False})
+ self.assertEqual((code, restart_plan["ok"]), (0, True))
+ self.assertEqual(restart_plan["current_owner_id"], started["owner_id"])
+ self.assertEqual(restart_plan["current_instance_id"], started["instance_id"])
+ restart_params = {"wait_s": 20, "startup_wait_s": 10,
+ "if_profile_revision": restart_plan["candidate_profile_revision"],
+ "if_owner_id": restart_plan["current_owner_id"],
+ "if_instance_id": restart_plan["current_instance_id"],
+ "if_source_sha256": restart_plan["candidate_source_sha256"],
+ "allow_source_switch": False, "allow_source_migration": False}
+ code, missing_condition = send("runtime.restart", {**restart_params,
+ "if_source_sha256": None})
+ self.assertEqual((code, missing_condition["ok"]), (2, False))
+ code, missing_owner = send("runtime.restart", {**restart_params,
+ "if_owner_id": None})
+ self.assertEqual((code, missing_owner["ok"]), (2, False))
+ count = len(journal.list_runs("local"))
+ code, stale_owner = send("runtime.restart", {**restart_params,
+ "if_owner_id": "0" * 32})
+ self.assertEqual((code, stale_owner["error"]), (6, "owner_changed_after_restart_plan"))
+ code, stale_instance = send("runtime.restart", {**restart_params,
+ "if_instance_id": "0" * 32})
+ self.assertEqual((code, stale_instance["error"]), (6, "instance_changed_after_restart_plan"))
+ self.assertEqual(len(journal.list_runs("local")), count)
+ host_denied = runtime._rpc("local", "restart", params={
+ "expected_owner_id": "0" * 32, "expected_instance_id": started["instance_id"]})
+ self.assertEqual(host_denied["error"], "owner_changed_after_restart_plan")
+ host_denied = runtime._rpc("local", "restart", params={
+ "expected_owner_id": started["owner_id"], "expected_instance_id": "0" * 32})
+ self.assertEqual(host_denied["error"], "instance_changed_after_restart_plan")
+ self.assertEqual(runtime.status("local")["instance_id"], started["instance_id"])
+ code, restarted = send("runtime.restart", restart_params)
+ self.assertEqual((code, restarted["ok"]), (0, True), restarted)
+ self.assertNotEqual(restarted["instance_id"], started["instance_id"])
+ self.assertEqual(journal.load("local", restarted["operation_id"])["kind"], "runtime.restart")
+ count = len(journal.list_runs("local"))
+ code, stale_verify = send("runtime.verify", verify_params)
+ self.assertEqual((code, stale_verify["error"]), (6, "instance_changed_after_verify_plan"))
+ self.assertEqual(len(journal.list_runs("local")), count)
+ code, stale_review = send("runtime.restart", restart_params)
+ self.assertEqual((code, stale_review["error"]), (6, "instance_changed_after_restart_plan"))
+ self.assertEqual(len(journal.list_runs("local")), count)
+ self.assertEqual(runtime.status("local")["instance_id"], restarted["instance_id"])
+ old_stop_params = {"wait_s": 12, "if_owner_id": old_stop_plan["plan"]["owner_id"],
+ "if_instance_id": old_stop_plan["plan"]["instance_id"]}
+ count = len(journal.list_runs("local"))
+ code, stale_stop = send("runtime.stop", old_stop_params)
+ self.assertEqual((code, stale_stop["error"]), (6, "instance_changed_after_stop_plan"))
+ self.assertEqual(len(journal.list_runs("local")), count)
+ self.assertEqual(runtime.status("local")["instance_id"], restarted["instance_id"])
+ code, stop_plan = send("runtime.stop.plan", {})
+ self.assertEqual((code, stop_plan["ok"]), (0, True))
+ stop_params = {"wait_s": 12, "if_owner_id": stop_plan["plan"]["owner_id"],
+ "if_instance_id": stop_plan["plan"]["instance_id"]}
+ code, stale_owner = send("runtime.stop", {**stop_params, "if_owner_id": "0" * 32})
+ self.assertEqual((code, stale_owner["error"]), (6, "owner_changed_after_stop_plan"))
+ self.assertEqual(len(journal.list_runs("local")), count)
+ host_denied = runtime._rpc("local", "stop", params={"expected_owner_id": "0" * 32,
+ "expected_instance_id": restarted["instance_id"]})
+ self.assertEqual(host_denied["error"], "owner_changed_after_stop_plan")
+ host_denied = runtime._rpc("local", "stop", params={"expected_owner_id": stop_params["if_owner_id"],
+ "expected_instance_id": started["instance_id"]})
+ self.assertEqual(host_denied["error"], "instance_changed_after_stop_plan")
+ self.assertEqual(runtime.status("local")["instance_id"], restarted["instance_id"])
+ code, stopped = send("runtime.stop", stop_params)
+ self.assertEqual((code, stopped["state"]), (0, "stopped"))
+ self.assertEqual(journal.load("local", stopped["operation_id"])["kind"], "runtime.stop")
+ self.assertEqual(runtime.status("local")["state"], "stopped")
+
+ def test_local_management_bridge_rejects_ambiguous_requests(self):
+ command = [sys.executable, "-m", "strata_control.management"]
+ root = Path(__file__).resolve().parents[2]
+ invalid = (
+ '{"schema_version":1,"action":"runtime.status","action":"runtime.start",'
+ '"profile":"local","params":{}}',
+ '{"schema_version":1,"action":"runtime.start","profile":"local",'
+ '"params":{"wait_s":NaN,"shutdown_timeout_s":2}}',
+ '{"schema_version":1,"action":"runtime.start","profile":"local",'
+ '"params":{"wait_s":10,"shutdown_timeout_s":2,"command":"rm -rf /"}}',
+ '{"schema_version":2,"action":"runtime.status","profile":"local","params":{}}',
+ )
+ for payload in invalid:
+ with self.subTest(payload=payload[:50]):
+ completed = subprocess.run(command, input=payload, text=True, capture_output=True,
+ cwd=root, env=os.environ.copy(), timeout=10)
+ response = json.loads(completed.stdout)
+ self.assertEqual((completed.returncode, response["ok"]), (2, False))
+ self.assertEqual(runtime.status("local")["state"], "stopped")
+ self.assertEqual(journal.list_runs("local"), [])
+
+ def test_owner_host_refuses_source_changed_after_start_review(self):
+ preview = management.runtime_action("start", "local", plan=True)["plan"]
+ self.config.write_bytes(self.config.read_bytes() + b" ")
+ host = subprocess.Popen([sys.executable, "-m", "strata_control.runtime", "--host", "local",
+ "--shutdown-timeout", "2", "--startup-wait", "10",
+ "--expected-profile-revision", preview["launch"]["profile_revision"],
+ "--expected-source-sha256", preview["source_sha256"]],
+ cwd=Path(__file__).resolve().parents[2], env=os.environ.copy(),
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL)
+ try:
+ deadline = time.monotonic() + 8
+ result = {"state": "stopped"}
+ while time.monotonic() < deadline:
+ result = runtime.status("local")
+ if result.get("state") == "failed":
+ break
+ self.assertIsNone(host.poll(), "owner host exited before reporting status")
+ time.sleep(0.05)
+ self.assertEqual(result.get("error"), "source_changed_after_start_plan")
+ self.assertIsNone(result.get("child_pid"))
+ self.assertEqual(list((self.root / "runtime").glob("*.ready.json")), [])
+ finally:
+ if host.poll() is None:
+ try:
+ runtime.stop("local", timeout=8)
+ finally:
+ host.wait(timeout=10)
+
+ def test_foreground_jsonl_emits_ready_and_stop_without_human_stdout(self):
+ for stop_signal, expected_code, expected_reason, quiet in (
+ (signal.SIGTERM, 0, "sigterm", False),
+ (signal.SIGINT, 130, "sigint", False),
+ (signal.SIGTERM, 0, "sigterm", True)):
+ with self.subTest(signal=expected_reason, quiet=quiet):
+ rows = queue.Queue()
+ stderr_path = self.root / f"serve-{expected_reason}-{'quiet' if quiet else 'normal'}.stderr"
+ with stderr_path.open("w+", encoding="utf-8") as diagnostics:
+ process = subprocess.Popen(
+ [sys.executable, "strata.py", "serve", "--profile", "local", "--port", "0",
+ "--shutdown-timeout", "2", "--output", "jsonl", *(["--quiet"] if quiet else [])],
+ cwd=Path(__file__).resolve().parents[2], env=os.environ.copy(),
+ stdout=subprocess.PIPE, stderr=diagnostics, text=True, bufsize=1)
+ reader = threading.Thread(target=lambda: [rows.put(line) for line in process.stdout],
+ daemon=True)
+ reader.start()
+ try:
+ collected = []
+ for _ in range(4):
+ collected.append(json.loads(rows.get(timeout=15)))
+ if collected[-1].get("event") == "ready":
+ break
+ self.assertEqual([row["event"] for row in collected], ["starting", "ready"])
+ ready = collected[-1]
+ self.assertGreater(ready["bound_port"], 0)
+ self.assertEqual(ready["model_state"], "ready")
+ self.assertEqual(ready["pid"], process.pid)
+ request = urllib.request.Request(
+ ready["api_url"] + "/v1/chat/completions", method="POST",
+ data=json.dumps({"messages": [{"role": "user", "content": "Hi"}],
+ "max_tokens": 1}).encode(),
+ headers={"Content-Type": "application/json"})
+ with urllib.request.urlopen(request, timeout=5) as response:
+ self.assertEqual(response.status, 200)
+ self.assertIn("choices", json.load(response))
+ process.send_signal(stop_signal)
+ self.assertEqual(process.wait(timeout=15), expected_code)
+ reader.join(timeout=3)
+ self.assertFalse(reader.is_alive())
+ while not rows.empty():
+ collected.append(json.loads(rows.get_nowait()))
+ self.assertEqual([row["event"] for row in collected],
+ ["starting", "ready", "stopping", "draining", "stopped"])
+ self.assertEqual(collected[-1]["reason"], expected_reason)
+ self.assertEqual(collected[-1]["exit_code"], expected_code)
+ self.assertTrue(all(row["schema_version"] == 1 for row in collected))
+ self.assertNotIn("api_key", json.dumps(collected).lower())
+ diagnostics.flush()
+ if quiet:
+ self.assertNotIn("ready:", stderr_path.read_text(encoding="utf-8"))
+ else:
+ self.assertIn("ready:", stderr_path.read_text(encoding="utf-8"))
+ finally:
+ if process.poll() is None:
+ process.kill()
+ process.wait(timeout=5)
+ reader.join(timeout=2)
+ process.stdout.close()
+
+ def test_start_profile_revision_restart_and_stop(self):
+ code, started = self._cli("start", "--profile", "local", "--wait", "10",
+ "--shutdown-timeout", "2")
+ self.assertEqual(code, 0)
+ self.assertEqual(started["state"], "ready")
+ self.assertTrue(started["api_identity_verified"])
+ self.assertTrue(started["launch_attested"])
+ self.assertTrue(started["generation_ready"])
+ self.assertEqual(started["readiness_state"], "generation_ready")
+ started_record = journal.load("local", started["operation_id"])
+ self.assertEqual((started_record["schema_version"], started_record["kind"], started_record["state"]),
+ (2, "runtime.start", "succeeded"))
+ self.assertTrue(started_record["result"]["launch_attested"])
+ first_id = started["instance_id"]
+ self.assertNotEqual(started["host_pid"], started["child_pid"])
+ status = self._cli("status", "--profile", "local")[1]
+ self.assertEqual(status["instance_id"], first_id)
+ self.assertNotIn("operation_id", status)
+ code, checked = self._cli("verify", "--profile", "local", "--wait", "10")
+ self.assertEqual(code, 0)
+ self.assertTrue(checked["verified_now"])
+ self.assertTrue(checked["launch_attested"])
+ self.assertTrue(checked["generation_ready"])
+ checked_record = journal.load("local", checked["operation_id"])
+ self.assertEqual(checked_record["kind"], "runtime.verify")
+ self.assertTrue(checked_record["result"]["launch_attested"])
+ profiles.set_values("local", ["parallel=2"])
+ code, restarted = self._cli("restart", "--profile", "local", "--wait", "20")
+ self.assertEqual(code, 0)
+ self.assertTrue(restarted["restarted"])
+ self.assertTrue(restarted["launch_attested"])
+ self.assertTrue(restarted["generation_ready"])
+ self.assertEqual(journal.load("local", restarted["operation_id"])["kind"], "runtime.restart")
+ self.assertEqual(restarted["previous_instance_id"], first_id)
+ self.assertNotEqual(restarted["instance_id"], first_id)
+ code, stopped = self._cli("stop", "--profile", "local", "--wait", "12")
+ self.assertEqual(code, 0)
+ self.assertEqual(stopped["state"], "stopped")
+ self.assertEqual(journal.load("local", stopped["operation_id"])["kind"], "runtime.stop")
+ self.assertEqual([row["origin"] for row in journal.list_runs("local")], ["direct"] * 4)
+ deadline = time.monotonic() + 3
+ while runtime._read_state("local") is not None and time.monotonic() < deadline:
+ time.sleep(0.05)
+ self.assertIsNone(runtime._read_state("local"))
+
+ def test_cli_stop_plan_pins_the_reviewed_owner_and_instance(self):
+ started = runtime.start("local", wait=10, shutdown_timeout=2)
+ self.assertTrue(started["ok"])
+ code, preview = self._cli("stop", "--profile", "local", "--plan")
+ self.assertEqual(code, 0, preview)
+ self.assertEqual(preview["plan"]["instance_id"], started["instance_id"])
+ self.assertFalse(preview["plan"]["would_stop"])
+ code, denied = self._cli("stop", "--profile", "local", "--wait", "12",
+ "--if-owner-id", "0" * 32,
+ "--if-instance-id", preview["plan"]["instance_id"])
+ self.assertEqual((code, denied["error"]["message"]), (6, "owner_changed_after_stop_plan"))
+ self.assertEqual(runtime.status("local")["instance_id"], started["instance_id"])
+ code, stopped = self._cli("stop", "--profile", "local", "--wait", "12",
+ "--if-owner-id", preview["plan"]["owner_id"],
+ "--if-instance-id", preview["plan"]["instance_id"])
+ self.assertEqual((code, stopped["state"]), (0, "stopped"))
+ record = journal.load("local", stopped["operation_id"])
+ self.assertEqual(record["intent"]["expected_owner_id"], preview["plan"]["owner_id"])
+
+ def test_managed_benchmark_binds_to_owned_launch(self):
+ with socket.socket() as reserved:
+ reserved.bind(("127.0.0.1", 0))
+ port = reserved.getsockname()[1]
+ cfg = json.loads(self.config.read_text(encoding="utf-8"))
+ cfg["port"] = port
+ self.config.write_text(json.dumps(cfg), encoding="utf-8")
+ started = runtime.start("local", wait=10, shutdown_timeout=2)
+ self.assertTrue(started["ok"])
+ identity = {"profile": "local", "revision": profiles.load("local")[1],
+ "source_sha256": hashlib.sha256(self.config.read_bytes()).hexdigest()}
+ endpoint = Endpoint(started["api_url"])
+ output = self.root / "managed-bench"
+ with redirect_stdout(io.StringIO()):
+ result = bench.run(endpoint, endpoint, output, concurrency=1,
+ profile_identity=identity, require_managed_match=True)
+ self.assertTrue(result["successful"])
+ self.assertEqual(result["profile_running_match"], "managed_launch_checked")
+ self.assertEqual(result["instance_id"], started["instance_id"])
+ self.assertTrue(result["profile_running_check"]["after"]["matched"])
+ output_json = io.StringIO()
+ with redirect_stdout(output_json):
+ code = main(["bench", "run", "--profile", "local", "--require-managed-match",
+ "--concurrency", "1", "--out", str(self.root / "cli-managed"),
+ "--output", "json"])
+ self.assertEqual(code, 0)
+ self.assertEqual(json.loads(output_json.getvalue())["summary"]["successful"], True)
+ self.assertEqual(json.loads(output_json.getvalue())["summary"]["profile_running_match"],
+ "managed_launch_checked")
+ self.assertEqual(bench.load(self.root / "cli-managed")["profile_running_match"],
+ "managed_launch_checked")
+ comparison = bench.compare(result, bench.load(self.root / "cli-managed"))
+ self.assertEqual(comparison["baseline"]["profile_running_match"], "managed_launch_checked")
+ self.assertFalse(any("running server config" in warning for warning in comparison["warnings"]))
+
+ def test_owned_runtime_and_calibration_exclude_each_other_even_on_port_zero(self):
+ first = runtime.start("local", wait=10, shutdown_timeout=2)
+ self.assertTrue(first["ok"])
+ output = self.root / "blocked-calibration.json"
+ with self.assertRaisesRegex(profiles.ProfileError, "engine lease"):
+ calibration.measure("local", output, exclusive_ack=True,
+ runner=lambda cfg, say: self.fail("calibration runner was started"))
+ self.assertFalse(output.exists())
+ self.assertTrue(runtime.stop("local", timeout=12)["ok"])
+ with calibration._managed_exclusive():
+ with self.assertRaisesRegex(profiles.ProfileError, "runtime host failed to start"):
+ runtime.start("local", wait=1, shutdown_timeout=2)
+ self.assertTrue(runtime.start("local", wait=10, shutdown_timeout=2)["ok"])
+
+ def test_failed_new_port_rolls_back_previous_owned_launch(self):
+ first = runtime.start("local", wait=10, shutdown_timeout=2)
+ self.assertTrue(first["ok"])
+ with socket.socket() as occupied:
+ occupied.bind(("127.0.0.1", 0))
+ occupied.listen(1)
+ profiles.set_values("local", [f"port={occupied.getsockname()[1]}"])
+ result = runtime.restart("local", timeout=20)
+ self.assertFalse(result["ok"])
+ self.assertTrue(result["rolled_back"])
+ self.assertNotEqual(result["instance_id"], first["instance_id"])
+ self.assertEqual(runtime.status("local")["instance_id"], result["instance_id"])
+
+ def test_changed_source_is_rejected_before_stopping_old_instance(self):
+ first = runtime.start("local", wait=10, shutdown_timeout=2)
+ self.assertTrue(first["ok"])
+ self.config.write_bytes(self.config.read_bytes() + b" ")
+ for allow in (False, True):
+ result = runtime.restart("local", timeout=10, allow_source_switch=allow,
+ expected_source_sha256=hashlib.sha256(self.config.read_bytes()).hexdigest()
+ if allow else None)
+ self.assertFalse(result["ok"])
+ self.assertEqual(result["error"], "source_config_changed_restart_requires_migration")
+ self.assertEqual(runtime.status("local")["instance_id"], first["instance_id"])
+
+ def test_edited_source_migration_is_previewed_digest_pinned_and_verified(self):
+ first = runtime.start("local", wait=10, shutdown_timeout=2)
+ self.assertTrue(first["ok"])
+ edited = json.loads(self.config.read_text())
+ edited["model_name"] = "edited-fake"
+ self.config.write_text(json.dumps(edited), encoding="utf-8")
+ denied = runtime.plan_restart("local")
+ self.assertEqual(denied["error"], "source_config_changed_restart_requires_migration")
+ self.assertTrue(denied["requires_allow_source_migration"])
+ code, plan = self._cli("restart", "--profile", "local", "--allow-source-migration", "--plan")
+ self.assertEqual(code, 0)
+ self.assertTrue(plan["source_migration"])
+ self.assertTrue(plan["rollback_snapshot_required"])
+ self.assertFalse(plan["source_switch"])
+ self.assertTrue(plan["changed"])
+ self.assertEqual(runtime.status("local")["instance_id"], first["instance_id"])
+ code, missing = self._cli("restart", "--profile", "local", "--allow-source-migration")
+ self.assertEqual((code, missing["error"]["code"]), (2, 2))
+ self.config.write_bytes(self.config.read_bytes() + b" ")
+ code, stale = self._cli("restart", "--profile", "local", "--allow-source-migration",
+ "--if-source-sha256", plan["candidate_source_sha256"])
+ self.assertEqual((code, stale["error"]), (6, "source_changed_after_preview"))
+ self.assertEqual(runtime.status("local")["instance_id"], first["instance_id"])
+ self.config.write_text(json.dumps(edited), encoding="utf-8")
+ code, restarted = self._cli("restart", "--profile", "local", "--allow-source-migration",
+ "--if-profile-revision", plan["candidate_profile_revision"],
+ "--if-source-sha256", plan["candidate_source_sha256"],
+ "--startup-wait", "10", "--wait", "20")
+ self.assertEqual(code, 0, restarted)
+ self.assertTrue(restarted["source_migrated"])
+ self.assertFalse(restarted["source_switched"])
+ self.assertTrue(restarted["launch_attested"])
+ self.assertTrue(restarted["generation_ready"])
+ self.assertNotEqual(restarted["instance_id"], first["instance_id"])
+ self.assertTrue(journal.load("local", restarted["operation_id"])["result"]["source_migrated"])
+ self.assertEqual(list((self.root / "runtime").glob("*.rollback.json")), [])
+
+ def test_failed_edited_source_migration_uses_private_snapshot_for_rollback(self):
+ secret = "migration-test-key"
+ original = json.loads(self.config.read_text())
+ original["api_key"] = secret
+ self.config.write_text(json.dumps(original), encoding="utf-8")
+ first = runtime.start("local", wait=10, shutdown_timeout=2)
+ self.assertTrue(first["ok"])
+ with socket.socket() as occupied:
+ occupied.bind(("127.0.0.1", 0))
+ occupied.listen(1)
+ edited = json.loads(self.config.read_text())
+ edited["port"] = occupied.getsockname()[1]
+ self.config.write_text(json.dumps(edited), encoding="utf-8")
+ plan = runtime.plan_restart("local", allow_source_migration=True)
+ code, result = self._cli("restart", "--profile", "local", "--allow-source-migration",
+ "--startup-wait", "5", "--wait", "20",
+ "--if-source-sha256", plan["candidate_source_sha256"])
+ self.assertEqual(code, 6)
+ self.assertFalse(result["ok"])
+ self.assertTrue(result["rolled_back"])
+ self.assertEqual(result["state"], "ready")
+ self.assertNotEqual(result["instance_id"], first["instance_id"])
+ self.assertEqual(json.loads(self.config.read_text())["port"], edited["port"])
+ snapshot = Path(result["rollback_source_config"])
+ self.assertEqual(snapshot.parent, self.root / "runtime")
+ self.assertEqual(snapshot.stat().st_mode & 0o077, 0)
+ self.assertEqual(json.loads(snapshot.read_text())["port"], 0)
+ self.assertEqual(json.loads(snapshot.read_text())["api_key"], secret)
+ self.assertNotIn(secret, json.dumps(result))
+ record_result = journal.load("local", result["operation_id"])["result"]
+ self.assertEqual(record_result["rollback_source_config"], str(snapshot))
+ self.assertNotIn(secret, json.dumps(record_result))
+ self.assertTrue(runtime.status("local")["generation_ready"])
+ # The edited file can be retried as a distinct source after freeing its port.
+ plan = runtime.plan_restart("local", allow_source_switch=True)
+ self.assertTrue(plan["source_switch"])
+ retried = runtime.restart("local", timeout=20, startup_wait=10,
+ allow_source_switch=True,
+ expected_source_sha256=plan["candidate_source_sha256"])
+ self.assertTrue(retried["ok"], retried)
+ self.assertFalse(snapshot.exists())
+
+ def test_explicit_source_switch_previews_and_restarts_new_config(self):
+ first = runtime.start("local", wait=10, shutdown_timeout=2)
+ self.assertTrue(first["ok"])
+ next_config = self.root / "next-run.json"
+ changed = json.loads(self.config.read_text())
+ changed["model_name"] = "fake-next"
+ next_config.write_text(json.dumps(changed), encoding="utf-8")
+ previous_revision = profiles.load("local")[1]
+ source_output = io.StringIO()
+ with redirect_stdout(source_output):
+ source_code = main(["profile", "use-config", "local", "--from-config", str(next_config),
+ "--if-revision", previous_revision, "--output", "json"])
+ self.assertEqual(source_code, 0)
+ next_revision = json.loads(source_output.getvalue())["revision"]
+
+ denied = runtime.plan_restart("local")
+ self.assertFalse(denied["ok"])
+ self.assertEqual(denied["error"], "source_switch_requires_opt_in")
+ self.assertTrue(denied["requires_allow_source_switch"])
+ code, preview = self._cli("restart", "--profile", "local", "--allow-source-switch", "--plan")
+ self.assertEqual(code, 0)
+ self.assertTrue(preview["source_switch"])
+ self.assertTrue(preview["changed"])
+ self.assertEqual(preview["current_source_config"], str(self.config.resolve()))
+ self.assertEqual(preview["candidate_source_config"], str(next_config.resolve()))
+ self.assertEqual(preview["candidate_profile_revision"], next_revision)
+ self.assertEqual(runtime.status("local")["instance_id"], first["instance_id"])
+
+ code, missing_digest = self._cli("restart", "--profile", "local", "--allow-source-switch")
+ self.assertEqual(code, 2)
+ self.assertFalse(missing_digest["ok"])
+ self.assertEqual(runtime.status("local")["instance_id"], first["instance_id"])
+ next_config.write_bytes(next_config.read_bytes() + b" ")
+ code, stale = self._cli("restart", "--profile", "local", "--allow-source-switch",
+ "--if-source-sha256", preview["candidate_source_sha256"])
+ self.assertEqual(code, 6)
+ self.assertEqual(stale["error"], "source_changed_after_preview")
+ self.assertEqual(runtime.status("local")["instance_id"], first["instance_id"])
+ next_config.write_text(json.dumps(changed), encoding="utf-8")
+ code, switched = self._cli("restart", "--profile", "local", "--allow-source-switch",
+ "--if-profile-revision", next_revision, "--wait", "20",
+ "--if-source-sha256", preview["candidate_source_sha256"],
+ "--startup-wait", "10")
+ self.assertEqual(code, 0, switched)
+ self.assertTrue(switched["source_switched"])
+ self.assertNotEqual(switched["instance_id"], first["instance_id"])
+ self.assertEqual(switched["profile_revision"], next_revision)
+ self.assertTrue(switched["launch_attested"])
+ record = journal.load("local", switched["operation_id"])
+ self.assertTrue(record["intent"]["allow_source_switch"])
+ self.assertEqual(runtime.plan_restart("local")["source_switch"], False)
+
+ def test_failed_source_switch_restores_prior_owned_launch(self):
+ first = runtime.start("local", wait=10, shutdown_timeout=2)
+ self.assertTrue(first["ok"])
+ with socket.socket() as occupied:
+ occupied.bind(("127.0.0.1", 0))
+ occupied.listen(1)
+ next_config = self.root / "bad-next-run.json"
+ changed = json.loads(self.config.read_text())
+ changed["port"] = occupied.getsockname()[1]
+ next_config.write_text(json.dumps(changed), encoding="utf-8")
+ proposed, revision = profiles.load("local")
+ proposed["source_config"] = str(next_config)
+ profiles.save("local", proposed, expected_revision=revision)
+ digest = hashlib.sha256(next_config.read_bytes()).hexdigest()
+ result = runtime.restart("local", timeout=20, startup_wait=5, allow_source_switch=True,
+ expected_source_sha256=digest)
+ self.assertFalse(result["ok"])
+ self.assertTrue(result["rolled_back"])
+ self.assertNotEqual(result["instance_id"], first["instance_id"])
+ self.assertEqual(runtime.status("local")["instance_id"], result["instance_id"])
+ self.assertEqual(runtime.status("local")["profile_revision"], revision)
+
+ def test_source_switch_needs_unchanged_distinct_regular_rollback_file(self):
+ first = runtime.start("local", wait=10, shutdown_timeout=2)
+ self.assertTrue(first["ok"])
+ hardlink = self.root / "same-inode.json"
+ os.link(self.config, hardlink)
+ proposed, revision = profiles.load("local")
+ proposed["source_config"] = str(hardlink)
+ profiles.save("local", proposed, expected_revision=revision)
+ denied = runtime.plan_restart("local", allow_source_switch=True)
+ self.assertEqual(denied["error"], "source_switch_requires_distinct_regular_files")
+
+ next_config = self.root / "next-run.json"
+ next_config.write_bytes(self.config.read_bytes())
+ proposed, revision = profiles.load("local")
+ proposed["source_config"] = str(next_config)
+ profiles.save("local", proposed, expected_revision=revision)
+ self.config.write_bytes(self.config.read_bytes() + b" ")
+ denied = runtime.plan_restart("local", allow_source_switch=True)
+ self.assertEqual(denied["error"], "rollback_source_changed")
+ self.assertEqual(runtime.status("local")["instance_id"], first["instance_id"])
+ allowed = runtime.plan_restart("local", allow_source_switch=True,
+ allow_source_migration=True)
+ self.assertTrue(allowed["source_switch"])
+ self.assertTrue(allowed["source_migration"])
+ result = runtime.restart("local", timeout=20, startup_wait=10,
+ allow_source_switch=True, allow_source_migration=True,
+ expected_source_sha256=allowed["candidate_source_sha256"])
+ self.assertTrue(result["ok"], result)
+ self.assertTrue(result["source_switched"])
+ self.assertTrue(result["source_migrated"])
+ self.assertEqual(list((self.root / "runtime").glob("*.rollback.json")), [])
+
+ def test_server_reading_changed_config_fails_launch_attestation(self):
+ host = runtime.Host("local", shutdown_timeout=2, startup_wait=10)
+ plan, args, source, original = host._plan()
+ # Change valid JSON between the owner's snapshot and the server's read.
+ self.config.write_bytes(original + b" ")
+ try:
+ host._launch(args, source, original, plan["profile_revision"])
+ result = host._wait_ready(10)
+ self.assertFalse(result["ok"])
+ self.assertEqual(result["error"], "probe_launch_attestation_mismatch")
+ finally:
+ host._stop_child()
+
+ def test_authenticated_generation_probe_keeps_credential_out_of_status(self):
+ secret = "runtime-probe-test-key"
+ cfg = json.loads(self.config.read_text())
+ cfg["api_key"] = secret
+ self.config.write_text(json.dumps(cfg))
+ result = runtime.start("local", wait=10, shutdown_timeout=2)
+ self.assertTrue(result["generation_ready"])
+ self.assertTrue(result["launch_attested"])
+ self.assertNotIn(secret, json.dumps(result))
+ self.assertNotIn(secret, json.dumps(runtime.status("local")))
+
+ def test_remote_bind_preview_accepts_server_supported_key_list(self):
+ cfg = json.loads(self.config.read_text())
+ cfg.update(host="0.0.0.0", api_key=["first", "second"])
+ self.config.write_text(json.dumps(cfg))
+ from strata_cli.cli import _launch_plan
+ plan, _ = _launch_plan("local")
+ self.assertEqual(plan["effective"]["host"], "0.0.0.0")
+ self.assertNotIn("first", json.dumps(plan))
+
+ def test_lazy_model_is_verified_as_unloaded_without_generation(self):
+ cfg = json.loads(self.config.read_text())
+ cfg["lazy_load"] = True
+ self.config.write_text(json.dumps(cfg))
+ result = runtime.start("local", wait=10, shutdown_timeout=2)
+ self.assertTrue(result["ok"])
+ self.assertTrue(result["api_identity_verified"])
+ self.assertFalse(result["generation_ready"])
+ self.assertEqual((result["model_state"], result["readiness_state"]), ("unloaded", "unloaded"))
+ code, checked = self._cli("verify", "--profile", "local", "--wait", "10", "--load")
+ self.assertEqual(code, 0)
+ self.assertTrue(checked["generation_ready"])
+ self.assertEqual(runtime.status("local")["model_state"], "ready")
+ self.assertTrue(runtime.verify("local", timeout=10)["generation_ready"])
+
+ def test_failed_generation_probe_does_not_report_ready(self):
+ engine = self.root / "engine.py"
+ engine.write_text(engine.read_text().replace(" print('T 97', flush=True)",
+ " print('ERR probe-failed', flush=True)\n continue"))
+ result = runtime.start("local", wait=10, shutdown_timeout=2)
+ self.assertFalse(result["ok"])
+ self.assertEqual(result["state"], "failed")
+ self.assertEqual(result["error"], "probe_http_400")
+
+ def test_zero_token_completion_does_not_count_as_generation_ready(self):
+ (self.root / "empty-generation").write_text("empty")
+ result = runtime.start("local", wait=10, shutdown_timeout=2)
+ self.assertFalse(result["ok"])
+ self.assertEqual(result["error"], "probe_generation_no_tokens")
+
+ def test_explicit_verify_reports_later_engine_failure_without_stopping_instance(self):
+ first = runtime.start("local", wait=10, shutdown_timeout=2)
+ self.assertTrue(first["generation_ready"])
+ flag = self.root / "fail-generation"
+ flag.write_text("fail")
+ code, checked = self._cli("verify", "--profile", "local", "--wait", "10")
+ self.assertEqual(code, 6)
+ self.assertEqual(checked["error"], "probe_http_400")
+ self.assertEqual(journal.load("local", checked["operation_id"])["state"], "failed")
+ self.assertEqual(runtime.status("local")["instance_id"], first["instance_id"])
+ flag.unlink()
+ self.assertTrue(runtime.verify("local", timeout=10)["generation_ready"])
+
+ def test_failed_generation_after_profile_edit_rolls_back_prior_launch(self):
+ first = runtime.start("local", wait=10, shutdown_timeout=2)
+ self.assertTrue(first["generation_ready"])
+ engine = self.root / "engine.py"
+ engine.write_text(engine.read_text().replace(
+ " print('T 97', flush=True)",
+ " if slot is not None:\n"
+ " print('ERR batch-probe-failed', flush=True)\n"
+ " continue\n"
+ " print('T 97', flush=True)"))
+ profiles.set_values("local", ["parallel=2"])
+ result = runtime.restart("local", timeout=30, startup_wait=10)
+ self.assertFalse(result["ok"])
+ self.assertTrue(result["rolled_back"])
+ restored = runtime.status("local")
+ self.assertTrue(restored["generation_ready"])
+ self.assertEqual(restored["instance_id"], result["instance_id"])
+
+ def test_start_plan_is_read_only(self):
+ code, result = self._cli("start", "--profile", "local", "--plan")
+ self.assertEqual(code, 0)
+ self.assertFalse(result["plan"]["would_start"])
+ self.assertIsNone(runtime._read_state("local"))
+ self.assertEqual(journal.list_runs("local"), [])
+
+ def test_restart_plan_compares_revision_without_stopping_instance(self):
+ started = runtime.start("local", wait=10, shutdown_timeout=2)
+ self.assertTrue(started["ok"])
+ unchanged = runtime.plan_restart("local")
+ self.assertTrue(unchanged["ok"])
+ self.assertFalse(unchanged["changed"])
+ profiles.set_values("local", ["parallel=2"])
+ code, planned = self._cli("restart", "--profile", "local", "--plan")
+ self.assertEqual(code, 0)
+ self.assertTrue(planned["changed"])
+ self.assertFalse(planned["would_drain"])
+ self.assertFalse(planned["would_start"])
+ count = len(journal.list_runs("local"))
+ code, denied = self._cli("restart", "--profile", "local",
+ "--if-profile-revision", planned["candidate_profile_revision"],
+ "--if-source-sha256", planned["candidate_source_sha256"],
+ "--if-owner-id", planned["current_owner_id"],
+ "--if-instance-id", "0" * 32)
+ self.assertEqual((code, denied["error"]["message"]),
+ (6, "instance_changed_after_restart_plan"))
+ self.assertEqual(len(journal.list_runs("local")), count)
+ self.assertEqual(runtime.status("local")["instance_id"], started["instance_id"])
+
+ def test_editable_recipe_previews_and_reruns_owned_instance(self):
+ recipes.initialize("local")
+ started = runtime.start("local", wait=10, shutdown_timeout=2)
+ self.assertTrue(started["ok"])
+ profiles.set_values("local", ["parallel=2"])
+ code, planned = self._ops("plan", "restart")
+ self.assertEqual(code, 0)
+ self.assertTrue(planned["plan"]["operation"]["preflight"]["changed"])
+ self.assertEqual(runtime.status("local")["instance_id"], started["instance_id"])
+ revision = planned["plan"]["recipe_revision"]
+ preflight = planned["plan"]["operation"]["preflight"]
+ code, ran = self._ops("run", "restart", "--if-revision", revision,
+ "--if-profile-revision", planned["plan"]["profile_revision"],
+ "--if-owner-id", preflight["current_owner_id"],
+ "--if-instance-id", preflight["current_instance_id"],
+ "--if-source-sha256", preflight["candidate_source_sha256"])
+ self.assertEqual(code, 0)
+ self.assertTrue(ran["operation"]["result"]["restarted"])
+ self.assertNotEqual(ran["operation"]["result"]["instance_id"], started["instance_id"])
+ record = journal.load("local", ran["operation"]["operation_id"])
+ self.assertEqual(record["state"], "succeeded")
+ self.assertEqual(record["result"]["instance_id"], ran["operation"]["result"]["instance_id"])
+ count = len(journal.list_runs("local"))
+ with self.assertRaisesRegex(profiles.ProfileError, "instance_changed_after_restart_plan"):
+ recipes.run("local", "restart", expected_revision=revision,
+ expected_profile_revision=planned["plan"]["profile_revision"],
+ expected_owner_id=preflight["current_owner_id"],
+ expected_instance_id=preflight["current_instance_id"],
+ expected_source_sha256=preflight["candidate_source_sha256"])
+ self.assertEqual(len(journal.list_runs("local")), count)
+
+ def test_stale_profile_revision_does_not_drain_owned_instance(self):
+ started = runtime.start("local", wait=10, shutdown_timeout=2)
+ self.assertTrue(started["ok"])
+ previous = profiles.load("local")[1]
+ profiles.set_values("local", ["parallel=2"])
+ result = runtime.restart("local", timeout=10, expected_profile_revision=previous)
+ self.assertFalse(result["ok"])
+ self.assertEqual(result["error"], "profile_changed_after_preview")
+ self.assertEqual(runtime.status("local")["instance_id"], started["instance_id"])
+
+ def _ops(self, *args):
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(["ops", *args, "--profile", "local", "--output", "json"])
+ return code, json.loads(output.getvalue())
+
+ def test_terminating_owner_host_stops_its_child_and_removes_state(self):
+ started = runtime.start("local", wait=10, shutdown_timeout=2)
+ self.assertTrue(started["ok"])
+ os.kill(started["host_pid"], signal.SIGTERM)
+ deadline = time.monotonic() + 8
+ while runtime._read_state("local") is not None and time.monotonic() < deadline:
+ time.sleep(0.05)
+ self.assertIsNone(runtime._read_state("local"))
+ owned = runtime._STARTED_HOSTS.pop("local", None)
+ if owned is not None:
+ self.assertEqual(owned.wait(timeout=3), 0)
+
+ def test_hard_killed_host_child_exits_and_next_start_recovers_private_state(self):
+ started = runtime.start("local", wait=10, shutdown_timeout=2)
+ self.assertTrue(started["ok"])
+ old_child = started["child_pid"]
+ state = runtime._read_state("local")
+ orphan = self.root / "runtime" / f"local-{state['token']}-{'a' * 32}.rollback.json"
+ orphan.write_bytes(self.config.read_bytes())
+ orphan.chmod(0o600)
+ os.kill(started["host_pid"], signal.SIGKILL)
+ owned = runtime._STARTED_HOSTS.pop("local")
+ self.assertEqual(owned.wait(timeout=3), -signal.SIGKILL)
+ stale = runtime.status("local")
+ self.assertEqual((stale["state"], stale["error"]), ("stale", "owner_host_lost"))
+ # The next start waits for the inherited-pipe guard to stop the old
+ # process group; it never sends a signal to the saved child PID.
+ replacement = runtime.start("local", wait=10, shutdown_timeout=2)
+ self.assertTrue(replacement["ok"])
+ self.assertNotEqual(replacement["child_pid"], old_child)
+ self.assertFalse(runtime._pid_exists(old_child))
+ self.assertFalse(orphan.exists())
+
+ def test_recovery_refuses_a_still_present_child(self):
+ state_path, socket_path, _ = runtime._paths("local")
+ token = "a" * 64
+ state = {"schema_version": 1, "profile": "local", "socket": str(socket_path),
+ "token": token, "host_pid": 999999}
+ lease = runtime._write_new(state_path, (json.dumps(state) + "\n").encode())
+ os.close(lease)
+ marker = runtime._child_marker("local", token)
+ marker.write_text(json.dumps({"host_token": token, "phase": "owned",
+ "pid": os.getpid(),
+ "ready": str(state_path.parent / "local-fake.ready.json")}), encoding="utf-8")
+ marker.chmod(0o600)
+ with self.assertRaisesRegex(profiles.ProfileError, "still present"):
+ runtime.start("local", wait=0, shutdown_timeout=2)
+ self.assertTrue(state_path.exists())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/terminal/test_terminal.py b/tests/terminal/test_terminal.py
new file mode 100644
index 000000000..2a177a062
--- /dev/null
+++ b/tests/terminal/test_terminal.py
@@ -0,0 +1,1647 @@
+"""Terminal contract checks that run without model weights or a GPU."""
+
+import asyncio
+import copy
+import io
+import json
+import os
+import tempfile
+import time
+import unittest
+from contextlib import redirect_stdout
+from pathlib import Path
+from unittest import mock
+
+from strata_cli.cli import main
+from strata_cli.client import (ClientError, Endpoint, normalize_legacy, normalize_status_only,
+ sanitize_telemetry, server_url)
+from strata_cli.render import display_width, field, render_view, safe
+from serve.server import (configure_batch_telemetry_env, parse_batch_window_sample,
+ parse_stage_in_flight_sample, parse_engine_stage_line,
+ read_engine_stage_log, visible_device_order)
+
+
+def four_gpu_snapshot():
+ metrics = {
+ "time": 1_790_000_000.0,
+ "engine": {"model": "test-model", "batch_groups": 4},
+ "live": {"parallel": 8, "running": 6, "queued": 5, "waiting": 2,
+ "slots": [{"slot": i, "group": i // 2, "state": "decoding" if i < 6 else "idle",
+ "prompt_tokens": 400 + i, "generated": i * 10} for i in range(8)]},
+ "hardware_static": {"gpu_count": 4, "gpu_name": "aggregate"},
+ "hardware": {"gpu_mem_used": 1000,
+ "gpus": [{"index": i, "name": f"GPU-{i}", "mem_used": 12 * 2**30,
+ "mem_total": 24 * 2**30, "util": 50 + i, "temp": 60 + i,
+ "power": 200 + i} for i in range(4)]},
+ "requests": [{"finish": "stop", "prompt_tokens": 100, "output_tokens": 20}],
+ "totals": {"requests": 1, "output_tokens": 20},
+ }
+ status = {"service": "strata", "model": "test-model", "loaded": True,
+ "concurrency": {"serving": 8}, "started": 1_789_999_000}
+ return normalize_legacy(metrics, status)
+
+
+class ContractTests(unittest.TestCase):
+ def test_replica_slots_and_requests_keep_identity_without_aggregate_batch_claim(self):
+ sample = four_gpu_snapshot()
+ sample["topology"]["mode"] = "replicas (configured)"
+ sample["topology"]["replica_devices"] = [{"replica": 0, "devices": [0, 1]},
+ {"replica": 1, "devices": [2, 3]}]
+ sample["sampled_at"] = time.time()
+ sample["work"]["groups"] = 2
+ sample["work"]["effective_rows_window"] = None
+ for slot in sample["work"]["slots"]:
+ slot["replica"] = slot["slot"] // 4
+ slot["group"] = slot["replica"]
+ sample["work"]["requests"] = [{"id": "abcdef012345", "state": "reading", "slot": 5,
+ "group": 1, "replica": 1, "prompt_tokens": 100, "prompt_read": 12}]
+ clean = sanitize_telemetry(sample)
+ self.assertEqual(clean["work"]["slots"][5]["replica"], 1)
+ self.assertEqual(clean["work"]["requests"][0]["replica"], 1)
+ self.assertEqual(clean["topology"]["replica_devices"][1]["devices"], [2, 3])
+ from rich.console import Console
+ from strata_cli.dashboard import MonitorHistory, render_dashboard
+ output = io.StringIO()
+ Console(file=output, width=110, color_system=None).print(render_dashboard(
+ clean, width=108, height=28, history=MonitorHistory(), color=False))
+ self.assertIn("replicas 2", output.getvalue())
+ self.assertIn("R1 G1", output.getvalue())
+ self.assertRegex(output.getvalue(), r"GPU 2 R1")
+ sample["work"]["replica_batches"] = [
+ {"replica": 0, "batch_sample_windows": 2, "batch_sample_rows": 8,
+ "batch_sample_active_rows": 4, "batch_sample_span_s": 1.0, "batch_sample_age_s": 0.5},
+ {"replica": 1, "batch_sample_windows": 2, "batch_sample_rows": 6,
+ "batch_sample_active_rows": 4, "batch_sample_span_s": 1.0, "batch_sample_age_s": 0.7}]
+ sample["work"].update(batch_sample_windows=2, batch_sample_rows=8,
+ batch_sample_active_rows=4, batch_sample_span_s=1.0,
+ batch_sample_age_s=0.5)
+ clean = sanitize_telemetry(sample)
+ self.assertIsNone(clean["work"]["effective_rows_window"])
+ self.assertEqual([row.get("effective_rows_window") for row in clean["work"]["replica_batches"]],
+ [4.0, 3.0])
+ output = io.StringIO()
+ Console(file=output, width=110, color_system=None).print(render_dashboard(
+ clean, width=108, height=28, history=MonitorHistory(), color=False))
+ self.assertIn("R0 4.0/2.0", output.getvalue())
+ self.assertIn("R1 3.0/2.0", output.getvalue())
+ self.assertIn("R1 3.0/2.0", render_view(clean, "serving", 110, 30))
+ self.assertIn("Replica 1", render_view(clean, "serving", 80, 24,
+ serving_pane="groups", selected=5, detail=True))
+ self.assertIn("Replica 1", render_view(clean, "requests", 80, 24, selected=0, detail=True))
+ self.assertIn("Replica R1 [configured cards 2,3", render_view(
+ clean, "hardware", 80, 24, selected=2, detail=True))
+ sample["topology"]["replica_stages"] = [
+ {"replica": replica, "stages": [
+ {"stage": stage, "layer_start": stage * 20, "layer_end": stage * 20 + 19,
+ "engine_ordinal": stage, "device_index": replica * 2 + stage}
+ for stage in range(2)]} for replica in range(2)]
+ sample["work"]["replica_stage_samples"] = [
+ {"replica": 0, "stage_sample_elapsed_us": 1_000_000,
+ "stage_in_flight_us": [800_000, 600_000], "stage_sample_age_s": 0.5},
+ {"replica": 1, "stage_sample_elapsed_us": 1_000_000,
+ "stage_in_flight_us": [700_000, 500_000], "stage_sample_age_s": 0.7}]
+ clean = sanitize_telemetry(sample)
+ self.assertTrue(clean["topology"]["replica_stages"][1]["resolved"])
+ self.assertEqual(clean["quality"]["stage_in_flight"], "unavailable")
+ self.assertEqual(clean["quality"]["replica_stage_in_flight"], "measured_host_span")
+ self.assertEqual([row["stage_in_flight"][0]["percent"] for row in
+ clean["work"]["replica_stage_samples"]], [80.0, 70.0])
+ self.assertIn("R1 Stage 1 Device 3 Layers 20-39 In-flight 50%",
+ render_view(clean, "engine", 80, 24))
+ self.assertIn("Replica host span R0 S0 80% S1 60% R1 S0 70% S1 50%", render_view(
+ clean, "serving", 110, 30))
+ self.assertIn("Replica R1 stage/layers 1:20-39 [engine log]", render_view(
+ clean, "hardware", 80, 24, selected=3, detail=True))
+ output = io.StringIO()
+ Console(file=output, width=110, color_system=None).print(render_dashboard(
+ clean, width=108, height=28, history=MonitorHistory(), color=False))
+ self.assertIn("Host span R1 S0 70%", output.getvalue())
+ self.assertIn("GPU 2 R1/S0", output.getvalue())
+ old_stage = copy.deepcopy(clean)
+ old_stage["work"]["replica_stage_samples"][1]["stage_sample_age_s"] = 5.1
+ output = io.StringIO()
+ Console(file=output, width=110, color_system=None).print(render_dashboard(
+ old_stage, width=108, height=28, history=MonitorHistory(), color=False))
+ self.assertIn("Host span R1 --", output.getvalue())
+ self.assertNotIn("Host span R1 S0 70%", output.getvalue())
+ compact_output = io.StringIO()
+ Console(file=compact_output, width=80, color_system=None).print(render_dashboard(
+ clean, width=78, height=24, history=MonitorHistory(), color=False))
+ self.assertIn("GPU 3 R1/S1", compact_output.getvalue())
+ shared_card = copy.deepcopy(clean)
+ shared_card["topology"]["replica_stages"][1]["stages"][0]["device_index"] = 3
+ shared_output = io.StringIO()
+ Console(file=shared_output, width=80, color_system=None).print(render_dashboard(
+ shared_card, width=78, height=24, history=MonitorHistory(), color=False))
+ self.assertIn("GPU 3 R1 ", shared_output.getvalue())
+ self.assertNotIn("GPU 3 R1/S", shared_output.getvalue())
+ partial = copy.deepcopy(sample)
+ partial["work"]["slots"] = partial["work"]["slots"][:2]
+ output = io.StringIO()
+ Console(file=output, width=110, color_system=None).print(render_dashboard(
+ sanitize_telemetry(partial), width=108, height=28, history=MonitorHistory(), color=False))
+ self.assertIn("replicas 2", output.getvalue())
+ self.assertIn("R0 4.0/2.0", output.getvalue())
+ self.assertIn("Group occupancy --", output.getvalue())
+ sample["work"]["slots"][5]["replica"] = 1.5
+ sample["work"]["requests"][0]["replica"] = True
+ sample["work"]["replica_batches"][1]["batch_sample_rows"] = 99
+ sample["work"]["replica_stage_samples"][1]["stage_in_flight_us"] = [700_000]
+ sample["topology"]["replica_stages"][1]["stages"][1]["device_index"] = 9
+ sample["topology"]["replica_devices"].append({"replica": 2, "devices": [3]})
+ rejected = sanitize_telemetry(sample)
+ self.assertIsNone(rejected["work"]["slots"][5]["replica"])
+ self.assertIsNone(rejected["work"]["requests"][0]["replica"])
+ self.assertIsNone(rejected["work"]["replica_batches"][1].get("effective_rows_window"))
+ self.assertNotIn("stage_in_flight", rejected["work"]["replica_stage_samples"][1])
+ self.assertEqual(rejected["work"]["replica_stage_samples"][0]["stage_in_flight"][0]["percent"], 80.0)
+ self.assertEqual(rejected["quality"]["replica_stage_in_flight"], "measured_host_span")
+ self.assertEqual(len(rejected["topology"]["replica_devices"]), 2)
+ self.assertIsNone(rejected["topology"]["replica_stages"][1]["stages"][1]["device_index"])
+ self.assertFalse(rejected["topology"]["replica_stages"][1]["resolved"])
+ output = io.StringIO()
+ Console(file=output, width=80, color_system=None).print(render_dashboard(
+ rejected, width=78, height=24, history=MonitorHistory(), color=False))
+ self.assertIn("GPU 3 R1 ", output.getvalue())
+ self.assertNotIn("GPU 3 R1/S1", output.getvalue())
+
+ def test_display_cells_preserve_wide_and_combining_clusters(self):
+ self.assertEqual(safe("漢字", 3), "漢")
+ self.assertEqual(display_width(safe("漢字", 3)), 2)
+ self.assertEqual(safe("x\u0338Y", 1), "x\u0338")
+ self.assertEqual(display_width(safe("x\u0338Y", 1)), 1)
+ self.assertEqual(safe("🇭🇷next", 1), "")
+ self.assertEqual(safe("🇭🇷next", 2), "🇭🇷")
+ self.assertEqual(safe("👩‍💻next", 2), "👩‍💻")
+ self.assertEqual(safe("\u202e漢", 2), "漢")
+ self.assertEqual(display_width(field("漢A", 4)), 4)
+ self.assertEqual(field("漢A", 4), "漢A ")
+ snapshot = four_gpu_snapshot()
+ snapshot["devices"][0]["name"] = "漢字GPUx\u0338"
+ snapshot["work"]["requests"] = [{"id": "漢字reqx\u0338", "state": "decoding",
+ "slot": 0, "group": 0, "generated": 3}]
+ for width, height in ((110, 30), (80, 24), (60, 16), (40, 12)):
+ with self.subTest(width=width):
+ for name in ("hardware", "serving", "requests"):
+ view = render_view(snapshot, name, width, height)
+ self.assertTrue(all(display_width(line) <= width for line in view.splitlines()), name)
+
+ def test_batch_telemetry_opt_in_and_explicit_disable_are_reversible(self):
+ env = {"STRATA_BATCH_TELEMETRY": "1"}
+ configure_batch_telemetry_env(env, {}, None)
+ self.assertEqual(env["STRATA_BATCH_TELEMETRY"], "1")
+ configure_batch_telemetry_env(env, {"batch_telemetry": False}, None)
+ self.assertNotIn("STRATA_BATCH_TELEMETRY", env)
+ configure_batch_telemetry_env(env, {"batch_telemetry": False}, True)
+ self.assertEqual(env["STRATA_BATCH_TELEMETRY"], "1")
+ configure_batch_telemetry_env(env, {"batch_telemetry": True}, False)
+ self.assertNotIn("STRATA_BATCH_TELEMETRY", env)
+
+ def test_batch_window_sample_distinguishes_processed_rows_from_active_slots(self):
+ self.assertEqual(parse_batch_window_sample("BSTAT 3 18 9 1000\n"),
+ {"windows": 3, "processed_rows": 18, "active_rows": 9, "elapsed_ms": 1000})
+ for invalid in ("BSTAT 0 2 1 100", "BSTAT 1 9 1 100", "BSTAT 1 4 5 100", "BSTAT 2 2 0 100",
+ "BSTAT 1 1 1 0", "BSTAT 1 1 1 extra", "BSTAT " + "9" * 100):
+ self.assertIsNone(parse_batch_window_sample(invalid))
+ sample = four_gpu_snapshot()
+ sample["work"].update(batch_sample_windows=3, batch_sample_rows=18,
+ batch_sample_active_rows=9, batch_sample_span_s=1.0,
+ batch_sample_age_s=1.5,
+ effective_rows_window=999)
+ sample["quality"]["batch_window_rows"] = "measured"
+ clean = sanitize_telemetry(sample)
+ self.assertEqual(clean["work"]["effective_rows_window"], 6.0)
+ self.assertEqual(clean["work"]["batch_active_rows_window"], 3.0)
+ self.assertEqual(clean["quality"]["batch_window_rows"], "measured")
+ self.assertEqual(clean["quality"]["batch_window_source"], "engine_bstat")
+ serving = render_view(clean, "serving", 110, 30)
+ self.assertIn("6.0 processed / 3.0 active", serving)
+ sample["work"]["batch_sample_rows"] = 25
+ rejected = sanitize_telemetry(sample)
+ self.assertIsNone(rejected["work"]["effective_rows_window"])
+ self.assertEqual(rejected["quality"]["batch_window_rows"], "unavailable")
+
+ def test_pipeline_stage_in_flight_sample_is_bounded_and_labelled_host_time(self):
+ self.assertEqual(parse_stage_in_flight_sample("PSTAT 4 20000 16000 14000 12000 10000\n"),
+ {"elapsed_us": 20000, "in_flight_us": [16000, 14000, 12000, 10000]})
+ for invalid in ("PSTAT 1 20000 10000", "PSTAT 4 20000 16000 14000 12000",
+ "PSTAT 4 20000 16000 14000 12000 21000", "PSTAT 2 0 0 0",
+ "PSTAT 2 100 1 -1", "PSTAT 2 100 1 1 extra", "PSTAT " + "9" * 300):
+ self.assertIsNone(parse_stage_in_flight_sample(invalid))
+ sample = four_gpu_snapshot()
+ sample["work"].update(stage_sample_elapsed_us=1_000_000,
+ stage_in_flight_us=[800000, 700000, 600000, 500000],
+ stage_sample_age_s=0.2)
+ clean = sanitize_telemetry(sample)
+ self.assertEqual([row["percent"] for row in clean["work"]["stage_in_flight"]],
+ [80.0, 70.0, 60.0, 50.0])
+ self.assertEqual(clean["quality"]["stage_in_flight_source"], "engine_pstat_host_span")
+ self.assertIn("S3 50%", render_view(clean, "serving", 110, 30))
+ self.assertIn("80/70/60/50%", render_view(clean, "engine", 40, 12))
+ self.assertIn("GPU kernel occupancy unavailable", render_view(clean, "engine", 80, 24))
+ from rich.console import Console
+ from strata_cli.dashboard import MonitorHistory, render_dashboard
+ old_stage = copy.deepcopy(clean)
+ old_stage["work"]["stage_sample_age_s"] = 5.1
+ output = io.StringIO()
+ Console(file=output, width=110, color_system=None).print(render_dashboard(
+ old_stage, width=108, height=28, history=MonitorHistory(), color=False))
+ self.assertIn("Stage host span --", output.getvalue())
+ detail = render_view(clean, "serving", 80, 24, serving_pane="groups", selected=7, detail=True)
+ self.assertIn("group 3", detail)
+ self.assertIn("q quit", detail)
+ sample["topology"] = {"mode": "layer split", "resolved": True, "source": "engine_start_log",
+ "stages": [{"stage": i, "layer_start": i * 12, "layer_end": i * 12 + 11,
+ "engine_ordinal": i, "device_index": i} for i in range(4)]}
+ mapped = sanitize_telemetry(sample)
+ engine = render_view(mapped, "engine", 80, 24)
+ self.assertIn("Stage 3 Engine GPU 3 Device 3 Layers 36-47 In-flight 50%", engine)
+ self.assertIn("q quit", engine)
+ sample["work"]["stage_in_flight_us"] = [800000, 700000, 600000]
+ self.assertEqual(sanitize_telemetry(sample)["quality"]["stage_in_flight"], "unavailable")
+ sample["work"]["stage_in_flight_us"] = [800000, 700000, 600000, 500000]
+ sample["work"]["stage_in_flight_us"][1] = 1_000_001
+ rejected = sanitize_telemetry(sample)
+ self.assertEqual(rejected["work"]["stage_in_flight"], [])
+ self.assertEqual(rejected["quality"]["stage_in_flight"], "unavailable")
+
+ def test_engine_stage_log_is_bounded_and_reports_only_valid_final_ranges(self):
+ line = ("strata serve: layer split: layers 0-11 (CUDA0), 12-23 (CUDA1), "
+ "24-35 (CUDA2), 36-47 (CUDA3), one hand-off per window")
+ self.assertEqual([row["layer_start"] for row in parse_engine_stage_line(line)], [0, 12, 24, 36])
+ for bad in (line.replace("12-23", "13-23"), line.replace("CUDA3", "CUDA99"),
+ line.replace("0-11", "0" * 6000 + "-11"),
+ line.replace("one hand-off per window", "unverified")):
+ self.assertIsNone(parse_engine_stage_line(bad))
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "engine.log"
+ path.write_text(line + "\n", encoding="utf-8")
+ offset = path.stat().st_size
+ self.assertEqual(read_engine_stage_log(str(path), offset), [])
+ with path.open("a", encoding="utf-8") as target:
+ target.write("INFO engine=0.1.42\n" + line + "\nREADY 4096 stop\n")
+ self.assertEqual(len(read_engine_stage_log(str(path), offset)), 4)
+ self.assertEqual(read_engine_stage_log(str(path), offset, limit=12), [])
+ cuda_env = {"CUDA_VISIBLE_DEVICES": "2,0,3,1", "CUDA_DEVICE_ORDER": "PCI_BUS_ID"}
+ self.assertEqual(visible_device_order(cuda_env, "cuda"), [2, 0, 3, 1])
+ self.assertEqual(visible_device_order({"CUDA_VISIBLE_DEVICES": "2,0,3,1"}, "cuda"), [])
+ self.assertEqual(visible_device_order({"HIP_VISIBLE_DEVICES": "1,0"}, "hip"), [1, 0])
+ self.assertEqual(visible_device_order({**cuda_env, "CUDA_VISIBLE_DEVICES": "2,2"}, "cuda"), [])
+ self.assertEqual(visible_device_order({**cuda_env, "CUDA_VISIBLE_DEVICES": "9" * 6000}, "cuda"), [])
+ self.assertEqual(visible_device_order({"CUDA_VISIBLE_DEVICES": "2,0"}, "sycl"), [])
+
+ def test_reported_stage_ranges_render_and_invalid_remote_map_is_rejected(self):
+ s = four_gpu_snapshot()
+ s["topology"] = {"mode": "layer split (engine reported)", "resolved": True,
+ "source": "engine_start_log", "stages": [
+ {"stage": i, "layer_start": i * 12, "layer_end": i * 12 + 11,
+ "engine_ordinal": i, "device_index": i} for i in range(4)]}
+ clean = sanitize_telemetry(s)
+ self.assertTrue(clean["topology"]["resolved"])
+ engine = render_view(clean, "engine", 80, 24)
+ device = render_view(clean, "hardware", 80, 24, selected=3, detail=True)
+ wide = render_view(clean, "serving", 110, 30)
+ self.assertIn("Stage 3 Engine GPU 3 Device 3 Layers 36-47", engine)
+ self.assertIn("Stage/layers 3:36-47 [engine log]", device)
+ self.assertIn("GPU 3: 36-47", wide)
+ s["topology"]["stages"][1]["layer_start"] = 13
+ rejected = sanitize_telemetry(s)
+ self.assertEqual(rejected["topology"]["stages"], [])
+ self.assertFalse(rejected["topology"]["resolved"])
+ self.assertEqual(rejected["quality"]["placement"], "unavailable")
+
+ def test_remote_url_requires_tls_and_no_embedded_credentials(self):
+ for url in ("http://example.com:8080", "https://[email protected]", "https://example.com/v1",
+ "https://example.com/#fragment"):
+ with self.assertRaises(ValueError, msg=url):
+ server_url(url)
+ self.assertEqual(server_url("http://127.0.0.1:8080/"), "http://127.0.0.1:8080")
+
+ def test_parallel_fields_do_not_invent_window_metrics(self):
+ s = four_gpu_snapshot()
+ self.assertEqual(len(s["devices"]), 4)
+ self.assertEqual(s["work"]["groups"], 4)
+ self.assertEqual(s["work"]["active"], 6)
+ self.assertEqual(s["work"]["occupied_slots"], 6)
+ self.assertEqual(s["work"]["queued"], 5)
+ self.assertIsNone(s["work"]["effective_rows_window"])
+ self.assertIsNone(s["work"]["slots_requested"])
+ self.assertIsNone(s["topology"]["mode"])
+ serving = render_view(s, "serving", 110, 30)
+ self.assertIn("GPU 3", serving)
+ self.assertIn("group 3", serving)
+ self.assertIn("rows/window --", serving)
+ self.assertIn("Engine waiting 2", serving)
+ self.assertIn("Slots occupied 6/8", serving)
+ self.assertIn("Stage/layer mapping unavailable", serving)
+ self.assertNotIn("aggregate", serving)
+ s["work"]["requests"] = [{"id": "queued-1", "state": "queued", "queued_at": 1_790_000_000.0,
+ "slot": None, "group": None, "prompt_tokens": 512}]
+ requests = render_view(s, "serving", 80, 24, serving_pane="requests")
+ groups = render_view(s, "serving", 80, 24, serving_pane="groups")
+ request_view = render_view(s, "requests", 80, 24)
+ self.assertIn("queued-1", requests)
+ self.assertIn("group 3", groups)
+ last_group = render_view(s, "serving", 80, 24, serving_pane="groups", selected=7)
+ self.assertIn("slot 7", last_group)
+ self.assertIn("group 3", last_group)
+ self.assertIn("queued-1", request_view)
+ s["work"]["requests"] = [{"id": f"r{i:02d}", "state": "queued" if i > 5 else "decoding",
+ "queued_at": 1_790_000_000.0} for i in range(11)]
+ scrolled = render_view(s, "serving", 80, 24, serving_pane="requests", selected=10)
+ self.assertIn("r10", scrolled)
+ self.assertIn("queued", scrolled)
+
+ def test_occupied_slot_count_requires_complete_report(self):
+ metrics = {"live": {"slots": [{"slot": i, "state": "decoding" if i < 6 else "idle"}
+ for i in range(8)]}}
+ status = {"concurrency": {"serving": 8}}
+ complete = normalize_legacy(metrics, status)
+ self.assertEqual(complete["work"]["occupied_slots"], 6)
+ complete["work"]["occupied_slots"] = 99
+ self.assertEqual(sanitize_telemetry(complete)["work"]["occupied_slots"], 6)
+ metrics["live"]["slots"] = metrics["live"]["slots"][:-1]
+ partial = normalize_legacy(metrics, status)
+ self.assertIsNone(partial["work"]["occupied_slots"])
+ partial["work"]["occupied_slots"] = 6
+ self.assertIsNone(sanitize_telemetry(partial)["work"]["occupied_slots"])
+ metrics["live"]["slots"].append({"slot": 0, "state": "decoding"})
+ self.assertIsNone(normalize_legacy(metrics, status)["work"]["occupied_slots"])
+ metrics["live"]["slots"] = [{"slot": i, "state": "decoding"} for i in range(70)]
+ status["concurrency"]["serving"] = 70
+ self.assertEqual(len(normalize_legacy(metrics, status)["work"]["slots"]), 64)
+ self.assertIsNone(normalize_legacy(metrics, status)["work"]["occupied_slots"])
+
+ def test_admission_pressure_is_preserved_in_monitor_contract(self):
+ s = four_gpu_snapshot()
+ s["work"].update(admission_reserved=8, admission_limit=8, max_queue=0,
+ admission_rejected=3, oldest_queue_s=0, client_disconnect_cancels=2)
+ clean = sanitize_telemetry(s)
+ self.assertEqual(clean["work"]["max_queue"], 0)
+ display = render_view(clean, "serving", 110, 30)
+ self.assertIn("Admission 8/8", display)
+ self.assertIn("Queue cap 0", display)
+ self.assertIn("Rejected 3", display)
+ self.assertIn("Disconnect cancels 2", display)
+
+ def test_wide_parallel_layout_keeps_no_slot_requests_visible(self):
+ s = four_gpu_snapshot()
+ s["work"]["requests"] = [
+ {"id": f"r{i:02d}", "state": "decoding" if i < 8 else "admitted",
+ "slot": i if i < 8 else None, "group": i // 2 if i < 8 else None}
+ for i in range(12)]
+ display = render_view(s, "serving", 110, 30)
+ self.assertIn("r11", display)
+ self.assertIn("more requests", display)
+
+ def test_parallel_prompt_progress_and_frozen_queue_age(self):
+ s = four_gpu_snapshot()
+ s["work"]["requests"] = [
+ {"id": "reading-1", "state": "reading", "slot": 0, "group": 0,
+ "queued_at": 1_789_999_998.0, "admitted_at": 1_789_999_999.0,
+ "prompt_tokens": 1000, "prompt_read": 250, "generated": 0},
+ {"id": "queued-2", "state": "queued", "slot": None, "group": None,
+ "queued_at": 1_789_999_995.0, "admitted_at": None,
+ "prompt_tokens": 900, "prompt_read": None, "generated": None},
+ ]
+ for width, height, pane in ((110, 30, "devices"), (80, 24, "requests"), (40, 12, "requests")):
+ shown = render_view(s, "serving", width, height, serving_pane=pane)
+ self.assertIn("read 250 new", shown)
+ self.assertLessEqual(len(shown.splitlines()), height)
+ self.assertTrue(all(len(line) <= width for line in shown.splitlines()))
+ with mock.patch("strata_cli.render.time.time", return_value=1_800_000_000.0):
+ shown = render_view(s, "serving", 80, 24, serving_pane="requests")
+ self.assertIn("wait 5.0 s", shown)
+ self.assertIn("wait 1.0 s", shown)
+ small = render_view(s, "requests", 40, 12, selected=1)
+ self.assertIn("queued-2", small)
+ self.assertIn("Pre-admit 5", small)
+ detail = render_view(s, "serving", 80, 24, serving_pane="requests", detail=True)
+ self.assertIn("REQUEST DETAIL", detail)
+ self.assertIn("Prompt 1,000 tokens", detail)
+ self.assertIn("First engine token --", detail)
+ self.assertNotIn("prompt body", detail.lower())
+ fitted = render_view(s, "serving", 78, 22, serving_pane="requests", detail=True)
+ self.assertIn("First engine token --", fitted)
+ self.assertIn("Sample age", fitted)
+ self.assertIn("q quit", fitted)
+ filtered = render_view(s, "serving", 110, 30, filter_text="queued-2")
+ self.assertIn("queued-2", filtered)
+ self.assertNotIn("reading-1", filtered)
+ compact_detail = render_view(s, "serving", 60, 16, serving_pane="requests", selected=1, detail=True)
+ self.assertIn("queued-2", compact_detail)
+ self.assertIn("Wait 5.0 s", compact_detail)
+ s["work"]["requests"][0]["first_engine_token_s"] = 1.234
+ self.assertIn("First engine token 1.234 s", render_view(s, "serving", 80, 24,
+ serving_pane="requests", detail=True))
+ s["recent"] = [{"finish": "stop", "first_engine_token_s": 1.234}]
+ self.assertIn("First engine token 1.234 s", render_view(s, "overview", 80, 24))
+ self.assertIn("First engine token 1.234 s", render_view(s, "serving", 110, 30))
+
+ def test_small_layout_and_untrusted_text(self):
+ s = four_gpu_snapshot()
+ s["model"]["id"] = "\x1b[2Jfake\u202emodel"
+ for width, height in ((110, 30), (80, 24), (60, 16), (40, 12)):
+ output = render_view(s, "overview", width, height)
+ self.assertNotIn("\x1b", output)
+ self.assertNotIn("\u202e", output)
+ self.assertLessEqual(len(output.splitlines()), height)
+ self.assertTrue(all(len(line) <= width for line in output.splitlines()))
+ if (width, height) == (40, 12):
+ self.assertEqual(output.count("More: strata status --json"), 1)
+
+ def test_recent_request_detail_scrolls_and_wide_serving_tabs_select_panes(self):
+ s = four_gpu_snapshot()
+ s["work"]["requests"] = [{"id": "live-1", "state": "decoding", "slot": 0, "group": 0}]
+ s["recent"] = [{"id": f"done-{i:02d}", "finish": "stop", "prompt_tokens": 100 + i,
+ "reused": i, "output_tokens": 12, "duration_s": 1.25,
+ "prompt_ms": 200, "decode_ms": 400, "first_engine_token_s": 0.7}
+ for i in range(20)]
+ wide_requests = render_view(s, "serving", 110, 30, serving_pane="requests")
+ wide_groups = render_view(s, "serving", 110, 30, serving_pane="groups", selected=7)
+ self.assertIn("Pane: Requests", wide_requests)
+ self.assertIn("live-1", wide_requests)
+ self.assertIn("Pane: Groups", wide_groups)
+ self.assertIn("slot 7", wide_groups)
+ for width, height in ((60, 16), (40, 12)):
+ devices = render_view(s, "serving", width, height, serving_pane="devices")
+ requests = render_view(s, "serving", width, height, serving_pane="requests")
+ groups = render_view(s, "serving", width, height, serving_pane="groups", selected=7)
+ self.assertIn("GPU 0", devices)
+ self.assertIn("live-1", requests)
+ self.assertIn("slot 7", groups)
+ detail = render_view(s, "requests", 80, 24, selected=17, detail=True)
+ self.assertIn("done-16", detail)
+ self.assertIn("RECENT REQUEST DETAIL", detail)
+ self.assertIn("First engine token 0.700 s", detail)
+ self.assertIn("Sample age", detail)
+ self.assertLessEqual(len(detail.splitlines()), 24)
+ self.assertTrue(all(len(line) <= 80 for line in detail.splitlines()))
+ small = render_view(s, "requests", 40, 12, selected=17, detail=True)
+ self.assertIn("done-16", small)
+ self.assertIn("Engine first 0.70 s", small)
+ self.assertIn("Prompt 116", small)
+ s["work"]["requests"] = []
+ only_recent = render_view(s, "requests", 40, 12, selected=0, detail=True)
+ self.assertIn("done-00", only_recent)
+ self.assertIn("Engine first 0.70 s", only_recent)
+
+ def test_device_and_slot_details_fit_standard_and_compact_views(self):
+ s = four_gpu_snapshot()
+ s["work"]["slots"][7]["request_id"] = "request-7"
+ for view, pane, width, height, selected, marker in (
+ ("serving", "devices", 80, 24, 3, "GPU 3"),
+ ("serving", "groups", 80, 24, 7, "Slot 7"),
+ ("hardware", "devices", 80, 24, 3, "GPU 3"),
+ ("serving", "devices", 60, 16, 3, "GPU 3"),
+ ("serving", "groups", 40, 12, 7, "slot 7"),
+ ("hardware", "devices", 40, 12, 3, "GPU 3"),
+ ):
+ with self.subTest(view=view, pane=pane, width=width):
+ display = render_view(s, view, width, height, serving_pane=pane,
+ selected=selected, detail=True)
+ self.assertIn(marker, display)
+ self.assertLessEqual(len(display.splitlines()), height)
+ self.assertTrue(all(len(line) <= width for line in display.splitlines()))
+ self.assertIn("q quit", display)
+ if width == 80:
+ self.assertIn("DETAIL (read only)", display)
+ self.assertIn("Sample age", display)
+ device = render_view(s, "serving", 80, 24, serving_pane="devices", selected=3, detail=True)
+ slot = render_view(s, "serving", 80, 24, serving_pane="groups", selected=7, detail=True)
+ self.assertIn("Stage/layer mapping unavailable", device)
+ self.assertIn("Request request-7", slot)
+ self.assertIn("not a GPU assignment", slot)
+
+ def test_wide_serving_scrolls_to_selected_device(self):
+ s = four_gpu_snapshot()
+ s["devices"] = [{"index": i, "name": f"Card-{i}", "mem_used": 8 * 2**30,
+ "mem_total": 24 * 2**30, "util": i, "temp": 40 + i,
+ "power": 100 + i} for i in range(16)]
+ display = render_view(s, "serving", 110, 30, selected=15)
+ self.assertIn("> GPU 15", display)
+ self.assertIn("GPU SENSORS (", display)
+ self.assertIn("q quit", display)
+ self.assertLessEqual(len(display.splitlines()), 30)
+
+ def test_zero_is_not_unknown(self):
+ s = normalize_legacy({"live": {"queued": 0, "tok_s": 0}, "hardware": {},
+ "totals": {"requests": 0}}, {"concurrency": {"serving": 1}})
+ self.assertEqual(s["work"]["queued"], 0)
+ self.assertEqual(s["rates"]["answer_tok_s"], 0)
+ self.assertIsNone(s["rates"]["prefill_tok_s"])
+
+ def test_v1_snapshot_excludes_unknown_and_untrusted_content(self):
+ clean = sanitize_telemetry({"schema_version": 1, "secret": "do not render",
+ "model": {"id": "\x1b[2Jmodel", "prompt": "private"},
+ "work": {"slots": [{"slot": 0, "state": "decoding",
+ "prompt": "private"}],
+ "requests": [{"id": "req-1", "state": "queued",
+ "first_engine_token_s": float("nan"),
+ "input": "private"}]},
+ "rates": {"answer_tok_s": float("nan")}})
+ serialized = json.dumps(clean)
+ self.assertNotIn("private", serialized)
+ self.assertNotIn("do not render", serialized)
+ self.assertNotIn("\x1b", serialized)
+ self.assertIsNone(clean["rates"]["answer_tok_s"])
+ self.assertIsNone(clean["work"]["requests"][0]["first_engine_token_s"])
+
+ def test_activity_feed_is_bounded_redacted_and_visible_at_terminal_sizes(self):
+ raw = four_gpu_snapshot()
+ raw["activity"] = {"last_seq": 70, "events": [
+ {"seq": i, "at": 1_790_000_000.0, "request_id": f"{i:012x}",
+ "event": "finished", "outcome": "stop", "prompt": "private"}
+ for i in range(1, 71)
+ ]}
+ raw["activity"]["events"][-1]["event"] = "\x1b[2Jforged"
+ clean = sanitize_telemetry(raw)
+ self.assertTrue(clean["activity"]["available"])
+ self.assertLessEqual(len(clean["activity"]["events"]), 32)
+ self.assertNotIn("private", json.dumps(clean))
+ self.assertNotIn("forged", json.dumps(clean))
+ self.assertEqual(clean["activity"]["events"][-1]["seq"], 69)
+ for width, height in ((110, 30), (80, 24), (60, 16), (40, 12)):
+ display = render_view(clean, "logs", width, height)
+ self.assertIn("activity", display)
+ self.assertIn("finished", display)
+ self.assertNotIn("private", display)
+ self.assertNotIn("\x1b", display)
+ self.assertLessEqual(len(display.splitlines()), height)
+ self.assertTrue(all(len(line) <= width for line in display.splitlines()))
+ legacy = render_view(four_gpu_snapshot(), "logs", 80, 24)
+ self.assertIn("unavailable", legacy)
+ raw["activity"] = {"last_seq": [], "events": [{"event": []}]}
+ self.assertFalse(sanitize_telemetry(raw)["activity"]["available"])
+
+ def test_cli_rejects_invalid_serve_flags_before_loading_engine(self):
+ with redirect_stdout(io.StringIO()):
+ self.assertEqual(main(["serve", "--profile", "missing.json", "--parallel", "0"]), 2)
+
+ def test_offline_server_rejects_remote_image_before_fetch(self):
+ from serve.server import ByteTokenizer, ChatTemplate, MockEngine, Service
+ tok = ByteTokenizer()
+ svc = Service(MockEngine(tok, "ok"), tok,
+ ChatTemplate(Path(__file__).resolve().parents[2] / "serve/chat_template.jinja"))
+ svc.offline = True
+ messages = [{"role": "user", "content": [{"type": "image", "source": "https://example.com/p.png"}]}]
+ with self.assertRaisesRegex(ValueError, "offline mode cannot download"):
+ svc.prepare(messages, [], {})
+
+ def test_non_loopback_serve_requires_inference_key(self):
+ with tempfile.TemporaryDirectory() as directory:
+ profile = Path(directory) / "model.json"
+ profile.write_text('{"host":"0.0.0.0","args":[]}', encoding="utf-8")
+ with mock.patch.dict(os.environ, {"STRATA_API_KEY": ""}), redirect_stdout(io.StringIO()):
+ self.assertEqual(main(["serve", "--profile", str(profile)]), 2)
+
+ def test_direct_server_rejects_remote_bind_before_engine_load(self):
+ import serve.server as server
+ with tempfile.TemporaryDirectory() as directory:
+ profile = Path(directory) / "model.json"
+ profile.write_text('{"args":[]}', encoding="utf-8")
+ with mock.patch.dict(os.environ, {}, clear=True), \
+ mock.patch.object(server, "StrataEngine", side_effect=AssertionError("engine started")):
+ self.assertEqual(server.main(["--engine", "strata", "--config", str(profile),
+ "--host", "0.0.0.0", "--port", "0"]), 2)
+
+ def test_code_run_uses_missing_component_exit_until_shared_harness_arrives(self):
+ output = io.StringIO()
+ with redirect_stdout(output):
+ code = main(["code", "run", "--prompt-file", "task.md", "--policy", "policy.json",
+ "--output", "jsonl"])
+ self.assertEqual(code, 5)
+ self.assertEqual(json.loads(output.getvalue())["error"]["code"], 5)
+
+
+try:
+ from strata_cli.monitor import MonitorApp, with_aggregate_rate
+except ImportError:
+ MonitorApp = None
+
+
[email protected](MonitorApp is None, "optional Textual dependency absent")
+class HeadlessMonitorTests(unittest.TestCase):
+ def test_live_monitor_marks_activity_gaps_after_freeze_and_resets_on_restart(self):
+ from rich.console import Console
+
+ def snapshot(instance, last, seqs):
+ value = four_gpu_snapshot()
+ value["sampled_at"] = time.time()
+ value["instance"]["id"] = instance
+ value["activity"] = {"available": True, "last_seq": last, "events": [
+ {"seq": seq, "at": value["sampled_at"], "request_id": f"{seq:012x}",
+ "event": "queued", "outcome": None} for seq in seqs]}
+ return value
+
+ class Source:
+ root = "http://127.0.0.1:8095"
+
+ def snapshot(self):
+ return self.snapshots.pop(0)
+
+ Source.snapshots = [snapshot("a", 5, [2, 4, 5]), snapshot("b", 2, [1, 2])]
+
+ async def exercise():
+ app = MonitorApp(Source(), snapshot("a", 2, [1, 2]), interval=30)
+ async with app.run_test(size=(80, 24)) as pilot:
+ app.view = 5
+ app.action_freeze()
+ app._schedule_poll(force=True)
+ await pilot.pause(0.1)
+ self.assertIsNone(app.displayed_activity_continuity["gap"])
+ app.action_freeze()
+ await pilot.pause()
+ self.assertEqual(app.displayed_activity_continuity["gap"],
+ {"from_seq": 3, "to_seq": 3})
+ shown = str(app.query_one("#content").render())
+ self.assertIn("Missed activity #3-3", shown)
+ app.view = 0
+ app._paint()
+ await pilot.pause()
+ output = io.StringIO()
+ Console(file=output, width=80, color_system=None).print(app.query_one("#content").content)
+ self.assertIn("Missed activity #3-3", output.getvalue())
+ app._schedule_poll(force=True)
+ await pilot.pause(0.1)
+ self.assertIsNone(app.displayed_activity_continuity["gap"])
+ self.assertTrue(app.displayed_activity_continuity["restarted"])
+ app.view = 5
+ app._paint()
+ await pilot.pause()
+ self.assertIn("Serving restarted", str(app.query_one("#content").render()))
+ await pilot.press("q")
+
+ asyncio.run(exercise())
+
+ def test_live_compact_screen_replaces_cached_work_on_disconnect(self):
+ from rich.console import Console
+
+ sample = four_gpu_snapshot()
+ sample["sampled_at"] = time.time()
+ sample["model"]["id"] = "cached-model"
+ sample["work"]["requests"] = [{"id": "cached-request", "state": "decoding", "slot": 0}]
+
+ class Source:
+ root = "http://127.0.0.1:8095"
+
+ def snapshot(self):
+ return sample
+
+ async def exercise(width, height, view):
+ app = MonitorApp(Source(), sample, interval=30)
+ async with app.run_test(size=(width, height)) as pilot:
+ app.view = view
+ app.connection_state = "disconnected"
+ app._paint()
+ await pilot.pause(0.05)
+ output = io.StringIO()
+ Console(file=output, width=width, color_system=None).print(app.query_one("#content").content)
+ shown = output.getvalue()
+ self.assertIn("CONNECTION LOST", shown)
+ self.assertNotIn("cached-model", shown)
+ self.assertNotIn("cached-request", shown)
+ self.assertNotIn("GPU-0", shown)
+ await pilot.press("q")
+
+ asyncio.run(exercise(40, 12, 0))
+ asyncio.run(exercise(80, 24, 1))
+
+ def test_overview_uses_selected_cards_and_marks_missing_sensors(self):
+ from rich.console import Console
+ from strata_cli.dashboard import MonitorHistory, render_dashboard
+
+ sample = four_gpu_snapshot()
+ sample["sampled_at"] = time.time()
+ sample["topology"]["selected_devices"] = [2, 0, 3, 1, 2, -1, 1.5, True]
+ extra = {**sample["devices"][0], "index": 5, "name": "unselected GPU"}
+ sample["devices"] = [extra, sample["devices"][1], sample["devices"][2], sample["devices"][0]]
+ sample = sanitize_telemetry(sample)
+ self.assertEqual(sample["topology"]["selected_devices"], [2, 0, 3, 1])
+ history = MonitorHistory()
+ complete = four_gpu_snapshot()
+ history.add(complete, ("id", "selected-cards"))
+ history.add(sample, ("id", "selected-cards"))
+ self.assertEqual(list(history.device_util[3]), [complete["devices"][3]["util"], None])
+ self.assertEqual(list(history.device_vram[3]), [50.0, None])
+ self.assertNotIn(5, history.device_util)
+ self.assertNotIn(5, history.device_vram)
+ for width, height in ((110, 30), (80, 24)):
+ with self.subTest(width=width):
+ output = io.StringIO()
+ Console(file=output, width=width, color_system=None).print(render_dashboard(
+ sample, width=width - 2, height=height - 2, history=history,
+ color=False))
+ shown = output.getvalue()
+ positions = [shown.index(f"GPU {index}") for index in (2, 0, 3, 1)]
+ self.assertEqual(positions, sorted(positions))
+ self.assertRegex(shown, r"GPU 3[^\n]*--/--G")
+ if width == 80:
+ self.assertRegex(shown, r"GPU 3[^\n]*--/--G[^\n]*--\s+--")
+ self.assertNotIn("vram", shown)
+ else:
+ self.assertRegex(shown, r"GPU 2[^\n]*vram [^\s-]+")
+ self.assertRegex(shown, r"GPU 3[^\n]*vram --")
+ self.assertNotIn("GPU 5", shown)
+ self.assertEqual(len(shown.splitlines()), height - 1)
+
+ duplicate = {**sample, "devices": sample["devices"] + [dict(sample["devices"][-1])]}
+ history.add(duplicate, ("id", "selected-cards"))
+ self.assertIsNone(history.device_util[0][-1])
+ self.assertIsNone(history.device_vram[0][-1])
+ output = io.StringIO()
+ Console(file=output, width=80, color_system=None).print(render_dashboard(
+ duplicate, width=78, height=22, history=history, color=False))
+ self.assertRegex(output.getvalue(), r"GPU 0[^\n]*--/--G")
+ self.assertRegex(output.getvalue(), r"GPU 0[^\n]*--/--G[^\n]*--\s+--")
+
+ def test_monitor_history_bounds_device_indices_across_snapshots(self):
+ from strata_cli.dashboard import MonitorHistory, _output_trend
+
+ history = MonitorHistory()
+ for start in (0, 16, 32):
+ history.add({"devices": [{"index": index, "util": 20}
+ for index in range(start, start + 16)],
+ "rates": {"aggregate_output_tok_s": 42.0}}, ("id", "same"))
+ self.assertEqual(set(history.device_util), set(range(start, start + 16)))
+ self.assertEqual(set(history.device_vram), set(range(start, start + 16)))
+ history.add({"devices": [{"index": 32, "util": 40}]}, ("id", "same"))
+ self.assertEqual(set(history.device_util), {32})
+ self.assertEqual(set(history.device_vram), {32})
+ self.assertIsNone(history.device_vram[32][-1])
+ self.assertEqual(list(history.output_rate)[-1], None)
+ self.assertEqual(_output_trend(history.output_rate, "ascii", False), "Output trend --")
+
+ def test_vram_history_is_per_card_and_missing_values_are_not_zero(self):
+ from rich.console import Console
+ from strata_cli.dashboard import MonitorHistory, render_dashboard
+
+ sample = four_gpu_snapshot()
+ sample["sampled_at"] = time.time()
+ sample["devices"][0]["mem_used"] = 6 * 2**30
+ sample["devices"][1]["mem_used"] = 18 * 2**30
+ history = MonitorHistory()
+ history.add(sample, ("id", "memory-samples"))
+ self.assertEqual(history.device_vram[0][-1], 25.0)
+ self.assertEqual(history.device_vram[1][-1], 75.0)
+ output = io.StringIO()
+ Console(file=output, width=110, color_system=None).print(render_dashboard(
+ sample, width=108, height=28, history=history, glyphs="ascii", color=False))
+ self.assertRegex(output.getvalue(), r"GPU 0[^\n]*vram :")
+ self.assertRegex(output.getvalue(), r"GPU 1[^\n]*vram \*")
+
+ sample["devices"][0]["mem_total"] = 0
+ sample["devices"][1]["mem_used"] = 30 * 2**30
+ history.add(sample, ("id", "memory-samples"))
+ self.assertIsNone(history.device_vram[0][-1])
+ self.assertIsNone(history.device_vram[1][-1])
+ history.gap()
+ self.assertIsNone(history.device_vram[0][-1])
+ history.add(sample, ("id", "new-instance"))
+ self.assertEqual(len(history.device_vram[0]), 1)
+ self.assertIsNone(history.device_vram[0][-1])
+
+ sample["devices"][0]["mem_used"] = 1e308
+ sample["devices"][0]["mem_total"] = 1e308
+ history.add(sample, ("id", "new-instance"))
+ self.assertEqual(history.device_vram[0][-1], 100.0)
+ output = io.StringIO()
+ Console(file=output, width=110, color_system=None).print(render_dashboard(
+ sample, width=108, height=28, history=history, glyphs="ascii", color=False))
+ self.assertRegex(output.getvalue(), r"GPU 0[^\n]*vram\s+@")
+
+ def test_overview_output_trend_is_bounded_and_resets_with_instance(self):
+ from rich.console import Console
+ from strata_cli.dashboard import MonitorHistory, _output_trend, render_dashboard
+
+ sample = four_gpu_snapshot()
+ sample["sampled_at"] = time.time()
+ history = MonitorHistory()
+ for value in (100.0, 120.0, 110.0):
+ sample["rates"]["aggregate_output_tok_s"] = value
+ history.add(sample, ("id", "first"))
+ for width, height in ((110, 30), (80, 24), (110, 42)):
+ with self.subTest(width=width):
+ output = io.StringIO()
+ Console(file=output, width=width, color_system=None).print(render_dashboard(
+ sample, width=width - 2, height=height - 2, history=history,
+ glyphs="ascii", color=False))
+ shown = output.getvalue()
+ self.assertIn("100-120 tok/s", shown)
+ self.assertLessEqual(len(shown.splitlines()), height - 1)
+ self.assertTrue(all(display_width(line) <= width for line in shown.splitlines()))
+
+ stale = {**sample, "sampled_at": time.time() - 6}
+ output = io.StringIO()
+ Console(file=output, width=110, color_system=None).print(render_dashboard(
+ stale, width=108, height=28, history=history, glyphs="ascii", color=False))
+ self.assertIn("Output trend --", output.getvalue())
+ self.assertNotIn("100-120 tok/s", output.getvalue())
+
+ sample["rates"]["aggregate_output_tok_s"] = None
+ history.add(sample, ("id", "first"))
+ self.assertEqual(_output_trend(history.output_rate, "ascii", False), "Output trend --")
+ sample["rates"]["aggregate_output_tok_s"] = 90.0
+ history.add(sample, ("id", "second"))
+ self.assertEqual(list(history.output_rate), [90.0])
+ self.assertIn("▁▁ 0 tok/s", _output_trend([0.0, 0.0], "unicode", True))
+
+ def test_batch_and_queue_histories_keep_replica_windows_separate(self):
+ from rich.console import Console
+ from strata_cli.dashboard import MonitorHistory, render_dashboard
+
+ sample = four_gpu_snapshot()
+ sample["sampled_at"] = time.time()
+ history = MonitorHistory(limit=3)
+ for rows, queued in ((4.0, 1), (6.0, 5)):
+ sample["work"].update(effective_rows_window=rows, batch_sample_age_s=0.5,
+ queued=queued)
+ history.add(sample, ("id", "one"))
+ output = io.StringIO()
+ Console(file=output, width=110, color_system=None).print(render_dashboard(
+ sample, width=108, height=28, history=history, glyphs="ascii", color=False))
+ shown = output.getvalue()
+ self.assertIn("Rows trend", shown)
+ self.assertIn("4.0-6.0/win", shown)
+ self.assertIn("Pre-admit", shown)
+ self.assertIn("1-5 req", shown)
+ self.assertEqual(len(shown.splitlines()), 29)
+ compact = io.StringIO()
+ Console(file=compact, width=80, color_system=None).print(render_dashboard(
+ sample, width=78, height=22, history=history, glyphs="ascii", color=False))
+ self.assertNotIn("Rows trend", compact.getvalue())
+ self.assertIn("1 Over", compact.getvalue())
+ history.gap()
+ self.assertIsNone(history.batch_rows[-1])
+ self.assertIsNone(history.pre_admit[-1])
+ self.assertIsNone(history.device_util[0][-1])
+ after_gap = io.StringIO()
+ Console(file=after_gap, width=110, color_system=None).print(render_dashboard(
+ sample, width=108, height=28, history=history, glyphs="ascii", color=False))
+ self.assertNotIn("Rows trend", after_gap.getvalue())
+ self.assertNotIn("Pre-admit ", after_gap.getvalue())
+
+ sample["work"]["batch_sample_age_s"] = 5.1
+ history.add(sample, ("id", "one"))
+ old_single = io.StringIO()
+ Console(file=old_single, width=110, color_system=None).print(render_dashboard(
+ sample, width=108, height=28, history=history, glyphs="ascii", color=False))
+ self.assertIsNone(history.batch_rows[-1])
+ self.assertIn("Rows/win -- processed", old_single.getvalue())
+ self.assertNotIn("Rows trend", old_single.getvalue())
+
+ replica = copy.deepcopy(sample)
+ replica["topology"]["mode"] = "replicas (configured)"
+ replica["topology"]["replica_devices"] = [{"replica": 0, "devices": [0, 1]},
+ {"replica": 1, "devices": [2, 3]}]
+ replica["work"]["effective_rows_window"] = None
+ for first, second in ((4.0, 3.0), (5.0, 4.0)):
+ replica["work"]["replica_batches"] = [
+ {"replica": 0, "effective_rows_window": first, "batch_active_rows_window": 2.0,
+ "batch_sample_age_s": 0.5},
+ {"replica": 1, "effective_rows_window": second, "batch_active_rows_window": 2.0,
+ "batch_sample_age_s": 0.5}]
+ history.add(replica, ("id", "two"))
+ output = io.StringIO()
+ Console(file=output, width=110, color_system=None).print(render_dashboard(
+ replica, width=108, height=28, history=history, glyphs="ascii", color=False))
+ shown = output.getvalue()
+ self.assertIn("R0 rows", shown)
+ self.assertIn("4.0-5.0/win", shown)
+ self.assertIn("R1 rows", shown)
+ self.assertIn("3.0-4.0/win", shown)
+ self.assertNotIn("Rows trend", shown)
+
+ replica["work"]["replica_batches"][1]["batch_sample_age_s"] = 5.1
+ history.add(replica, ("id", "two"))
+ self.assertIsNone(history.replica_batch_rows[1][-1])
+ old_sample = io.StringIO()
+ Console(file=old_sample, width=110, color_system=None).print(render_dashboard(
+ replica, width=108, height=28, history=history, glyphs="ascii", color=False))
+ self.assertIn("R1 --/--", old_sample.getvalue())
+ self.assertNotIn("R1 rows", old_sample.getvalue())
+
+ replica["work"]["replica_batches"] = [replica["work"]["replica_batches"][0]]
+ history.add(replica, ("id", "two"))
+ self.assertIsNone(history.replica_batch_rows[1][-1])
+ self.assertEqual(len(history.replica_batch_rows[0]), 3)
+ history.add(replica, ("id", "three"))
+ self.assertEqual(len(history.batch_rows), 1)
+ self.assertEqual(len(history.replica_batch_rows[0]), 1)
+
+ def test_overview_slot_phases_require_complete_slot_report(self):
+ from rich.console import Console
+ from strata_cli.dashboard import MonitorHistory, render_dashboard
+
+ sample = four_gpu_snapshot()
+ sample["sampled_at"] = time.time()
+ sample["work"]["slots"][0]["state"] = "reading"
+ self.assertIn("Occupied slots by group G0 2/2", render_view(sample, "serving", 110, 30))
+ for width, height in ((110, 30), (80, 24)):
+ with self.subTest(width=width):
+ output = io.StringIO()
+ Console(file=output, width=width, color_system=None).print(render_dashboard(
+ sample, width=width - 2, height=height - 2, history=MonitorHistory(),
+ color=False))
+ shown = output.getvalue()
+ self.assertIn("read 1 decode 5 idle 2", shown)
+ self.assertLessEqual(len(shown.splitlines()), height - 1)
+ self.assertTrue(all(display_width(line) <= width for line in shown.splitlines()))
+
+ incomplete = dict(sample["work"])
+ incomplete["slots"] = incomplete["slots"][:-1]
+ output = io.StringIO()
+ Console(file=output, width=110, color_system=None).print(render_dashboard(
+ {**sample, "work": incomplete}, width=108, height=28, history=MonitorHistory(), color=False))
+ self.assertNotIn("Slot phases", output.getvalue())
+ self.assertIn("Group occupancy --", output.getvalue())
+ self.assertIn("Occupied slots by group -- (slot report incomplete)",
+ render_view({**sample, "work": incomplete}, "serving", 110, 30))
+
+ duplicated = dict(sample["work"])
+ duplicated["slots"] = [dict(row) for row in sample["work"]["slots"]]
+ duplicated["slots"][1]["slot"] = duplicated["slots"][0]["slot"]
+ output = io.StringIO()
+ Console(file=output, width=110, color_system=None).print(render_dashboard(
+ {**sample, "work": duplicated}, width=108, height=28, history=MonitorHistory(), color=False))
+ self.assertNotIn("Slot phases", output.getvalue())
+ self.assertIn("Group occupancy --", output.getvalue())
+
+ invalid_group = dict(sample["work"])
+ invalid_group["slots"] = [dict(row) for row in sample["work"]["slots"]]
+ invalid_group["slots"][1]["group"] = None
+ output = io.StringIO()
+ Console(file=output, width=110, color_system=None).print(render_dashboard(
+ {**sample, "work": invalid_group}, width=108, height=28, history=MonitorHistory(), color=False))
+ self.assertIn("Slot phases", output.getvalue())
+ self.assertIn("Group occupancy --", output.getvalue())
+
+ invalid_group["slots"][1]["group"] = 9
+ self.assertIn("Occupied slots by group -- (slot report incomplete)",
+ render_view({**sample, "work": invalid_group}, "serving", 110, 30))
+ invalid_group["slots"][1]["group"] = 0
+ invalid_group["slots"][1]["slot"] = 99
+ output = io.StringIO()
+ Console(file=output, width=110, color_system=None).print(render_dashboard(
+ {**sample, "work": invalid_group}, width=108, height=28, history=MonitorHistory(), color=False))
+ self.assertNotIn("Slot phases", output.getvalue())
+ self.assertIn("Group occupancy --", output.getvalue())
+
+ def test_connection_panel_hides_cached_work_until_recovery(self):
+ from rich.console import Console
+ from strata_cli.dashboard import MonitorHistory, render_dashboard
+
+ sample = four_gpu_snapshot()
+ sample["sampled_at"] = time.time() - 4
+ sample["rates"]["answer_tok_s"] = 42.5
+ sample["work"]["requests"] = [{"id": "cached-request", "state": "decoding", "slot": 0}]
+ expected = {"connecting": "CONNECTING", "disconnected": "CONNECTION LOST",
+ "auth_required": "AUTHORIZATION REQUIRED", "incompatible": "INCOMPATIBLE SERVER"}
+ for width, height in ((110, 30), (80, 24)):
+ for state, title in expected.items():
+ with self.subTest(width=width, state=state):
+ output = io.StringIO()
+ Console(file=output, width=width, color_system=None).print(render_dashboard(
+ sample, width=width - 2, height=height - 2, history=MonitorHistory(),
+ connection_state=state, color=False))
+ shown = output.getvalue()
+ self.assertIn(title, shown)
+ self.assertNotIn("cached-request", shown)
+ self.assertNotIn("42.5 tok/s", shown)
+ self.assertNotIn("GPU 0", shown)
+ self.assertLessEqual(len(shown.splitlines()), height - 1)
+ self.assertTrue(all(display_width(line) <= width for line in shown.splitlines()))
+
+ def test_compact_connection_panel_hides_cached_work_across_views(self):
+ sample = four_gpu_snapshot()
+ sample["sampled_at"] = time.time() - 4
+ sample["model"]["id"] = "cached-model"
+ sample["rates"]["answer_tok_s"] = 42.5
+ sample["work"]["requests"] = [{"id": "cached-request", "state": "decoding", "slot": 0}]
+ titles = {"connecting": "CONNECTING", "disconnected": "CONNECTION LOST",
+ "auth_required": "AUTHORIZATION REQUIRED", "incompatible": "INCOMPATIBLE SERVER"}
+ for width, height in ((80, 24), (60, 16), (40, 12)):
+ for view in ("overview", "serving", "requests", "engine", "hardware", "logs"):
+ for state, title in titles.items():
+ with self.subTest(width=width, view=view, state=state):
+ shown = render_view(sample, view, width, height, connection_state=state)
+ self.assertIn(title, shown)
+ for cached in ("cached-model", "cached-request", "42.5 tok/s", "GPU-0"):
+ self.assertNotIn(cached, shown)
+ self.assertLessEqual(len(shown.splitlines()), height)
+ self.assertTrue(all(display_width(line) <= width for line in shown.splitlines()))
+
+ def test_overview_dashboard_keeps_parallel_work_and_four_devices_on_one_screen(self):
+ from rich.console import Console
+ from strata_cli.dashboard import MonitorHistory, _spark, render_dashboard
+ from strata_cli.monitor import choose_glyphs
+
+ self.assertEqual(choose_glyphs("auto", "utf-8", "xterm-256color"), "unicode")
+ self.assertEqual(choose_glyphs("auto", "ascii", "xterm-256color"), "ascii")
+ self.assertEqual(choose_glyphs("auto", "utf-8", "dumb"), "ascii")
+ self.assertEqual(choose_glyphs("braille", "ascii", "dumb"), "braille")
+
+ sample = four_gpu_snapshot()
+ sample["sampled_at"] = time.time()
+ sample["instance"]["id"] = "fixture-instance"
+ sample["rates"].update(answer_tok_s=42.5, prefill_tok_s=180.0,
+ aggregate_output_tok_s=126.0)
+ sample["work"].update(effective_rows_window=5.0, batch_active_rows_window=3.0,
+ batch_sample_age_s=0.5,
+ requests=[{"id": "queued-1", "state": "queued", "slot": None,
+ "group": None, "queued_at": sample["sampled_at"] - 2},
+ {"id": "running-1", "state": "decoding", "slot": 0,
+ "group": 0, "generated": 18}])
+ sample["activity"] = {"available": True, "events": [
+ {"seq": 1, "at": sample["sampled_at"], "request_id": "running-1", "event": "admitted"}]}
+ history = MonitorHistory()
+ history.add(sample, ("id", "fixture-instance"))
+ for width, height in ((110, 30), (80, 24), (110, 42)):
+ with self.subTest(width=width):
+ output = io.StringIO()
+ Console(file=output, width=width, color_system=None).print(render_dashboard(
+ sample, width=width - 2, height=height - 2, history=history,
+ connection_state="connected", glyphs="ascii", color=False))
+ shown = output.getvalue()
+ self.assertLessEqual(len(shown.splitlines()), height - 1)
+ self.assertTrue(all(display_width(line) <= width for line in shown.splitlines()))
+ for expected in ("BATCHING / PARALLEL", "HARDWARE", "REQUESTS", "ACTIVITY",
+ "5.0", "queued-1", "GPU 0", "GPU 1", "GPU 2", "GPU 3",
+ "G0", "G3", "42.5 tok/s"):
+ self.assertIn(expected, shown)
+ if width == 110:
+ self.assertIn("Stage host span", shown)
+ if height == 42:
+ self.assertIn("SESSION", shown)
+ self.assertIn("ENGINE", shown)
+ if width == 80:
+ self.assertIn("1 Over", shown)
+ self.assertRegex(shown, r"queued-1[^\n]*wait")
+ self.assertNotRegex(shown, r"queued-1[^\n]*out")
+
+ history.add({"devices": [{"index": 0, "util": 90}]}, ("id", "restarted"))
+ self.assertEqual(list(history.device_util[0]), [90])
+ self.assertNotIn(1, history.device_util)
+ self.assertTrue(all("\u2800" <= char <= "\u28ff" for char in _spark([25, 75, 50, 100], "braille")))
+ self.assertEqual(_spark([None, None], "braille"), "--")
+ self.assertEqual(len(_spark([25, 75, 50, 100], "unicode")), 4)
+ sample["devices"][0]["name"] = "漢字 RTX 6000"
+ sample["work"]["requests"][0]["id"] = "\x1b[2J漢字-queued\u202e"
+ sample["work"]["slots"][0]["state"] = None
+ output = io.StringIO()
+ Console(file=output, width=80, color_system=None).print(render_dashboard(
+ sample, width=78, height=22, history=history, color=False))
+ self.assertIn("Group occupancy --", output.getvalue())
+ self.assertNotIn("\x1b", output.getvalue())
+ self.assertNotIn("\u202e", output.getvalue())
+ self.assertTrue(all(display_width(line) <= 80 for line in output.getvalue().splitlines()))
+
+ sample["work"]["requests"].append({"id": "reading-1", "state": "reading", "slot": 2,
+ "group": 1, "prompt_read": 250, "prompt_tokens": 1000})
+ output = io.StringIO()
+ Console(file=output, width=110, color_system=None).print(render_dashboard(
+ sample, width=108, height=28, history=history, glyphs="unicode", color=False))
+ self.assertIn("Reading reading-1", output.getvalue())
+ self.assertIn("250/1,000", output.getvalue())
+ self.assertTrue(all(display_width(line) <= 110 for line in output.getvalue().splitlines()))
+
+ sample["model"]["loaded"] = False
+ output = io.StringIO()
+ Console(file=output, width=110, color_system=None).print(render_dashboard(
+ sample, width=108, height=28, history=history, glyphs="unicode", color=False))
+ self.assertIn("SLEEPING", output.getvalue())
+ self.assertNotIn("42.5 tok/s", output.getvalue())
+
+ def test_wide_visual_overview_uses_real_rates_slots_and_request_rows(self):
+ from rich.console import Console
+ from strata_cli.dashboard import MonitorHistory, render_dashboard
+
+ sample = four_gpu_snapshot()
+ sample["sampled_at"] = time.time()
+ sample["model"]["context"] = 32768
+ sample["rates"].update(answer_tok_s=41.8, prefill_tok_s=188.6,
+ aggregate_output_tok_s=119.4)
+ sample["work"].update(slots_effective=8, queued=2, effective_rows_window=4.0,
+ batch_active_rows_window=3.0, batch_sample_age_s=0.5,
+ requests=[{"id": "queue-a", "state": "queued", "slot": None,
+ "prompt_tokens": 500, "queued_at": sample["sampled_at"] - 2},
+ {"id": "decode-b", "state": "decoding", "slot": 0,
+ "group": 0, "prompt_tokens": 200, "generated": 37,
+ "first_engine_token_s": 0.71}])
+ sample["work"]["slots"][0]["held_tokens"] = 1200
+ history = MonitorHistory()
+ history.add(sample, ("id", "visual-fixture"))
+ history.add(sample, ("id", "visual-fixture"))
+ for width, height in ((140, 44), (128, 36)):
+ with self.subTest(width=width, height=height):
+ output = io.StringIO()
+ Console(file=output, width=width, color_system=None).print(render_dashboard(
+ sample, width=width - 2, height=height - 2, history=history,
+ connection_state="connected", glyphs="ascii", color=False))
+ shown = output.getvalue()
+ self.assertLessEqual(len(shown.splitlines()), height - 1)
+ self.assertTrue(all(display_width(line) <= width for line in shown.splitlines()))
+ for expected in ("THROUGHPUT", "PROMPT 188.6 tok/s", "119.4 tok/s",
+ "GPUS", "GPU 0", "GPU 3", "CONTEXT / BATCHING",
+ "MAX ACTIVE HELD 1,200", "PARALLEL SLOTS", "G0",
+ "REQUESTS", "queue-a", "decode-b", "wait 2.0s",
+ "1ST ENGINE"):
+ self.assertIn(expected, shown)
+ self.assertNotIn("cached 0", shown)
+ history.gap()
+ self.assertIsNone(history.prefill_rate[-1])
+ self.assertIsNone(history.answer_rate[-1])
+ stale_output = io.StringIO()
+ Console(file=stale_output, width=140, color_system=None).print(render_dashboard(
+ sample, width=138, height=42, history=history,
+ connection_state="stale", glyphs="ascii", color=False))
+ self.assertIn("MAX ACTIVE HELD --", stale_output.getvalue())
+ self.assertIn("PROMPT -- tok/s", stale_output.getvalue())
+ self.assertNotIn("119.4 tok/s", stale_output.getvalue())
+ idle = copy.deepcopy(sample)
+ idle["work"].update(active=0, queued=0, waiting=0, occupied_slots=0, requests=[])
+ for slot in idle["work"]["slots"]:
+ slot["state"] = "idle"
+ idle_output = io.StringIO()
+ Console(file=idle_output, width=140, color_system=None).print(render_dashboard(
+ idle, width=138, height=42, history=history,
+ connection_state="connected", glyphs="ascii", color=False))
+ self.assertIn("MAX ACTIVE HELD 0", idle_output.getvalue())
+ self.assertIn("No active requests", idle_output.getvalue())
+
+ def test_initial_attach_keeps_status_when_telemetry_is_unavailable(self):
+ status_only = sanitize_telemetry(normalize_status_only(
+ {"service": "strata", "model": "fixture", "loaded": False,
+ "concurrency": {"serving": 4}}))
+
+ class Source:
+ root = "http://127.0.0.1:8095"
+
+ def snapshot(self):
+ return status_only
+
+ async def exercise():
+ app = MonitorApp(Source(), None, interval=30)
+ async with app.run_test(size=(80, 24)) as pilot:
+ await pilot.pause(0.1)
+ self.assertEqual(app.connection_state, "telemetry_unavailable")
+ self.assertTrue(app.has_snapshot)
+ self.assertEqual(app.displayed["model"]["id"], "fixture")
+ from rich.console import Console
+ output = io.StringIO()
+ console = Console(file=output, width=80, color_system=None)
+ console.print(app.query_one("#content").content)
+ self.assertIn("Telemetry unavailable; status only", output.getvalue())
+ self.assertIn("NO MODEL LOADED", output.getvalue())
+ await pilot.press("q")
+ asyncio.run(exercise())
+
+ def test_stale_snapshot_hides_live_rates_without_changing_cached_values(self):
+ sample = four_gpu_snapshot()
+ sample["sampled_at"] = time.time()
+ sample["rates"].update(answer_tok_s=12, prefill_tok_s=24, aggregate_output_tok_s=36)
+ live = render_view(sample, "overview", 80, 24, connection_state="connected")
+ stale = render_view(sample, "overview", 80, 24, connection_state="stale")
+ serving = render_view(sample, "serving", 110, 30, connection_state="stale")
+ self.assertIn("[LIVE]", live)
+ self.assertIn("Answer speed 12.0 tok/s", live)
+ self.assertIn("[STALE]", stale)
+ self.assertIn("Answer speed --", stale)
+ self.assertIn("Prompt reading --", stale)
+ self.assertIn("Total output --", serving)
+ self.assertEqual(sample["rates"]["answer_tok_s"], 12)
+ self.assertIn("[STALE]", render_view({**sample, "sampled_at": time.time() - 10},
+ "overview", 80, 24, connection_state="connected"))
+
+ def test_failed_poll_marks_stale_immediately_then_recovers(self):
+ initial = four_gpu_snapshot()
+ initial["sampled_at"] = time.time()
+ initial["rates"]["answer_tok_s"] = 12
+ initial["rates"]["output_tokens_server_counter"] = 100
+ initial["instance"]["id"] = "same-instance"
+ sample_time = initial["sampled_at"]
+
+ class Source:
+ root = "http://127.0.0.1:8095"
+ calls = 0
+
+ def snapshot(self):
+ self.calls += 1
+ if self.calls <= 3:
+ raise ClientError("temporarily unavailable", 3)
+ result = four_gpu_snapshot()
+ result["instance"]["id"] = "same-instance"
+ result["sampled_at"] = sample_time + self.calls - 4
+ result["rates"]["output_tokens_server_counter"] = 160 + 30 * (self.calls - 4)
+ return result
+
+ async def exercise():
+ from rich.console import Console
+
+ source = Source()
+ app = MonitorApp(source, initial, interval=30)
+ async with app.run_test(size=(80, 24)) as pilot:
+ for expected in ("stale", "stale", "disconnected", "connected"):
+ app._schedule_poll(force=True)
+ await pilot.pause(0.1)
+ self.assertEqual(app.connection_state, expected)
+ output = io.StringIO()
+ Console(file=output, width=80, color_system=None).print(app.query_one("#content").content)
+ if expected == "disconnected":
+ self.assertIn("CONNECTION LOST", output.getvalue())
+ self.assertNotIn("GPU 0", output.getvalue())
+ if expected in ("stale", "disconnected"):
+ self.assertIsNone(app.history.batch_rows[-1])
+ self.assertIsNone(app.history.pre_admit[-1])
+ self.assertIsNone(app.history.device_util[0][-1])
+ if expected == "connected":
+ self.assertIn("GPU 0", output.getvalue())
+ self.assertNotIn("CONNECTION LOST", output.getvalue())
+ self.assertEqual(source.calls, 4)
+ self.assertEqual(app.failures, 0)
+ self.assertIsNone(app.latest["rates"]["aggregate_output_tok_s"])
+ app._schedule_poll(force=True)
+ await pilot.pause(0.1)
+ self.assertEqual(app.latest["rates"]["aggregate_output_tok_s"], 30)
+ await pilot.press("q")
+ asyncio.run(exercise())
+
+ def test_unexpected_poll_error_marks_snapshot_stale_without_leaking_details(self):
+ initial = four_gpu_snapshot()
+ initial["sampled_at"] = time.time()
+
+ class Source:
+ root = "http://127.0.0.1:8095"
+
+ def snapshot(self):
+ raise RuntimeError("private URL and credential")
+
+ async def exercise():
+ app = MonitorApp(Source(), initial, interval=30)
+ async with app.run_test(size=(80, 24)) as pilot:
+ app._schedule_poll(force=True)
+ await pilot.pause(0.1)
+ self.assertEqual(app.connection_state, "stale")
+ self.assertEqual(app.error, "Telemetry collection failed")
+ self.assertIsNone(app.rate_previous)
+ self.assertNotIn("private URL", str(app.query_one("#message").render()))
+ await pilot.press("q")
+ asyncio.run(exercise())
+
+ def test_initial_attach_shows_connecting_and_requires_manual_retry_after_auth(self):
+ class Source:
+ root = "http://127.0.0.1:8095"
+ calls = 0
+
+ def snapshot(self):
+ self.calls += 1
+ if self.calls == 1:
+ raise ClientError("credential required", 4)
+ if self.calls == 2:
+ raise ClientError("unsupported telemetry schema", 5)
+ result = four_gpu_snapshot()
+ result["sampled_at"] = time.time()
+ return result
+
+ async def exercise():
+ source = Source()
+ app = MonitorApp(source, None, interval=30)
+ self.assertEqual(app.connection_state, "connecting")
+ async with app.run_test(size=(80, 24)) as pilot:
+ await pilot.pause(0.1)
+ self.assertEqual(app.connection_state, "auth_required")
+ self.assertEqual(app.next_poll_at, float("inf"))
+ self.assertFalse(app.has_snapshot)
+ app._schedule_poll()
+ await pilot.pause(0.1)
+ self.assertEqual(source.calls, 1)
+ app._schedule_poll(force=True)
+ await pilot.pause(0.1)
+ self.assertEqual(app.connection_state, "incompatible")
+ self.assertEqual(app.next_poll_at, float("inf"))
+ app._schedule_poll(force=True)
+ await pilot.pause(0.1)
+ self.assertEqual(app.connection_state, "connected")
+ self.assertTrue(app.has_snapshot)
+ self.assertIsNone(app.selection_notice)
+ await pilot.press("q")
+ asyncio.run(exercise())
+
+ def test_restart_clears_matching_request_id_after_freeze(self):
+ initial = four_gpu_snapshot()
+ initial["instance"]["id"] = "server-old"
+ initial["work"]["requests"] = [{"id": "reused-id", "state": "decoding"}]
+ initial["recent"] = []
+ restarted = four_gpu_snapshot()
+ restarted["instance"]["id"] = "server-new"
+ restarted["work"]["requests"] = [{"id": "reused-id", "state": "queued"}]
+ restarted["recent"] = []
+
+ class Source:
+ root = "http://127.0.0.1:8095"
+
+ def snapshot(self):
+ return restarted
+
+ async def exercise():
+ app = MonitorApp(Source(), initial, interval=30)
+ async with app.run_test(size=(80, 24)) as pilot:
+ await pilot.press("3", "enter", "space")
+ self.assertTrue(app.detail)
+ app._schedule_poll(force=True)
+ await pilot.pause(0.1)
+ self.assertEqual(app.displayed["instance"]["id"], "server-old")
+ self.assertTrue(app.detail)
+ await pilot.press("space")
+ self.assertEqual(app.displayed["instance"]["id"], "server-new")
+ self.assertFalse(app.detail)
+ self.assertIsNone(app.selected_identity)
+ self.assertEqual(app.selection_notice, "Server instance changed; selection cleared")
+ await pilot.press("q")
+ asyncio.run(exercise())
+
+ def test_table_keys_and_device_identity_survive_reorder(self):
+ initial = four_gpu_snapshot()
+ initial["work"]["requests"] = [{"id": f"r{i:02d}", "state": "queued"} for i in range(20)]
+ initial["recent"] = []
+ reordered = four_gpu_snapshot()
+ reordered["devices"].reverse()
+ disappeared = four_gpu_snapshot()
+ disappeared["devices"] = disappeared["devices"][:3]
+
+ class Source:
+ root = "http://127.0.0.1:8095"
+
+ def __init__(self):
+ self.values = [reordered, disappeared]
+
+ def snapshot(self):
+ return self.values.pop(0)
+
+ async def exercise():
+ app = MonitorApp(Source(), initial, interval=30, requests=20)
+ async with app.run_test(size=(80, 24)) as pilot:
+ await pilot.press("3", "end")
+ self.assertEqual(app.selected, 19)
+ await pilot.press("pageup")
+ self.assertEqual(app.selected, 7)
+ await pilot.press("home", "pagedown")
+ self.assertEqual(app.selected, 12)
+ await pilot.press("right")
+ self.assertEqual(app.view, 3)
+ await pilot.press("left", "5", "end", "enter")
+ self.assertEqual(app.selected_identity, ("device", "3"))
+ self.assertTrue(app.detail)
+ app._schedule_poll(force=True)
+ await pilot.pause(0.1)
+ self.assertEqual(app.selected, 0)
+ self.assertTrue(app.detail)
+ self.assertIn("GPU 3", str(app.query_one("#content").render()))
+ app._schedule_poll(force=True)
+ await pilot.pause(0.1)
+ self.assertFalse(app.detail)
+ self.assertEqual(app.selection_notice, "No longer retained; select another row")
+ await pilot.press("q")
+ asyncio.run(exercise())
+
+ def test_slot_detail_follows_slot_across_snapshot_reorder(self):
+ initial = four_gpu_snapshot()
+ reordered = four_gpu_snapshot()
+ reordered["work"]["slots"].reverse()
+
+ class Source:
+ root = "http://127.0.0.1:8095"
+
+ def snapshot(self):
+ return reordered
+
+ async def exercise():
+ app = MonitorApp(Source(), initial, interval=30)
+ async with app.run_test(size=(80, 24)) as pilot:
+ await pilot.press("2", "tab", "tab", "end", "enter")
+ self.assertEqual(app.selected_identity, ("slot", "7"))
+ self.assertTrue(app.detail)
+ app._schedule_poll(force=True)
+ await pilot.pause(0.1)
+ self.assertEqual(app.selected, 0)
+ self.assertTrue(app.detail)
+ self.assertIn("Slot 7", str(app.query_one("#content").render()))
+ await pilot.press("q")
+ asyncio.run(exercise())
+
+ def test_request_detail_follows_live_request_into_recent_history(self):
+ value = four_gpu_snapshot()
+ value["work"]["requests"] = [{"id": "finishing-1", "state": "decoding"}]
+ value["recent"] = []
+ finished = four_gpu_snapshot()
+ finished["work"]["requests"] = []
+ finished["recent"] = [{"id": "finishing-1", "finish": "stop", "output_tokens": 9}]
+
+ class Source:
+ root = "http://127.0.0.1:8095"
+
+ def snapshot(self):
+ return finished
+
+ async def exercise():
+ app = MonitorApp(Source(), value, interval=30)
+ async with app.run_test(size=(80, 24)) as pilot:
+ await pilot.press("3", "enter")
+ self.assertEqual(app.selected_identity, ("live", "finishing-1"))
+ app._schedule_poll(force=True)
+ await pilot.pause(0.1)
+ self.assertEqual(app.selected_identity, ("recent", "finishing-1"))
+ self.assertTrue(app.detail)
+ self.assertIn("RECENT REQUEST DETAIL", str(app.query_one("#content").render()))
+ await pilot.press("q")
+ asyncio.run(exercise())
+
+ def test_recent_detail_follows_identity_and_closes_when_it_disappears(self):
+ def snapshot(recent_ids):
+ value = four_gpu_snapshot()
+ value["work"]["requests"] = [{"id": "live-1", "state": "decoding"}]
+ value["recent"] = [{"id": item, "finish": "stop", "prompt_tokens": 100,
+ "output_tokens": 2, "duration_s": 0.5,
+ "first_engine_token_s": 0.2} for item in recent_ids]
+ value["sampled_at"] = time.time()
+ return value
+
+ class Source:
+ root = "http://127.0.0.1:8095"
+
+ def __init__(self):
+ self.values = [snapshot(["new-1", "done-1"]), snapshot(["new-1"])]
+
+ def snapshot(self):
+ return self.values.pop(0)
+
+ async def exercise():
+ app = MonitorApp(Source(), snapshot(["done-1"]), interval=30)
+ async with app.run_test(size=(80, 24)) as pilot:
+ await pilot.press("3", "down", "enter")
+ await pilot.pause()
+ self.assertTrue(app.detail)
+ self.assertEqual(app.selected_identity, ("recent", "done-1"))
+ self.assertIn("RECENT REQUEST DETAIL", str(app.query_one("#content").render()))
+ app._schedule_poll(force=True)
+ await pilot.pause(0.1)
+ self.assertEqual(app.selected, 2)
+ self.assertTrue(app.detail)
+ self.assertIn("done-1", str(app.query_one("#content").render()))
+ app._schedule_poll(force=True)
+ await pilot.pause(0.1)
+ self.assertFalse(app.detail)
+ self.assertEqual(app.selection_notice, "No longer retained; select another row")
+ await pilot.press("q")
+ asyncio.run(exercise())
+
+ def test_polling_has_one_in_flight_cycle_and_freeze_keeps_display(self):
+ class Source:
+ root = "http://127.0.0.1:8095"
+ calls = 0
+
+ def snapshot(self):
+ self.calls += 1
+ time.sleep(0.1)
+ result = four_gpu_snapshot()
+ result["sampled_at"] = time.time()
+ return result
+
+ async def exercise():
+ source = Source()
+ initial = four_gpu_snapshot()
+ app = MonitorApp(source, initial, interval=30)
+ async with app.run_test(size=(80, 24)) as pilot:
+ app.action_freeze()
+ app._schedule_poll(force=True)
+ app._schedule_poll(force=True)
+ await pilot.pause(0.2)
+ self.assertEqual(source.calls, 1)
+ self.assertIs(app.displayed, initial)
+ app.action_freeze()
+ self.assertIs(app.displayed, app.latest)
+ await pilot.press("q")
+ asyncio.run(exercise())
+
+ def test_aggregate_rate_uses_one_window_and_resets_on_restart(self):
+ old = {"instance": {"id": "one"}, "sampled_at": 10.0,
+ "rates": {"output_tokens_server_counter": 100}}
+ fresh = {"instance": {"id": "one"}, "sampled_at": 12.0,
+ "rates": {"output_tokens_server_counter": 160}}
+ self.assertEqual(with_aggregate_rate(old, fresh)["rates"]["aggregate_output_tok_s"], 30)
+ restarted = {"instance": {"id": "two"}, "sampled_at": 14.0,
+ "rates": {"output_tokens_server_counter": 3}}
+ self.assertIsNone(with_aggregate_rate(fresh, restarted)["rates"]["aggregate_output_tok_s"])
+ invalid = {"instance": {"id": "one"}, "sampled_at": float("inf"),
+ "rates": {"output_tokens_server_counter": 190}}
+ self.assertIsNone(with_aggregate_rate(fresh, invalid)["rates"]["aggregate_output_tok_s"])
+ stale = {"instance": {"id": "one"}, "sampled_at": time.time() - 10,
+ "rates": {"output_tokens_server_counter": 100}}
+ self.assertIsNone(MonitorApp(Endpoint("http://127.0.0.1:8080"), stale).rate_previous)
+
+ def test_navigation_freeze_and_quit_at_supported_sizes(self):
+ async def exercise(size):
+ endpoint = Endpoint("http://127.0.0.1:18765")
+ app = MonitorApp(endpoint, four_gpu_snapshot(), interval=30)
+ async with app.run_test(size=size) as pilot:
+ await pilot.press("2")
+ await pilot.pause()
+ self.assertEqual(app.view, 1)
+ await pilot.press("tab")
+ await pilot.pause()
+ self.assertEqual(app.serving_pane, "requests")
+ await pilot.press("enter")
+ await pilot.pause()
+ self.assertFalse(app.detail) # fixture has no correlated request rows
+ await pilot.press("space")
+ await pilot.pause()
+ self.assertTrue(app.frozen)
+ await pilot.press("space")
+ await pilot.pause()
+ self.assertFalse(app.frozen)
+ await pilot.press("q")
+ for size in ((110, 30), (80, 24), (60, 16), (40, 12)):
+ asyncio.run(exercise(size))
+
+ def test_resize_keeps_selected_request_visible_in_tiny_serving_view(self):
+ async def exercise():
+ snapshot = four_gpu_snapshot()
+ snapshot["work"]["requests"] = [
+ {"id": "selected-1", "state": "reading", "slot": 0,
+ "group": 0, "prompt_read": 8, "prompt_tokens": 64}]
+ app = MonitorApp(Endpoint("http://127.0.0.1:18765"), snapshot, interval=30)
+ async with app.run_test(size=(110, 30)) as pilot:
+ await pilot.press("2", "tab", "enter")
+ await pilot.pause()
+ self.assertTrue(app.detail)
+ identity = app.selected_identity
+ for width, height in ((80, 24), (60, 16), (40, 12), (110, 30)):
+ await pilot.resize_terminal(width, height)
+ content = str(app.query_one("#content").render())
+ self.assertEqual((app.screen.size.width, app.screen.size.height),
+ (width, height))
+ self.assertIn("selected-1", content)
+ self.assertEqual(app.selected_identity, identity)
+ self.assertTrue(app.detail)
+ if (width, height) == (40, 12):
+ self.assertIn("More: strata status --json", content)
+ self.assertIn("q keeps server on", str(app.query_one("#message").render()))
+ elif (width, height) == (110, 30):
+ self.assertNotIn("More: strata status --json", content)
+ await pilot.press("q")
+ asyncio.run(exercise())
+
+ def test_request_detail_key_is_read_only(self):
+ async def exercise():
+ snapshot = four_gpu_snapshot()
+ snapshot["work"]["requests"] = [{"id": "r1", "state": "reading", "slot": 0,
+ "group": 0, "prompt_read": 8, "prompt_tokens": 64}]
+ endpoint = Endpoint("http://127.0.0.1:18765")
+ app = MonitorApp(endpoint, snapshot, interval=30)
+ async with app.run_test(size=(80, 24)) as pilot:
+ await pilot.press("2", "tab", "enter")
+ await pilot.pause()
+ self.assertTrue(app.detail)
+ self.assertIn("REQUEST DETAIL", str(app.query_one("#content").render()))
+ await pilot.press("enter")
+ await pilot.pause()
+ self.assertFalse(app.detail)
+ await pilot.press("q")
+ asyncio.run(exercise())
+
+ def test_filter_paste_is_bounded_clean_and_keeps_keyboard_focus(self):
+ from textual.events import Paste
+ from textual.widgets import Input
+
+ async def exercise():
+ snapshot = four_gpu_snapshot()
+ snapshot["work"]["requests"] = [{"id": "r01", "state": "reading"},
+ {"id": "r02", "state": "queued"}]
+ app = MonitorApp(Endpoint("http://127.0.0.1:18765"), snapshot, interval=30)
+ async with app.run_test(size=(80, 24)) as pilot:
+ await pilot.press("3", "slash")
+ field = app.query_one("#filter", Input)
+ self.assertIs(app.focused, field)
+ field.post_message(Paste("x" * 1024 + "\u202e"))
+ await pilot.pause()
+ self.assertLessEqual(len(field.value), 80)
+ self.assertNotIn("\u202e", field.value)
+ await pilot.press("q")
+ self.assertFalse(app.closing)
+ field.value = ""
+ field.post_message(Paste("\u202er01"))
+ await pilot.pause()
+ self.assertEqual(field.value, "r01")
+ await pilot.press("enter")
+ self.assertEqual(app.filter_text, "r01")
+ self.assertIsNone(app.focused)
+ shown = str(app.query_one("#content").render())
+ self.assertIn("r01", shown)
+ self.assertNotIn("r02", shown)
+ await pilot.press("q")
+ self.assertTrue(app.closing)
+ asyncio.run(exercise())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/terminal/test_visual_detail.py b/tests/terminal/test_visual_detail.py
new file mode 100644
index 000000000..0e6195baf
--- /dev/null
+++ b/tests/terminal/test_visual_detail.py
@@ -0,0 +1,117 @@
+"""Wide monitor pages preserve readable telemetry and redacted request data."""
+
+import io
+import time
+import unittest
+
+try:
+ from rich.console import Console
+ from strata_cli.dashboard import MonitorHistory
+ from strata_cli.detail_dashboard import render_detail_dashboard
+except ImportError:
+ Console = None
+
+
+def snapshot():
+ now = time.time()
+ slots = [{"slot": i, "group": i // 2, "state": "decoding" if i < 3 else "idle",
+ "request_id": f"req-{i}" if i < 3 else None,
+ "held_tokens": 1500 + 100 * i if i < 3 else 0,
+ "tok_s": 12.0 + i if i < 3 else None} for i in range(4)]
+ return {
+ "sampled_at": now, "source": "test", "instance": {"id": "test", "state": "ready"},
+ "model": {"id": "test-model", "loaded": True, "context": 8192},
+ "work": {"active": 3, "occupied_slots": 3, "slots_effective": 4,
+ "slots_requested": 4, "groups": 2, "queued": 1, "waiting": 0,
+ "max_queue": 8, "admission_limit": 12, "admission_reserved": 4,
+ "batch_sample_age_s": 0.2, "effective_rows_window": 3.0,
+ "batch_active_rows_window": 3.0, "slots": slots,
+ "requests": [{"id": f"req-{i}", "state": "decoding", "slot": i,
+ "group": i // 2, "prompt_tokens": 400,
+ "generated": 60 + i, "queued_at": now - 2,
+ "admitted_at": now - 1.5,
+ "first_engine_token_s": 0.8,
+ "prompt_body": "SECRET_PROMPT"} for i in range(3)] +
+ [{"id": "wait-0", "state": "queued", "slot": None,
+ "prompt_tokens": 500, "queued_at": now - 1}]},
+ "rates": {"aggregate_output_tok_s": 41.0, "answer_tok_s": 13.5,
+ "prefill_tok_s": 120.0},
+ "topology": {"mode": "layer split", "resolved": True,
+ "selected_devices": [0, 1],
+ "stages": [{"stage": i, "device_index": i,
+ "layer_start": 10 * i, "layer_end": 10 * i + 9}
+ for i in range(2)]},
+ "devices": [{"index": i, "name": f"GPU-{i}", "util": 70 + i,
+ "mem_used": (10 + i) * 2**30, "mem_total": 24 * 2**30,
+ "temp": 60 + i, "power": 180 + i} for i in range(2)],
+ "ram": {"used": 20 * 2**30, "total": 64 * 2**30},
+ "recent": [{"id": "done-0", "finish": "stop", "prompt_tokens": 100,
+ "reused": 20, "output_tokens": 40, "duration_s": 3.2,
+ "first_engine_token_s": 0.7}],
+ "activity": {"available": True, "last_seq": 2,
+ "events": [{"seq": 1, "at": now - 2, "request_id": "req-0",
+ "event": "queued"},
+ {"seq": 2, "at": now - 1, "request_id": "req-0",
+ "event": "admitted"}]},
+ }
+
+
[email protected](Console is None, "optional Rich dependency absent")
+class VisualDetailTests(unittest.TestCase):
+ def render(self, sample, view, width=140, height=44, **options):
+ output = io.StringIO()
+ history = MonitorHistory()
+ history.add(sample, ("id", "test"))
+ Console(file=output, width=width - 2, color_system=None).print(
+ render_detail_dashboard(sample, view, width=width - 2,
+ height=height - 2, history=history,
+ color=False, **options))
+ return output.getvalue()
+
+ def test_all_five_pages_fit_wide_terminals_and_keep_request_text_private(self):
+ sample = snapshot()
+ for width, height in ((140, 44), (128, 36)):
+ for view in ("serving", "requests", "engine", "hardware", "logs"):
+ with self.subTest(width=width, view=view):
+ shown = self.render(sample, view, width, height)
+ self.assertIn(f"STRATA / {view.upper()}", shown)
+ self.assertNotIn("SECRET_PROMPT", shown)
+ self.assertLessEqual(len(shown.splitlines()), height - 2)
+ self.assertTrue(all(len(line) <= width - 2 for line in shown.splitlines()))
+ self.assertIn("ROWS/WINDOW", self.render(sample, "serving"))
+ self.assertIn("GPU 0", self.render(sample, "hardware"))
+ self.assertIn("HOST SPAN", self.render(sample, "engine"))
+ self.assertIn("req-0", self.render(sample, "logs"))
+
+ def test_selection_detail_and_stale_readings(self):
+ sample = snapshot()
+ summary = self.render(sample, "requests", selected=0)
+ expanded = self.render(sample, "requests", selected=0, detail=True)
+ self.assertIn("Enter expands", summary)
+ self.assertIn("First engine token", expanded)
+ self.assertNotIn("First engine token", summary)
+ stale = self.render(sample, "serving", connection_state="stale")
+ self.assertIn("STALE", stale)
+ self.assertNotIn("41.0 tok/s", stale)
+ stale_hardware = self.render(sample, "hardware", connection_state="stale")
+ self.assertNotIn("70%", stale_hardware)
+ self.assertIn("--/--G", stale_hardware)
+
+ def test_replica_batch_windows_remain_separate(self):
+ sample = snapshot()
+ sample["topology"]["mode"] = "replicas (configured)"
+ sample["work"]["effective_rows_window"] = None
+ sample["work"]["replica_batches"] = [
+ {"replica": 0, "effective_rows_window": 2.0,
+ "batch_active_rows_window": 1.5, "batch_sample_age_s": 0.2},
+ {"replica": 1, "effective_rows_window": 3.0,
+ "batch_active_rows_window": 2.0, "batch_sample_age_s": 0.3},
+ ]
+ shown = self.render(sample, "serving")
+ self.assertIn("R0 ROWS/WIN", shown)
+ self.assertIn("R1 ROWS/WIN", shown)
+ self.assertIn("Replica sample windows are independent", shown)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/tuning/test_components.py b/tests/tuning/test_components.py
new file mode 100644
index 000000000..1ab2d98d2
--- /dev/null
+++ b/tests/tuning/test_components.py
@@ -0,0 +1,497 @@
+"""Component store tests (checklist P06, P07, P11, P12, P13).
+
+The security tests here use the actual attack shapes rather than a generic "bad path", because the
+failure this guards against is arbitrary file writes from a hostile archive, and each shape defeats a
+different naive check:
+
+* ``../`` escapes a destination that only joins paths;
+* a leading ``/`` defeats a check that only looks for ``..``;
+* a Windows drive letter defeats a POSIX-only check on a Windows host;
+* a backslash separator defeats a check that only splits on ``/``;
+* a symlink pointing outside defeats every name-based check, because the *name* is innocent.
+
+Every refusal is asserted to leave the destination directory **empty**: checking after extraction
+would be too late.
+"""
+
+from __future__ import annotations
+
+import io
+import json
+import os
+import stat
+import sys
+import tarfile
+import tempfile
+import unittest
+import zipfile
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from strata_control import components as C # noqa: E402
+
+
+def manifest(**over) -> dict:
+ base = {
+ "schema_version": 1,
+ "id": "strata-engine",
+ "version": "0.1.44.1",
+ "kind": "engine",
+ "backend": "metal",
+ "platforms": ["macos-arm64"],
+ "artifacts": [{"name": "engine.tar.gz", "url": "https://example.invalid/e.tar.gz",
+ "sha256": "a" * 64, "bytes": 1024, "format": "tar.gz"}],
+ "license": "proprietary",
+ }
+ base.update(over)
+ return base
+
+
+def tar_bytes(entries: list[tuple[str, bytes]], *, links: list[tuple[str, str]] | None = None,
+ devices: bool = False) -> bytes:
+ buffer = io.BytesIO()
+ with tarfile.open(fileobj=buffer, mode="w:gz") as tar:
+ for name, payload in entries:
+ info = tarfile.TarInfo(name)
+ info.size = len(payload)
+ info.mode = 0o644
+ tar.addfile(info, io.BytesIO(payload))
+ for name, target in (links or []):
+ info = tarfile.TarInfo(name)
+ info.type = tarfile.SYMTYPE
+ info.linkname = target
+ tar.addfile(info)
+ if devices:
+ info = tarfile.TarInfo("dev/null")
+ info.type = tarfile.CHRTYPE
+ info.devmajor, info.devminor = 1, 3
+ tar.addfile(info)
+ return buffer.getvalue()
+
+
+class StoreCase(unittest.TestCase):
+ def setUp(self):
+ self.tmp = Path(tempfile.mkdtemp(prefix="strata-components-"))
+ self.store = C.ComponentStore(self.tmp / "store")
+
+ def tearDown(self):
+ import shutil
+ shutil.rmtree(self.tmp, ignore_errors=True)
+
+ def payload(self, data: bytes, name: str = "engine.tar.gz") -> tuple[C.Component, dict]:
+ import hashlib
+ man = manifest(artifacts=[{"name": name, "url": None,
+ "sha256": hashlib.sha256(data).hexdigest(),
+ "bytes": len(data), "format": "tar.gz"}])
+ return C.parse_manifest(man), {name: data}
+
+
+class TestManifestParsing(StoreCase):
+ def test_a_valid_manifest_parses(self):
+ c = C.parse_manifest(manifest())
+ self.assertEqual(c.id, "strata-engine")
+ self.assertEqual(c.backend, "metal")
+ self.assertEqual(len(c.artifacts), 1)
+
+ def test_a_manifest_without_a_digest_is_refused(self):
+ bad = manifest(artifacts=[{"name": "e.tar.gz", "sha256": "", "bytes": 10}])
+ with self.assertRaises(C.ComponentError) as ctx:
+ C.parse_manifest(bad)
+ self.assertIn("sha256", str(ctx.exception))
+
+ def test_a_short_or_non_hex_digest_is_refused(self):
+ for digest in ("abc", "z" * 64, "A" * 63):
+ with self.assertRaises(C.ComponentError):
+ C.parse_manifest(manifest(artifacts=[{"name": "e", "sha256": digest, "bytes": 1}]))
+
+ def test_an_unknown_kind_is_refused(self):
+ with self.assertRaises(C.ComponentError) as ctx:
+ C.parse_manifest(manifest(kind="kernel"))
+ self.assertIn("unknown component kind", str(ctx.exception))
+
+ def test_a_manifest_that_does_not_state_its_platforms_is_refused(self):
+ """An unstated platform would be read as every platform, which is the unsafe default."""
+ bad = manifest()
+ bad.pop("platforms")
+ with self.assertRaises(C.ComponentError) as ctx:
+ C.parse_manifest(bad)
+ self.assertIn("which platforms", str(ctx.exception))
+
+ def test_an_artifact_name_that_is_a_path_is_refused(self):
+ for name in ("../../etc/passwd", "sub/dir", "..", "a\\b"):
+ with self.assertRaises(C.ComponentError):
+ C.parse_manifest(manifest(artifacts=[
+ {"name": name, "sha256": "a" * 64, "bytes": 1}]))
+
+ def test_an_unknown_schema_version_is_refused(self):
+ with self.assertRaises(C.ComponentError) as ctx:
+ C.parse_manifest(manifest(schema_version=99))
+ self.assertIn("schema_version", str(ctx.exception))
+
+ def test_malformed_json_is_refused_with_the_parse_error(self):
+ with self.assertRaises(C.ComponentError) as ctx:
+ C.parse_manifest("{not json")
+ self.assertIn("not valid JSON", str(ctx.exception))
+
+ def test_the_cache_key_is_the_bytes_not_the_version_label(self):
+ """A rebuilt artifact with the same version must be a different key."""
+ a = C.parse_manifest(manifest())
+ b = C.parse_manifest(manifest(artifacts=[{"name": "engine.tar.gz", "url": None,
+ "sha256": "b" * 64, "bytes": 1024}]))
+ self.assertEqual(a.version, b.version, "the label is the same")
+ self.assertNotEqual(a.cache_key, b.cache_key, "the bytes differ, so the key must differ")
+
+
+class TestCompatibility(StoreCase):
+ def test_a_component_for_this_platform_is_compatible(self):
+ self.assertEqual(C.check_compatible(C.parse_manifest(manifest()), target="macos-arm64"), [])
+
+ def test_another_platform_is_refused_with_both_named(self):
+ reasons = C.check_compatible(C.parse_manifest(manifest()), target="linux-x86_64")
+ self.assertTrue(reasons)
+ self.assertIn("macos-arm64", reasons[0])
+ self.assertIn("linux-x86_64", reasons[0])
+
+ def test_a_backend_that_is_not_committed_to_on_a_platform_is_refused(self):
+ """Windows SYCL and Intel Macs are explicitly not supported, not merely untested."""
+ ok, why = C.backend_supported("sycl", "windows-x86_64")
+ self.assertFalse(ok)
+ self.assertIn("not a supported combination", why)
+ ok, why = C.backend_supported("metal", "macos-x86_64")
+ self.assertFalse(ok, "Intel Macs are excluded from local Metal support")
+ self.assertTrue(C.backend_supported("metal", "macos-arm64")[0])
+ self.assertTrue(C.backend_supported("cuda", "linux-x86_64")[0])
+ self.assertTrue(C.backend_supported("sycl", "linux-x86_64")[0])
+
+ def test_an_unknown_backend_is_refused(self):
+ ok, why = C.backend_supported("vulkan", "linux-x86_64")
+ self.assertFalse(ok)
+ self.assertIn("unknown backend family", why)
+
+ def test_a_component_for_another_backend_is_refused(self):
+ c = C.parse_manifest(manifest(backend="metal", platforms=["macos-arm64"]))
+ reasons = C.check_compatible(c, target="macos-arm64", backend="cuda")
+ self.assertTrue(any("built for the metal backend" in r for r in reasons), reasons)
+
+
+class TestSafeExtraction(StoreCase):
+ """The attack shapes, each asserted to write nothing."""
+
+ def extract(self, data: bytes, name: str = "a.tar.gz") -> Path:
+ archive = self.tmp / name
+ archive.write_bytes(data)
+ destination = self.tmp / "out"
+ C.safe_extract(archive, destination)
+ return destination
+
+ def assert_refused_and_empty(self, data: bytes, expect: str):
+ destination = self.tmp / "out"
+ with self.assertRaises(C.UnsafeArchive) as ctx:
+ archive = self.tmp / "bad.tar.gz"
+ archive.write_bytes(data)
+ C.safe_extract(archive, destination)
+ self.assertIn(expect, str(ctx.exception))
+ present = sorted(p.name for p in destination.rglob("*")) if destination.exists() else []
+ self.assertEqual(present, [], f"a refusal must leave nothing behind, found {present}")
+
+ def test_a_normal_archive_extracts(self):
+ out = self.extract(tar_bytes([("bin/strata", b"#!/bin/sh\n"), ("README", b"hi")]))
+ self.assertEqual((out / "bin/strata").read_bytes(), b"#!/bin/sh\n")
+ self.assertEqual((out / "README").read_bytes(), b"hi")
+
+ def test_a_parent_segment_is_refused(self):
+ self.assert_refused_and_empty(tar_bytes([("../escaped", b"x")]), "'..' segment")
+
+ def test_a_nested_parent_segment_is_refused(self):
+ self.assert_refused_and_empty(tar_bytes([("a/b/../../../escaped", b"x")]), "'..' segment")
+
+ def test_an_absolute_path_is_refused(self):
+ self.assert_refused_and_empty(tar_bytes([("/etc/passwd", b"x")]), "absolute path")
+
+ def test_a_windows_drive_path_is_refused(self):
+ self.assert_refused_and_empty(tar_bytes([("C:\\Windows\\evil", b"x")]), "drive-letter")
+
+ def test_a_backslash_parent_segment_is_refused(self):
+ self.assert_refused_and_empty(tar_bytes([("..\\escaped", b"x")]), "'..' segment")
+
+ def test_a_unc_path_is_refused(self):
+ self.assert_refused_and_empty(tar_bytes([("//server/share/evil", b"x")]), "absolute path")
+
+ def test_a_symlink_is_refused(self):
+ """A symlink's *name* is innocent, so only refusing links catches it."""
+ self.assert_refused_and_empty(
+ tar_bytes([("link", b"")], links=[("escape", "/etc/passwd")]), "symlink")
+
+ def test_a_device_member_is_refused(self):
+ self.assert_refused_and_empty(tar_bytes([("ok", b"x")], devices=True), "device")
+
+ def test_a_good_member_before_a_bad_one_does_not_leave_the_good_one(self):
+ """Validation happens over the whole archive first, so nothing is written before a refusal."""
+ self.assert_refused_and_empty(
+ tar_bytes([("fine.txt", b"hello"), ("../escaped", b"x")]), "'..' segment")
+
+ def test_a_zip_with_a_parent_segment_is_refused(self):
+ buffer = io.BytesIO()
+ with zipfile.ZipFile(buffer, "w") as zf:
+ zf.writestr("../escaped", "x")
+ archive = self.tmp / "bad.zip"
+ archive.write_bytes(buffer.getvalue())
+ destination = self.tmp / "out"
+ with self.assertRaises(C.UnsafeArchive):
+ C.safe_extract(archive, destination, fmt="zip")
+ self.assertFalse(destination.exists() and any(destination.rglob("*")))
+
+ def test_the_executable_bit_survives_and_nothing_else_does(self):
+ buffer = io.BytesIO()
+ with tarfile.open(fileobj=buffer, mode="w:gz") as tar:
+ info = tarfile.TarInfo("bin/run")
+ info.size = 2
+ info.mode = 0o4755 # setuid, which must not survive
+ tar.addfile(info, io.BytesIO(b"#\n"))
+ out = self.extract(buffer.getvalue())
+ mode = (out / "bin/run").stat().st_mode
+ self.assertTrue(mode & stat.S_IXUSR, "a bundled runtime needs its executable bit")
+ self.assertFalse(mode & stat.S_ISUID, "setuid from an archive is never trusted")
+
+
+class TestInstall(StoreCase):
+ def test_a_verified_component_installs_into_the_cache(self):
+ component, payloads = self.payload(tar_bytes([("bin/strata", b"engine")]))
+ path = self.store.install(component, payloads=payloads, target="macos-arm64")
+ self.assertTrue((path / ".complete").exists())
+ self.assertEqual((path / "bin/strata").read_bytes(), b"engine")
+ self.assertEqual(path.name, component.cache_key)
+
+ def test_a_digest_mismatch_installs_nothing(self):
+ data = tar_bytes([("bin/strata", b"engine")])
+ component, _ = self.payload(data)
+ wrong = b"different bytes entirely"
+ with self.assertRaises(C.ComponentError) as ctx:
+ self.store.install(component, payloads={"engine.tar.gz": wrong}, target="macos-arm64")
+ self.assertIn("does not match its manifest", str(ctx.exception))
+ cache = self.store.root / "cache"
+ present = [p.name for p in cache.iterdir()] if cache.exists() else []
+ self.assertEqual(present, [], "a mismatch must leave no cache entry and no staging directory")
+
+ def test_a_declared_size_mismatch_is_refused(self):
+ data = tar_bytes([("a", b"x")])
+ component, _ = self.payload(data)
+ object.__setattr__(component.artifacts[0], "bytes", len(data) + 5)
+ with self.assertRaises(C.ComponentError) as ctx:
+ self.store.install(component, payloads={"engine.tar.gz": data}, target="macos-arm64")
+ self.assertIn("bytes", str(ctx.exception))
+
+ def test_an_incompatible_component_is_refused_before_anything_is_written(self):
+ component, payloads = self.payload(tar_bytes([("a", b"x")]))
+ with self.assertRaises(C.ComponentError) as ctx:
+ self.store.install(component, payloads=payloads, target="linux-x86_64")
+ self.assertEqual(ctx.exception.code, 2)
+ self.assertFalse(any((self.store.root / "cache").iterdir()))
+
+ def test_a_second_install_of_the_same_bytes_reuses_the_cache(self):
+ component, payloads = self.payload(tar_bytes([("a", b"x")]))
+ first = self.store.install(component, payloads=payloads, target="macos-arm64")
+ stamp = (first / ".complete").stat().st_mtime_ns
+ second = self.store.install(component, target="macos-arm64")
+ self.assertEqual(first, second)
+ self.assertEqual((second / ".complete").stat().st_mtime_ns, stamp,
+ "the cached payload was reused rather than rebuilt")
+
+ def test_a_hostile_archive_installs_nothing(self):
+ data = tar_bytes([("fine.txt", b"ok"), ("../escape", b"x")])
+ component, payloads = self.payload(data)
+ with self.assertRaises(C.UnsafeArchive):
+ self.store.install(component, payloads=payloads, target="macos-arm64")
+ self.assertFalse(any((self.store.root / "cache").iterdir()))
+ self.assertFalse((self.tmp / "escape").exists(), "nothing escaped the destination")
+
+
+class TestActivation(StoreCase):
+ def build(self, version: str, marker: bytes) -> tuple[C.Component, dict]:
+ import hashlib
+ data = tar_bytes([("marker", marker)])
+ man = manifest(version=version, artifacts=[
+ {"name": "engine.tar.gz", "url": None, "sha256": hashlib.sha256(data).hexdigest(),
+ "bytes": len(data), "format": "tar.gz"}])
+ return C.parse_manifest(man), {"engine.tar.gz": data}
+
+ def test_activation_puts_the_payload_at_the_active_path(self):
+ component, payloads = self.build("1.0", b"one")
+ self.store.install(component, payloads=payloads, target="macos-arm64")
+ result = self.store.activate(component, target="macos-arm64")
+ self.assertEqual((Path(result["active"]) / "marker").read_bytes(), b"one")
+
+ def test_the_cache_survives_activation(self):
+ """A compatible application update must not have to download the engine again."""
+ component, payloads = self.build("1.0", b"one")
+ cached = self.store.install(component, payloads=payloads, target="macos-arm64")
+ self.store.activate(component, target="macos-arm64")
+ self.assertTrue((cached / "marker").exists(), "the cached payload was consumed")
+
+ def test_activating_a_newer_version_retains_the_previous_one(self):
+ first, p1 = self.build("1.0", b"one")
+ self.store.install(first, payloads=p1, target="macos-arm64")
+ self.store.activate(first, target="macos-arm64")
+ second, p2 = self.build("2.0", b"two")
+ self.store.install(second, payloads=p2, target="macos-arm64")
+ result = self.store.activate(second, target="macos-arm64")
+ self.assertTrue(result["moved_aside"], "the displaced version is kept, not deleted")
+ self.assertEqual((Path(result["active"]) / "marker").read_bytes(), b"two")
+
+ def test_rollback_restores_the_previous_version_exactly(self):
+ first, p1 = self.build("1.0", b"one")
+ self.store.install(first, payloads=p1, target="macos-arm64")
+ self.store.activate(first, target="macos-arm64")
+ second, p2 = self.build("2.0", b"two")
+ self.store.install(second, payloads=p2, target="macos-arm64")
+ self.store.activate(second, target="macos-arm64")
+
+ result = self.store.rollback("strata-engine")
+ self.assertEqual(result["restored"], "1.0")
+ active = self.store.active_path("strata-engine")
+ self.assertEqual((active / "marker").read_bytes(), b"one")
+
+ def test_rollback_without_a_previous_version_is_refused(self):
+ """'Rollback succeeded' and 'the component is gone' must not be the same outcome."""
+ component, payloads = self.build("1.0", b"one")
+ self.store.install(component, payloads=payloads, target="macos-arm64")
+ self.store.activate(component, target="macos-arm64")
+ with self.assertRaises(C.ComponentError) as ctx:
+ self.store.rollback("strata-engine")
+ self.assertEqual(ctx.exception.code, 2)
+ self.assertTrue(self.store.active_path("strata-engine").exists(),
+ "the active version must survive a refused rollback")
+
+ def test_activating_something_not_installed_is_refused(self):
+ component, _ = self.build("1.0", b"one")
+ with self.assertRaises(C.ComponentError) as ctx:
+ self.store.activate(component, target="macos-arm64")
+ self.assertIn("not installed", str(ctx.exception))
+
+ def test_activating_an_incompatible_component_is_refused(self):
+ component, payloads = self.build("1.0", b"one")
+ self.store.install(component, payloads=payloads, target="macos-arm64")
+ with self.assertRaises(C.ComponentError) as ctx:
+ self.store.activate(component, target="linux-x86_64")
+ self.assertEqual(ctx.exception.code, 2)
+
+
+class TestStoreState(StoreCase):
+ def build(self, version: str) -> tuple[C.Component, dict]:
+ import hashlib
+ data = tar_bytes([("marker", version.encode())])
+ man = manifest(version=version, artifacts=[
+ {"name": "engine.tar.gz", "url": None, "sha256": hashlib.sha256(data).hexdigest(),
+ "bytes": len(data), "format": "tar.gz"}])
+ return C.parse_manifest(man), {"engine.tar.gz": data}
+
+ def test_installed_versions_are_listed_and_the_active_one_marked(self):
+ one, p1 = self.build("1.0")
+ self.store.install(one, payloads=p1, target="macos-arm64")
+ two, p2 = self.build("2.0")
+ self.store.install(two, payloads=p2, target="macos-arm64")
+ self.store.activate(one, target="macos-arm64")
+ listed = self.store.installed("strata-engine")
+ self.assertEqual([c.version for c in listed], ["1.0", "2.0"])
+ self.assertEqual([c.version for c in listed if c.active], ["1.0"])
+
+ def test_a_damaged_state_file_does_not_make_the_store_unusable(self):
+ (self.store.root / "state.json").write_text("{ broken", encoding="utf-8")
+ self.assertEqual(self.store.state()["components"], {})
+
+ def test_pruning_keeps_what_is_active_and_what_rollback_needs(self):
+ one, p1 = self.build("1.0")
+ self.store.install(one, payloads=p1, target="macos-arm64")
+ self.store.activate(one, target="macos-arm64")
+ two, p2 = self.build("2.0")
+ kept = self.store.install(two, payloads=p2, target="macos-arm64")
+ self.store.activate(two, target="macos-arm64")
+
+ removed = self.store.prune_cache()
+ self.assertNotIn(one.cache_key, removed, "the rollback target must survive a prune")
+ self.assertNotIn(two.cache_key, removed, "the active version must survive a prune")
+ self.assertTrue((kept / "marker").exists())
+
+ def test_pruning_removes_a_cache_entry_nothing_refers_to(self):
+ orphan = self.store.root / "cache" / ("f" * 64)
+ orphan.mkdir(parents=True)
+ (orphan / "junk").write_text("x", encoding="utf-8")
+ self.assertIn("f" * 64, self.store.prune_cache())
+ self.assertFalse(orphan.exists())
+
+
+class TestInterruptedTransfer(StoreCase):
+ """P12: an interrupted download keeps its bytes and resumes."""
+
+ def test_a_partial_file_larger_than_the_declared_size_is_discarded(self):
+ """A stale partial from a different artifact must not be appended to."""
+ partial = self.store.root / "partial" / "engine.tar.gz"
+ partial.write_bytes(b"x" * 5000)
+ component, _ = self.payload(tar_bytes([("a", b"x")]))
+ artifact = component.artifacts[0]
+ # A URL is needed to reach the transfer logic at all; it is never fetched, because the stale
+ # partial is discarded and the ranged request then fails on the unreachable host.
+ object.__setattr__(artifact, "url", "https://example.invalid/e.tar.gz")
+ object.__setattr__(artifact, "bytes", 100)
+ with self.assertRaises(C.ComponentError):
+ self.store._fetch(artifact)
+ self.assertFalse(partial.exists(), "a stale partial is removed, not appended to")
+
+ def test_a_short_download_is_an_error_and_the_partial_is_kept(self):
+ """The bytes are kept so a later attempt resumes rather than restarting."""
+ import urllib.request
+ body = b"only part of it"
+
+ class FakeResponse(io.BytesIO):
+ status = 200
+
+ def __enter__(self_inner):
+ return self_inner
+
+ def __exit__(self_inner, *a):
+ return False
+
+ original = urllib.request.urlopen
+ urllib.request.urlopen = lambda *a, **k: FakeResponse(body)
+ try:
+ component, _ = self.payload(tar_bytes([("a", b"x")]))
+ artifact = component.artifacts[0]
+ object.__setattr__(artifact, "url", "https://example.invalid/e.tar.gz")
+ with self.assertRaises(C.ComponentError) as ctx:
+ self.store._fetch(artifact)
+ self.assertIn("resume", str(ctx.exception))
+ finally:
+ urllib.request.urlopen = original
+ self.assertTrue((self.store.root / "partial" / "engine.tar.gz").exists(),
+ "the partial bytes must be kept for a resume")
+
+ def test_an_unreachable_url_is_reported_as_an_interruption_not_a_crash(self):
+ import urllib.request
+ original = urllib.request.urlopen
+
+ def boom(*a, **k):
+ raise OSError("network unreachable")
+
+ urllib.request.urlopen = boom
+ try:
+ component, _ = self.payload(tar_bytes([("a", b"x")]))
+ artifact = component.artifacts[0]
+ object.__setattr__(artifact, "url", "https://example.invalid/e.tar.gz")
+ with self.assertRaises(C.ComponentError) as ctx:
+ self.store._fetch(artifact)
+ self.assertIn("interrupted", str(ctx.exception))
+ finally:
+ urllib.request.urlopen = original
+
+ def test_a_crash_during_install_leaves_no_complete_entry(self):
+ """The `.complete` marker is written last, so a partial directory is never trusted."""
+ data = tar_bytes([("a", b"x")])
+ component, _ = self.payload(data)
+ with self.assertRaises(C.ComponentError):
+ self.store.install(component, payloads={"engine.tar.gz": b"wrong"}, target="macos-arm64")
+ self.assertIsNone(self.store.cached(component))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/tuning/test_offline.py b/tests/tuning/test_offline.py
new file mode 100644
index 000000000..e7039c2a9
--- /dev/null
+++ b/tests/tuning/test_offline.py
@@ -0,0 +1,193 @@
+"""Offline policy tests (checklist U08).
+
+The checklist asks for two claims that are easy to conflate, and the whole point of these tests is
+that they are separate:
+
+* **runtime-only no-download** — the server fetches nothing while serving;
+* **strict offline** — nothing in the process tree reaches the network, including children, tools and
+ the agent runtime.
+
+A passing runtime-only test says nothing about the second: the first is about the server's own code
+paths, and the second is about every process it can start. So they are tested separately, and the
+strict tests check the actual environment a child receives rather than the flag that was passed.
+
+The limits are tested too. A policy that claims more than it enforces is worse than one that states
+its boundary, so `limits()` is asserted to be non-empty and specific.
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+import unittest
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from strata_control import offline as O # noqa: E402
+
+
+class TestUrlDecisions(unittest.TestCase):
+ """One predicate decides every fetch, so "offline" is not a scattered set of ifs."""
+
+ def test_a_remote_url_is_refused_when_offline(self):
+ decision = O.check_url("https://huggingface.co/model.bin", offline=True)
+ self.assertFalse(decision)
+ self.assertIn("huggingface.co", decision.reason)
+
+ def test_a_remote_url_is_allowed_when_not_offline(self):
+ self.assertTrue(O.check_url("https://huggingface.co/model.bin", offline=False))
+
+ def test_a_local_scheme_is_allowed_even_when_offline(self):
+ """Talking to this machine is not a download, and forbidding it would break the local API."""
+ for url in ("file:///tmp/image.png", "data:image/png;base64,AAAA"):
+ decision = O.check_url(url, offline=True)
+ self.assertTrue(decision, f"{url} must be allowed offline")
+
+ def test_loopback_over_http_is_allowed_when_offline(self):
+ for url in ("http://127.0.0.1:8095/v1/models", "http://localhost:8095/health",
+ "http://[::1]:8095/health"):
+ self.assertTrue(O.check_url(url, offline=True), f"{url} is this machine")
+
+ def test_a_bare_path_is_allowed_when_offline(self):
+ """A profile usually names a local image as a path, not as a URL."""
+ self.assertTrue(O.check_url("/models/photo.png", offline=True))
+ self.assertTrue(O.check_url("photo.png", offline=True))
+
+ def test_a_non_http_scheme_is_refused_when_offline(self):
+ decision = O.check_url("ftp://example.com/x", offline=True)
+ self.assertFalse(decision)
+ self.assertIn("scheme", decision.reason)
+
+ def test_require_url_raises_with_the_reason(self):
+ with self.assertRaises(O.OfflineViolation) as ctx:
+ O.require_url("https://example.com/x", offline=True)
+ self.assertIn("would leave this machine", str(ctx.exception))
+ self.assertEqual(ctx.exception.url, "https://example.com/x")
+
+ def test_require_url_passes_a_local_url(self):
+ O.require_url("http://127.0.0.1:1/x", offline=True) # must not raise
+
+
+class TestChildEnvironment(unittest.TestCase):
+ """Strict offline must reach code we do not own, which means the environment."""
+
+ def test_the_offline_markers_are_set_for_children(self):
+ env = O.child_environment(offline=True, base={})
+ self.assertEqual(env["HF_HUB_OFFLINE"], "1")
+ self.assertEqual(env["TRANSFORMERS_OFFLINE"], "1")
+ self.assertEqual(env["PIP_NO_INDEX"], "1")
+ self.assertEqual(env["STRATA_OFFLINE"], "1")
+
+ def test_proxies_are_emptied_so_an_accidental_call_fails_fast(self):
+ env = O.child_environment(offline=True,
+ base={"HTTPS_PROXY": "http://corp-proxy:8080"})
+ self.assertEqual(env["HTTPS_PROXY"], "")
+ self.assertEqual(env["NO_PROXY"], "*")
+
+ def test_the_parent_environment_is_not_mutated(self):
+ base = {"HTTPS_PROXY": "http://corp-proxy:8080", "PATH": "/usr/bin"}
+ O.child_environment(offline=True, base=base)
+ self.assertEqual(base["HTTPS_PROXY"], "http://corp-proxy:8080",
+ "the caller's environment must be untouched")
+
+ def test_a_marker_from_a_previous_run_is_removed_when_not_offline(self):
+ """Otherwise a later server mysteriously refuses to fetch anything."""
+ env = O.child_environment(offline=False, base={"HF_HUB_OFFLINE": "1", "PATH": "/usr/bin"})
+ self.assertNotIn("HF_HUB_OFFLINE", env)
+ self.assertEqual(env["PATH"], "/usr/bin")
+
+ def test_the_real_environment_is_used_by_default(self):
+ env = O.child_environment(offline=True)
+ self.assertEqual(env["STRATA_OFFLINE"], "1")
+ self.assertIn("PATH", env, "the child still needs a PATH")
+
+
+class TestProfilePreflight(unittest.TestCase):
+ """Refusing before the server starts beats failing on the first request."""
+
+ def test_a_plain_profile_is_strictly_offline_capable(self):
+ self.assertEqual(O.ensure_strictly_offline({"model": "x", "args": []}), [])
+
+ def test_mcp_servers_are_named_as_a_reason(self):
+ reasons = O.ensure_strictly_offline({"mcp_servers": {"a": {}, "b": {}}})
+ self.assertTrue(reasons)
+ self.assertIn("2 MCP server", reasons[0])
+
+ def test_a_before_load_command_is_named_as_a_reason(self):
+ reasons = O.ensure_strictly_offline({"before_load": "curl https://example.com/x"})
+ self.assertTrue(reasons)
+ self.assertIn("before_load", reasons[0])
+
+ def test_remote_image_sources_are_named_as_a_reason(self):
+ reasons = O.ensure_strictly_offline({"images": {"allowed_hosts": ["cdn.example.com"]}})
+ self.assertTrue(reasons)
+ self.assertIn("images.allowed_hosts", reasons[0])
+
+ def test_a_local_image_section_is_not_a_reason(self):
+ self.assertEqual(O.ensure_strictly_offline({"images": {"size": 512}}), [])
+
+
+class TestTheLimitIsStated(unittest.TestCase):
+ """A policy that claims more than it enforces is worse than one that names its boundary."""
+
+ def test_the_limits_are_specific_and_non_empty(self):
+ limits = O.limits()
+ self.assertTrue(limits)
+ joined = " ".join(limits).lower()
+ self.assertIn("socket", joined, "the socket case is the one that matters")
+ self.assertIn("sandbox", joined)
+
+ def test_the_report_separates_the_two_claims(self):
+ report = O.report(offline=True, cfg={"model": "x"})
+ self.assertTrue(report["strict_offline"])
+ self.assertTrue(report["runtime_only_no_download"],
+ "runtime-only is true independently of strict offline")
+ self.assertTrue(report["enforced"])
+ self.assertTrue(report["not_enforced"], "the limits travel with the claim")
+
+ def test_the_report_of_a_non_offline_run_does_not_claim_enforcement(self):
+ report = O.report(offline=False, cfg={})
+ self.assertFalse(report["strict_offline"])
+ self.assertEqual(report["not_enforced"], [])
+ self.assertTrue(report["runtime_only_no_download"])
+
+ def test_the_report_says_which_profile_parts_block_strict_offline(self):
+ report = O.report(offline=True, cfg={"mcp_servers": {"a": {}}})
+ self.assertTrue(report["profile_needs_network"])
+
+
+class TestTheServerUsesThePolicy(unittest.TestCase):
+ """A guard that is not wired in is decoration, so the wiring itself is asserted."""
+
+ def setUp(self):
+ self.source = (Path(__file__).resolve().parents[2] / "serve" / "server.py").read_text(
+ encoding="utf-8")
+
+ def test_the_image_path_consults_the_policy_or_the_flag(self):
+ # The reviewed server already refuses a remote image URL when offline; what matters here is
+ # that the refusal exists on both image paths rather than one.
+ self.assertGreaterEqual(self.source.count("offline mode cannot download an image URL"), 2,
+ "both image paths must refuse a remote fetch")
+
+ def test_child_env_stamps_the_policy(self):
+ self.assertIn("offline_policy.OFFLINE_ENV", self.source,
+ "children must be given the offline environment")
+
+ def test_every_child_environment_call_passes_the_policy(self):
+ """A single call site that forgot the flag would leak network access to that child."""
+ offenders = []
+ for index, line in enumerate(self.source.splitlines(), start=1):
+ if "child_env(" in line and "def child_env" not in line:
+ if "offline=" not in line:
+ offenders.append(f"line {index}: {line.strip()}")
+ self.assertEqual(offenders, [],
+ "every child_env call must pass the server's offline state: "
+ + "; ".join(offenders))
+
+ def test_the_strict_offline_preflight_runs_before_serving(self):
+ self.assertIn("ensure_strictly_offline", self.source)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/calibrate.py b/tools/calibrate.py
index 3ed6a4c85..ca269d978 100644
--- a/tools/calibrate.py
+++ b/tools/calibrate.py
@@ -53,6 +53,20 @@ PROMPTS = (
)
+class CalibrationCancelled(RuntimeError):
+ """An operator requested a stop; no partial sample may enter the report."""
+
+
+def _check_cancel(cancel_event):
+ if cancel_event is not None and cancel_event.is_set():
+ raise CalibrationCancelled("calibration cancelled")
+
+
+def _progress(callback, stage: str, completed: int, total: int):
+ if callback is not None:
+ callback(stage, completed, total)
+
+
def chat_ids(tok, text: str) -> list[int]:
return tok.encode(f"<|im_start|>user\n{text}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n",
parse_special=True)
@@ -111,18 +125,22 @@ def pick(measured: dict, default_key, min_gain: float = MIN_GAIN):
class Session:
"""One running engine: measure decode tok/s for a setting (the median of the prompts' rates)."""
- def __init__(self, engine, ids_list):
+ def __init__(self, engine, ids_list, cancel_event=None):
self.engine = engine
self.ids_list = ids_list
+ self.cancel_event = cancel_event
def rate(self, tune: dict | None = None, max_new: int | None = None) -> float:
rates = []
for ids in self.ids_list:
+ _check_cancel(self.cancel_event)
sampling = {"temperature": 0}
if tune:
sampling["strata_tune"] = tune
- n = sum(1 for t in self.engine.generate(ids, max_new or MAX_NEW, sampling, threading.Event())
+ n = sum(1 for t in self.engine.generate(ids, max_new or MAX_NEW, sampling,
+ self.cancel_event or threading.Event())
if t is not None)
+ _check_cancel(self.cancel_event)
ms = (self.engine.last or {}).get("decode_ms") or 0.0
if n > 8 and ms > 0:
rates.append(n / (ms / 1000.0))
@@ -133,7 +151,7 @@ class Session:
self.rate()
-def run(cfg: dict, say=print, start_engine=None) -> dict:
+def run(cfg: dict, say=print, start_engine=None, *, progress=None, cancel_event=None) -> dict:
"""Measure on the engine `cfg` describes; returns {"settings": {flag: value}, "report": {...}}.
`start_engine(args)` returns a started engine (serve.server.StrataEngine or a stand-in in tests)."""
if start_engine is None:
@@ -150,7 +168,10 @@ def run(cfg: dict, say=print, start_engine=None) -> dict:
tok = ST.Tokenizer(toks, (tpath / "merges.txt").read_text(encoding="utf-8").split("\n"),
json.loads((tpath / "token_type.json").read_text()))
ids_list = [chat_ids(tok, p) for p in PROMPTS]
- return measure(engine_args(cfg), ids_list, start_engine, say, host_worker_extras())
+ if progress is None and cancel_event is None:
+ return measure(engine_args(cfg), ids_list, start_engine, say, host_worker_extras())
+ return measure(engine_args(cfg), ids_list, start_engine, say, host_worker_extras(),
+ progress=progress, cancel_event=cancel_event)
def engine_args(cfg: dict) -> list[str]:
@@ -176,7 +197,8 @@ def engine_error(log: str | None, since: int = 0) -> str | None:
return next((x for x in reversed(lines) if x.startswith(("strata", "ERR"))), lines[-1] if lines else None)
-def sweep(s, values: list, base_tune: dict, key: str, label: str, say) -> dict:
+def sweep(s, values: list, base_tune: dict, key: str, label: str, say,
+ progress=None, stage: str | None = None) -> dict:
"""Every value, `SWEEP_ROUNDS` times, one round visiting all of them and every other round in reverse order.
A single rate per value cannot order neighbours. #1332 has 0.75 to 0.95 inside each other's noise at 72.7,
@@ -187,9 +209,15 @@ def sweep(s, values: list, base_tune: dict, key: str, label: str, say) -> dict:
medians, so every value keeps the same chance the others had.
"""
out = {v: [] for v in values}
+ if stage is not None:
+ _progress(progress, stage, 0, len(values) * SWEEP_ROUNDS)
+ completed = 0
for r in range(SWEEP_ROUNDS):
for v in (values if r % 2 == 0 else values[::-1]):
out[v].append(s.rate({**base_tune, key: v}))
+ completed += 1
+ if stage is not None:
+ _progress(progress, stage, completed, len(values) * SWEEP_ROUNDS)
say(f" round {r + 1}/{SWEEP_ROUNDS} {label}: " +
" ".join(f"{v:g} {out[v][-1]:.1f}" for v in values))
med = {v: statistics.median(out[v]) for v in values}
@@ -199,9 +227,12 @@ def sweep(s, values: list, base_tune: dict, key: str, label: str, say) -> dict:
return out
-def measure(base_args: list[str], ids_list, start_engine, say=print, extra_workers=()) -> dict:
+def measure(base_args: list[str], ids_list, start_engine, say=print, extra_workers=(),
+ *, progress=None, cancel_event=None) -> dict:
t0 = time.time()
report: dict = {}
+ _check_cancel(cancel_event)
+ _progress(progress, "loading", 0, 1)
say(" Loading the model for the measurements ...")
base_args = apply(base_args, {}) # the product defaults: what the measurements must beat
eng = start_engine(base_args)
@@ -210,23 +241,29 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke
d_pcie = float(info.get("pcie_frac", 0.55))
d_minp = float(info.get("spec_min_p", 0.5))
d_workers = int(info.get("pool_workers", 0)) or None
- s = Session(eng, ids_list)
+ s = Session(eng, ids_list, cancel_event)
s.warm_up()
+ _progress(progress, "loading", 1, 1)
# 1. the PCIe share, at the default draft floor
by_pcie = sweep(s, sorted(set(PCIE_FRACS) | {round(d_pcie, 2)}), {"spec_min_p": d_minp}, "pcie_frac",
- "PCIe share", say)
+ "PCIe share", say, progress, "pcie_share")
best_pcie = max(by_pcie, key=lambda k: statistics.median(by_pcie[k]))
# 2. the draft floor, at that share
by_minp = sweep(s, sorted(set(SPEC_MIN_PS) | {round(d_minp, 2)}), {"pcie_frac": best_pcie}, "spec_min_p",
- "draft floor", say)
+ "draft floor", say, progress, "draft_floor")
best_minp = max(by_minp, key=lambda k: statistics.median(by_minp[k]))
# 3. the winner against the default, interleaved, the same number of rounds
dflt, cand = (round(d_pcie, 2), round(d_minp, 2)), (best_pcie, best_minp)
confirm = {dflt: [], cand: []}
+ confirm_total = SWEEP_ROUNDS * 2 if cand != dflt else 1
+ _progress(progress, "confirmation", 0, confirm_total)
if cand != dflt:
for _ in range(SWEEP_ROUNDS):
for k in (dflt, cand):
confirm[k].append(s.rate({"pcie_frac": k[0], "spec_min_p": k[1]}))
+ _progress(progress, "confirmation", sum(map(len, confirm.values())), confirm_total)
+ else:
+ _progress(progress, "confirmation", 1, 1)
chosen = pick(confirm, dflt) if cand != dflt else dflt
report.update(default={"pcie_frac": dflt[0], "spec_min_p": dflt[1], "pool_workers": d_workers},
pcie_sweep={str(k): v for k, v in by_pcie.items()},
@@ -243,19 +280,24 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke
if d_workers and len(worker_candidates(d_workers, extra_workers)) > 1:
tuned = with_arg(with_arg(base_args, "--pcie-frac", f"{chosen[0]:.2f}"), "--spec-min-p", f"{chosen[1]:.2f}")
by_workers = {}
- for w in worker_candidates(d_workers, extra_workers):
+ workers = worker_candidates(d_workers, extra_workers)
+ _progress(progress, "cpu_workers", 0, len(workers))
+ for index, w in enumerate(workers, 1):
+ _check_cancel(cancel_event)
say(f" Measuring with {w} CPU workers (restarts the engine) ...")
e = restart(start_engine, with_arg(tuned, "--pool-workers", None if w == d_workers else str(w)), f"{w} workers",
say, report)
if e is None:
+ _progress(progress, "cpu_workers", index, len(workers))
continue
try:
- sw = Session(e, ids_list)
+ sw = Session(e, ids_list, cancel_event)
sw.warm_up(1)
by_workers[w] = [sw.rate(), sw.rate()]
say(f" {w} workers: {statistics.median(by_workers[w]):.1f} tok/s")
finally:
close(e)
+ _progress(progress, "cpu_workers", index, len(workers))
report["workers"] = {str(k): v for k, v in by_workers.items()}
w_best = pick(by_workers, d_workers) if by_workers else d_workers
if w_best != d_workers:
@@ -263,10 +305,14 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke
base_rate = statistics.median(by_workers[w_best])
elif by_workers.get(d_workers):
base_rate = statistics.median(by_workers[d_workers])
+ else:
+ _progress(progress, "cpu_workers", 1, 1)
# 5. the adaptive expert tier (a restart each), with everything chosen so far
tuned = apply(base_args, settings)
by_adapt = {}
- for cand in ADAPT_CANDIDATES:
+ _progress(progress, "expert_tier", 0, len(ADAPT_CANDIDATES))
+ for index, cand in enumerate(ADAPT_CANDIDATES, 1):
+ _check_cancel(cancel_event)
key = "default" if cand is None else "/".join(cand)
args = tuned
for flag, v in zip(ADAPT_FLAGS, cand or (None,) * len(ADAPT_FLAGS)):
@@ -274,14 +320,16 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke
say(f" Measuring the expert tier {'(the engine default)' if cand is None else 'every ' + cand[0] + ', ' + cand[1] + ' swaps, decay ' + cand[2]} (restarts the engine) ...")
e = restart(start_engine, args, "the expert tier " + key, say, report)
if e is None:
+ _progress(progress, "expert_tier", index, len(ADAPT_CANDIDATES))
continue
try:
- sa = Session(e, ids_list)
+ sa = Session(e, ids_list, cancel_event)
sa.warm_up(1)
by_adapt[key] = [sa.rate(max_new=TIER_MAX_NEW), sa.rate(max_new=TIER_MAX_NEW)]
say(f" {statistics.median(by_adapt[key]):.1f} tok/s")
finally:
close(e)
+ _progress(progress, "expert_tier", index, len(ADAPT_CANDIDATES))
a_best = pick(by_adapt, "default") if by_adapt else "default"
report["adapt"] = by_adapt
if a_best != "default":
@@ -292,6 +340,7 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke
base_rate = statistics.median(by_adapt["default"])
report["seconds"] = round(time.time() - t0)
report["tok_s"] = round(base_rate, 1) if base_rate else None
+ _check_cancel(cancel_event)
return {"settings": settings, "report": report}
diff --git a/tools/minimal_cli_smoke.py b/tools/minimal_cli_smoke.py
new file mode 100644
index 000000000..27661f483
--- /dev/null
+++ b/tools/minimal_cli_smoke.py
@@ -0,0 +1,125 @@
+#!/usr/bin/env python3
+"""Check source CLI dispatch without optional terminal or harness packages.
+
+This runs Python with -S against a loopback telemetry fixture. It checks lazy
+client dispatch and early serving failure, not an actual engine or installation.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import platform
+import subprocess
+import sys
+import tempfile
+import threading
+from pathlib import Path
+
+from portable_monitor_smoke import _server
+
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def _run(*args: str) -> subprocess.CompletedProcess[str]:
+ env = os.environ.copy()
+ env.pop("PYTHONPATH", None)
+ env.pop("PYTHONHOME", None)
+ env["PYTHONNOUSERSITE"] = "1"
+ return subprocess.run([sys.executable, "-S", *args], cwd=ROOT, env=env,
+ capture_output=True, text=True, timeout=20, check=False)
+
+
+def _record(result: subprocess.CompletedProcess[str], expected_exit: int) -> dict:
+ if result.returncode != expected_exit or result.stderr.strip():
+ raise RuntimeError(f"CLI exit {result.returncode}, stderr {result.stderr.strip()!r}")
+ try:
+ value = json.loads(result.stdout)
+ except json.JSONDecodeError as exc:
+ raise RuntimeError("CLI did not write exactly one JSON record") from exc
+ if not isinstance(value, dict) or value.get("schema_version") != 1:
+ raise RuntimeError("CLI JSON schema was missing")
+ return value
+
+
+def smoke() -> dict:
+ probe = _run("-c", "import importlib.util,json,sys; print(json.dumps({"
+ "'no_site':sys.flags.no_site,'rich':importlib.util.find_spec('rich') is not None,"
+ "'textual':importlib.util.find_spec('textual') is not None}))")
+ if probe.returncode or probe.stderr.strip():
+ raise RuntimeError("could not establish the no-site-packages test environment")
+ extras = json.loads(probe.stdout)
+ if extras != {"no_site": 1, "rich": False, "textual": False}:
+ raise RuntimeError("optional terminal packages are visible in the test environment")
+
+ help_result = _run(str(ROOT / "strata.py"), "--help")
+ if (help_result.returncode or help_result.stderr.strip() or
+ not all(word in help_result.stdout for word in ("serve", "monitor", "code"))):
+ raise RuntimeError("source CLI help failed without optional packages")
+
+ server, paths, _ = _server()
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ url = f"http://127.0.0.1:{server.server_address[1]}"
+ status = _record(_run(str(ROOT / "strata.py"), "status", "--url", url, "--json"), 0)
+ once = _record(_run(str(ROOT / "strata.py"), "monitor", "--url", url,
+ "--once", "--output", "json"), 0)
+ for value in (status, once):
+ if (value.get("ok") is not True or
+ (value.get("snapshot", {}).get("instance") or {}).get("id") != "portable-smoke" or
+ (value.get("snapshot", {}).get("model") or {}).get("id") != "portable-smoke-model"):
+ raise RuntimeError("one-shot CLI showed the wrong telemetry fixture")
+ if paths != ["GET /v1/telemetry", "GET /v1/telemetry"]:
+ raise RuntimeError("one-shot commands sent unexpected HTTP requests")
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=2)
+
+ with tempfile.TemporaryDirectory(prefix="strata-minimal-cli-") as directory:
+ missing = str(Path(directory) / "missing-config.json")
+ serve = _record(_run(str(ROOT / "strata.py"), "serve", "--profile", missing,
+ "--offline", "--output", "jsonl"), 5)
+ if (serve.get("event") != "failed" or serve.get("exit_code") != 5 or
+ "cannot read run config" not in (serve.get("error") or {}).get("message", "")):
+ raise RuntimeError("missing run config did not fail before server startup")
+ code = _record(_run(str(ROOT / "strata.py"), "code", "run", "--prompt-file",
+ str(Path(directory) / "missing-prompt.txt"), "--policy", "review",
+ "--output", "jsonl"), 5)
+ if (code.get("ok") is not False or
+ (code.get("error") or {}).get("code") != 5 or
+ "harness component" not in (code.get("error") or {}).get("message", "")):
+ raise RuntimeError("missing harness did not return actionable exit 5")
+
+ return {"schema_version": 1, "scope": "source_cli_without_site_packages",
+ "platform": platform.platform(), "python": platform.python_version(),
+ "optional_packages_visible": {"rich": False, "textual": False},
+ "commands": ["--help", "status --json", "monitor --once --output json",
+ "serve --offline --output jsonl (missing config)",
+ "code run --output jsonl (missing harness)"],
+ "telemetry_gets": len(paths), "non_gets": 0,
+ "actual_engine_started": False, "passed": True}
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--report", type=Path, required=True, help="new absolute JSON report path")
+ args = parser.parse_args()
+ report = args.report.expanduser()
+ if not report.is_absolute() or report.exists():
+ parser.error("--report must be an absolute new file")
+ result = smoke()
+ report.parent.mkdir(parents=True, exist_ok=True)
+ descriptor = os.open(report, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
+ json.dump(result, stream, indent=2)
+ stream.write("\n")
+ print(json.dumps({"report": str(report), "passed": result["passed"]}))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tools/minimal_server_smoke.py b/tools/minimal_server_smoke.py
new file mode 100644
index 000000000..81780639c
--- /dev/null
+++ b/tools/minimal_server_smoke.py
@@ -0,0 +1,74 @@
+#!/usr/bin/env python3
+"""Exercise fake-engine serving from a clean runtime-only Python environment.
+
+Create a fresh venv, install requirements.txt, then run this script with that
+venv's Python. The runtime integration module exercises foreground and POSIX
+owned serving; no GPU, model weights or optional terminal framework is needed.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import importlib.util
+import json
+import os
+import platform
+import re
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[1]
+TEST_MODULE = "tests.terminal.test_runtime"
+MIN_TESTS = 32
+
+
+def smoke() -> dict:
+ if sys.prefix == sys.base_prefix:
+ raise RuntimeError("run with a dedicated virtual environment")
+ if os.name != "posix":
+ raise RuntimeError("this owned-runtime check currently requires POSIX")
+ visible = {name: importlib.util.find_spec(name) is not None
+ for name in ("rich", "textual", "numpy", "jinja2", "requests")}
+ if visible != {"rich": False, "textual": False, "numpy": True,
+ "jinja2": True, "requests": True}:
+ raise RuntimeError(f"runtime-only dependency set was not isolated: {visible}")
+ started = time.monotonic()
+ result = subprocess.run([sys.executable, "-m", "unittest", TEST_MODULE], cwd=ROOT,
+ capture_output=True, text=True, timeout=240, check=False)
+ summary = result.stdout + result.stderr
+ count = re.search(r"Ran (\d+) tests in [0-9.]+s\s+OK\s*$", summary)
+ passed = result.returncode == 0 and count is not None and int(count[1]) >= MIN_TESTS
+ return {"schema_version": 1, "scope": "source_checkout_fake_engine_runtime_only",
+ "platform": platform.platform(), "python": platform.python_version(),
+ "requirements_sha256": hashlib.sha256((ROOT / "requirements.txt").read_bytes()).hexdigest(),
+ "optional_packages_visible": {name: visible[name] for name in ("rich", "textual")},
+ "server_packages_visible": {name: visible[name] for name in ("numpy", "jinja2", "requests")},
+ "test_module": TEST_MODULE, "tests_run": int(count[1]) if count else None,
+ "duration_s": round(time.monotonic() - started, 2),
+ "test_exit_code": result.returncode, "actual_gpu_engine": False,
+ "passed": bool(passed), "test_summary": summary[-1000:]}
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--report", type=Path, required=True, help="new absolute JSON report path")
+ args = parser.parse_args()
+ report = args.report.expanduser()
+ if not report.is_absolute() or report.exists():
+ parser.error("--report must be an absolute new file")
+ result = smoke()
+ report.parent.mkdir(parents=True, exist_ok=True)
+ descriptor = os.open(report, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
+ json.dump(result, stream, indent=2)
+ stream.write("\n")
+ print(json.dumps({"report": str(report), "passed": result["passed"]}), flush=True)
+ return 0 if result["passed"] else 6
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tools/monitor_soak.py b/tools/monitor_soak.py
new file mode 100644
index 000000000..cef6feddc
--- /dev/null
+++ b/tools/monitor_soak.py
@@ -0,0 +1,309 @@
+#!/usr/bin/env python3
+"""Headless Monitor soak against a bounded synthetic telemetry server.
+
+This is a client stability check, not model, GPU or serving performance evidence.
+Run for 1800 seconds to exercise reconnects, instance changes and bounded state.
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+import os
+import threading
+import time
+import tracemalloc
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+
+from strata_cli.client import Endpoint
+
+
+class SyntheticTelemetry:
+ def __init__(self, *, exercise_ui: bool = False):
+ self.lock = threading.Lock()
+ self.instance = 0
+ self.unavailable = False
+ self.gets = 0
+ self.failures = 0
+ self.other_methods = 0
+ self.bytes_sent = 0
+ self.in_flight = 0
+ self.max_in_flight = 0
+ self.seq = 0
+ self.exercise_ui = exercise_ui
+
+ def snapshot(self) -> dict:
+ with self.lock:
+ self.seq += 1
+ seq, instance = self.seq, self.instance
+ now = time.time()
+ events = [{"seq": number, "at": now, "request_id": f"{number:012x}", "event": "queued"}
+ for number in range(max(1, seq - 63), seq + 1)]
+ devices = [{"index": i, "name": f"Synthetic card {i}"} for i in range(4)]
+ topology = {}
+ if self.exercise_ui:
+ # Rotate an unrelated host card and intermittently lose or duplicate
+ # a selected sensor. The Overview must retain only the four selected
+ # card histories and mark current gaps unavailable.
+ devices = [{"index": 100 + seq, "name": "Unselected host card", "util": 10}]
+ devices += [{"index": i, "name": f"Selected card {i}",
+ "util": (40 + i * 11 + seq) % 100,
+ "mem_used": (12 + i) * 2**30, "mem_total": 24 * 2**30}
+ for i in range(4) if not (i == 3 and seq % 5 == 0)]
+ if seq % 7 == 0:
+ devices.append({"index": 1, "name": "Ambiguous card 1", "util": 99})
+ topology = {"mode": "layer split", "selected_devices": [0, 1, 2, 3],
+ "resolved": False, "stages": []}
+ return {"schema_version": 1, "source": "synthetic-soak", "sampled_at": now,
+ "instance": {"id": f"synthetic-{instance}", "state": "ready", "boot_time": now - 60},
+ "model": {"id": "synthetic-model", "loaded": True, "context": 4096},
+ "rates": {"output_tokens_server_counter": seq * 12},
+ "work": {"active": 0, "queued": seq % 5, "waiting": 0, "slots_requested": 8,
+ "slots_effective": 8, "groups": 4,
+ "batch_sample_windows": 4, "batch_sample_rows": 4 * (3 + seq % 4),
+ "batch_sample_active_rows": 4 * min(3, 2 + seq % 3),
+ "batch_sample_span_s": 1.0, "batch_sample_age_s": 0.1,
+ "requests": [{"id": f"r{i:02d}", "state": "queued"} for i in range(70)]},
+ "topology": topology, "devices": devices,
+ "activity": {"last_seq": seq, "events": events}}
+
+ def counters(self) -> dict:
+ with self.lock:
+ return {"gets": self.gets, "http_failures": self.failures,
+ "other_methods": self.other_methods, "bytes_sent": self.bytes_sent,
+ "max_in_flight": self.max_in_flight, "instance": self.instance}
+
+
+def handler_for(service: SyntheticTelemetry):
+ class Handler(BaseHTTPRequestHandler):
+ def log_message(self, *_args):
+ pass
+
+ def do_GET(self):
+ with service.lock:
+ service.in_flight += 1
+ service.max_in_flight = max(service.max_in_flight, service.in_flight)
+ service.gets += 1
+ unavailable = service.unavailable
+ try:
+ if self.path != "/v1/telemetry":
+ self.send_error(404)
+ return
+ if unavailable:
+ with service.lock:
+ service.failures += 1
+ self.send_error(503)
+ return
+ body = json.dumps(service.snapshot(), separators=(",", ":")).encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+ with service.lock:
+ service.bytes_sent += len(body)
+ finally:
+ with service.lock:
+ service.in_flight -= 1
+
+ def do_POST(self):
+ with service.lock:
+ service.other_methods += 1
+ self.send_error(405)
+
+ return Handler
+
+
+async def soak(seconds: float, interval: float, *, exercise_ui: bool = False) -> dict:
+ try:
+ from strata_cli.monitor import MonitorApp
+ except ImportError as exc:
+ raise RuntimeError("the optional Textual monitor dependency is required") from exc
+ service = SyntheticTelemetry(exercise_ui=exercise_ui)
+ server = ThreadingHTTPServer(("127.0.0.1", 0), handler_for(service))
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ endpoint = Endpoint(f"http://127.0.0.1:{server.server_port}", timeout=1)
+ tracemalloc.start()
+ started = time.monotonic()
+ cpu_started = time.process_time()
+ events: list[str] = []
+ baseline = None
+ max_output_rate_samples = 0
+ max_batch_samples = 0
+ max_pre_admit_samples = 0
+ max_device_histories = 0
+ max_device_samples = 0
+ sensor_gap_observed = False
+ max_vram_histories = 0
+ max_vram_samples = 0
+ vram_sensor_gap_observed = False
+ resize_count = 0
+ sizes_seen: set[tuple[int, int]] = set()
+ resize_size_cycle = ((140, 44), (110, 30), (80, 24), (60, 16), (40, 12))
+ resize_step = max(1.0, min(5.0, seconds / 20))
+ next_resize = 1.0
+ next_progress = 60.0
+ outage_length = min(5.0, max(1.0, seconds / 20))
+ try:
+ app = MonitorApp(endpoint, None, interval=interval)
+ observed_states = {app.connection_state}
+ async with app.run_test(size=(80, 24)) as pilot:
+ await pilot.press("2")
+ while True:
+ elapsed = time.monotonic() - started
+ if elapsed >= seconds:
+ break
+ if baseline is None and elapsed >= min(5.0, seconds / 5):
+ baseline = tracemalloc.get_traced_memory()[0]
+ if elapsed >= seconds * 0.25 and "disconnect" not in events:
+ with service.lock:
+ service.unavailable = True
+ events.append("disconnect")
+ if elapsed >= seconds * 0.25 + outage_length and "reconnect" not in events:
+ with service.lock:
+ service.unavailable = False
+ events.append("reconnect")
+ if elapsed >= seconds * 0.5 and "restart" not in events:
+ with service.lock:
+ service.instance += 1
+ service.seq = 0
+ events.append("restart")
+ if elapsed >= seconds * 0.75 and "second_disconnect" not in events:
+ with service.lock:
+ service.unavailable = True
+ events.append("second_disconnect")
+ if elapsed >= seconds * 0.75 + outage_length and "second_reconnect" not in events:
+ with service.lock:
+ service.unavailable = False
+ events.append("second_reconnect")
+ if elapsed >= next_progress:
+ print(json.dumps({"elapsed_s": round(elapsed, 1), **service.counters()}), flush=True)
+ next_progress += 60.0
+ if exercise_ui and elapsed >= next_resize:
+ size = resize_size_cycle[resize_count % len(resize_size_cycle)]
+ await pilot.resize_terminal(*size)
+ sizes_seen.add(size)
+ resize_count += 1
+ next_resize += resize_step
+ observed_states.add(app.connection_state)
+ max_output_rate_samples = max(max_output_rate_samples, len(app.history.output_rate))
+ max_batch_samples = max(max_batch_samples, len(app.history.batch_rows))
+ max_pre_admit_samples = max(max_pre_admit_samples, len(app.history.pre_admit))
+ max_device_histories = max(max_device_histories, len(app.history.device_util))
+ max_device_samples = max(max_device_samples,
+ *(len(rows) for rows in app.history.device_util.values()), 0)
+ sensor_gap_observed |= any(rows and rows[-1] is None
+ for rows in app.history.device_util.values())
+ max_vram_histories = max(max_vram_histories, len(app.history.device_vram))
+ max_vram_samples = max(max_vram_samples,
+ *(len(rows) for rows in app.history.device_vram.values()), 0)
+ vram_sensor_gap_observed |= any(rows and rows[-1] is None
+ for rows in app.history.device_vram.values())
+ await asyncio.sleep(min(0.5, max(0.01, seconds - elapsed)))
+ await pilot.press("6")
+ await pilot.pause(0.1)
+ latest = app.latest
+ final_instance = (latest.get("instance") or {}).get("id")
+ retained_activity = len((latest.get("activity") or {}).get("events") or [])
+ retained_requests = len((latest.get("work") or {}).get("requests") or [])
+ output_rate_samples = list(app.history.output_rate)
+ valid_output_rate_samples = sum(value is not None for value in output_rate_samples)
+ valid_batch_samples = sum(value is not None for value in app.history.batch_rows)
+ valid_pre_admit_samples = sum(value is not None for value in app.history.pre_admit)
+ output_rate_instance = app.history.instance
+ monitor_recovered = app.error is None and app.failures == 0
+ await pilot.press("q")
+ process_memory = tracemalloc.get_traced_memory()[0]
+ counters = service.counters()
+ # A fresh read after detach proves the monitor did not shut down the server.
+ detached_server_readable = endpoint.snapshot()["instance"]["id"] == final_instance
+ return {"schema_version": 1, "scope": "synthetic_headless_monitor_soak",
+ "duration_s": round(time.monotonic() - started, 2), "poll_interval_s": interval,
+ "events": events, "final_instance_id": final_instance,
+ "monitor_states": sorted(observed_states),
+ "retained_activity": retained_activity, "retained_requests": retained_requests,
+ "output_rate_samples_retained": len(output_rate_samples),
+ "output_rate_valid_samples": valid_output_rate_samples,
+ "output_rate_history_max_samples": max_output_rate_samples,
+ "batch_history_max_samples": max_batch_samples,
+ "batch_history_valid_samples": valid_batch_samples,
+ "pre_admit_history_max_samples": max_pre_admit_samples,
+ "pre_admit_history_valid_samples": valid_pre_admit_samples,
+ "output_rate_history_instance": list(output_rate_instance) if output_rate_instance else None,
+ "exercise_ui": exercise_ui,
+ "resize_count": resize_count,
+ "terminal_sizes_seen": [list(size) for size in sorted(sizes_seen)],
+ "device_history_max_cards": max_device_histories,
+ "device_history_max_samples": max_device_samples,
+ "device_sensor_gap_observed": sensor_gap_observed,
+ "vram_history_max_cards": max_vram_histories,
+ "vram_history_max_samples": max_vram_samples,
+ "vram_sensor_gap_observed": vram_sensor_gap_observed,
+ "traced_memory_baseline_bytes": baseline,
+ "traced_memory_final_bytes": process_memory,
+ "traced_memory_growth_bytes": process_memory - baseline if baseline is not None else None,
+ "synthetic_memory_growth_budget_bytes": 20 * 1024 * 1024,
+ "combined_process_cpu_s": round(time.process_time() - cpu_started, 3),
+ "monitor_recovered": monitor_recovered,
+ "detached_server_readable": detached_server_readable,
+ "http": {**counters,
+ "gets_per_s": round(counters["gets"] / max(0.1, time.monotonic() - started), 3),
+ "bytes_per_s": round(counters["bytes_sent"] / max(0.1, time.monotonic() - started), 1)},
+ "passed": (set(events) == {"disconnect", "reconnect", "restart",
+ "second_disconnect", "second_reconnect"}
+ and final_instance == "synthetic-1" and retained_activity <= 32
+ and retained_requests <= 50 and 2 <= valid_output_rate_samples
+ and max_output_rate_samples <= app.history.limit
+ and 2 <= valid_batch_samples and max_batch_samples <= app.history.limit
+ and 2 <= valid_pre_admit_samples and max_pre_admit_samples <= app.history.limit
+ and output_rate_instance == ("id", final_instance)
+ and counters["other_methods"] == 0
+ and counters["max_in_flight"] <= 1 and counters["http_failures"] >= 2
+ and {"connecting", "connected", "stale"} <= observed_states
+ and monitor_recovered and detached_server_readable and baseline is not None
+ and process_memory - baseline <= 20 * 1024 * 1024
+ and (not exercise_ui or
+ (sizes_seen == set(resize_size_cycle) and resize_count >= 4
+ and max_device_histories <= 4 and max_device_samples <= app.history.limit
+ and sensor_gap_observed
+ and set(app.history.device_util) == {0, 1, 2, 3}
+ and max_vram_histories <= 4 and max_vram_samples <= app.history.limit
+ and vram_sensor_gap_observed
+ and set(app.history.device_vram) == {0, 1, 2, 3})))}
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=2)
+ tracemalloc.stop()
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description="Headless synthetic Strata Monitor soak")
+ parser.add_argument("--seconds", type=float, default=1800)
+ parser.add_argument("--interval", type=float, default=0.5)
+ parser.add_argument("--exercise-ui", action="store_true",
+ help="resize across five terminal sizes and churn selected/host card sensors")
+ parser.add_argument("--report", type=Path, required=True, help="new absolute JSON report path")
+ args = parser.parse_args(argv)
+ if not 8 <= args.seconds <= 3600 or not 0.5 <= args.interval <= 30:
+ parser.error("--seconds must be 8..3600 and --interval must be 0.5..30")
+ if args.exercise_ui and args.seconds < 30:
+ parser.error("--exercise-ui requires at least 30 seconds")
+ report_path = args.report.expanduser()
+ if not report_path.is_absolute() or report_path.exists():
+ parser.error("--report must be an absolute new file")
+ result = asyncio.run(soak(args.seconds, args.interval, exercise_ui=args.exercise_ui))
+ report_path.parent.mkdir(parents=True, exist_ok=True)
+ descriptor = os.open(report_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ with os.fdopen(descriptor, "w", encoding="utf-8") as stream:
+ json.dump(result, stream, indent=2)
+ stream.write("\n")
+ print(json.dumps({"report": str(report_path), "passed": result["passed"]}), flush=True)
+ return 0 if result["passed"] else 6
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tools/portable_monitor_pty_smoke.py b/tools/portable_monitor_pty_smoke.py
new file mode 100644
index 000000000..a814c974d
--- /dev/null
+++ b/tools/portable_monitor_pty_smoke.py
@@ -0,0 +1,127 @@
+#!/usr/bin/env python3
+"""Check packaged Monitor detach and terminal restoration on a POSIX PTY.
+
+Run with the Python environment that has the optional Textual dependency.
+This exercises an actual terminal session against loopback fake telemetry; it
+does not qualify a physical terminal, Windows console or inference engine.
+"""
+
+from __future__ import annotations
+
+import argparse
+import fcntl
+import hashlib
+import json
+import os
+import platform
+import pty
+import select
+import struct
+import subprocess
+import sys
+import termios
+import threading
+import time
+import urllib.request
+from pathlib import Path
+
+from portable_monitor_smoke import _server
+
+
+def _case(bundle: Path, url: str, paths: list[str], key: bytes) -> dict:
+ master, slave = pty.openpty()
+ process = None
+ before_count = len(paths)
+ try:
+ fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", 30, 110, 0, 0))
+ before = termios.tcgetattr(slave)
+ env = os.environ.copy()
+ env["TERM"] = "xterm-256color"
+ process = subprocess.Popen(
+ [sys.executable, "-I", str(bundle), "monitor", "--url", url,
+ "--interval", "0.5", "--glyphs", "ascii"],
+ stdin=slave, stdout=slave, stderr=slave, close_fds=True, env=env)
+ output = bytearray()
+ bytes_read = 0
+ sent = False
+ active_raw = False
+ deadline = time.monotonic() + 12
+ while time.monotonic() < deadline:
+ ready, _, _ = select.select([master], [], [], 0.1)
+ if ready:
+ try:
+ chunk = os.read(master, 65536)
+ except OSError:
+ chunk = b""
+ bytes_read += len(chunk)
+ output.extend(chunk)
+ if len(output) > 65536:
+ del output[:-65536]
+ if not sent and len(paths) > before_count and b"STRATA" in output:
+ active = termios.tcgetattr(slave)
+ active_raw = not bool(active[3] & termios.ICANON) and not bool(active[3] & termios.ECHO)
+ if active_raw:
+ os.write(master, key)
+ sent = True
+ if process.poll() is not None:
+ break
+ if process.poll() is None:
+ process.kill()
+ exit_code = process.wait(timeout=3)
+ restored = termios.tcgetattr(slave) == before
+ if exit_code != 0 or not sent or not active_raw or not restored:
+ raise RuntimeError(f"PTY detach failed: key={key!r}, exit={exit_code}, "
+ f"sent={sent}, raw={active_raw}, restored={restored}")
+ return {"key": "ctrl-c" if key == b"\x03" else "q", "exit_code": exit_code,
+ "terminal_went_raw": active_raw, "terminal_restored": restored,
+ "telemetry_gets": len(paths) - before_count, "terminal_output_bytes": bytes_read}
+ finally:
+ if process is not None and process.poll() is None:
+ process.kill()
+ process.wait(timeout=3)
+ os.close(master)
+ os.close(slave)
+
+
+def smoke(bundle: Path) -> dict:
+ bundle = bundle.resolve(strict=True)
+ server, paths, _ = _server()
+ worker = threading.Thread(target=server.serve_forever, daemon=True)
+ worker.start()
+ try:
+ url = f"http://127.0.0.1:{server.server_port}"
+ cases = [_case(bundle, url, paths, key) for key in (b"q", b"\x03")]
+ with urllib.request.urlopen(url + "/v1/telemetry", timeout=3) as response:
+ server_alive = response.status == 200
+ finally:
+ server.shutdown()
+ server.server_close()
+ worker.join(timeout=3)
+ if not server_alive or any(path != "GET /v1/telemetry" for path in paths):
+ raise RuntimeError("Monitor detach changed or stopped the telemetry server")
+ return {"schema_version": 1, "scope": "portable_monitor_posix_pty_smoke",
+ "bundle_sha256": hashlib.sha256(bundle.read_bytes()).hexdigest(),
+ "python": platform.python_version(), "platform": platform.platform(),
+ "cases": cases, "server_alive_after_detach": True,
+ "http_gets": len(paths), "other_http_methods": 0, "passed": True}
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__)
+ ap.add_argument("--bundle", type=Path, required=True)
+ ap.add_argument("--report", type=Path, required=True, help="new absolute JSON report file")
+ args = ap.parse_args()
+ if os.name != "posix":
+ ap.error("this pseudo-terminal check requires a POSIX host")
+ if not args.report.is_absolute() or args.report.exists():
+ ap.error("--report must be a new absolute file path")
+ report = smoke(args.bundle)
+ with args.report.open("x", encoding="utf-8") as stream:
+ json.dump(report, stream, indent=2, sort_keys=True)
+ stream.write("\n")
+ print(json.dumps({"report": str(args.report), "passed": True}))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tools/portable_monitor_smoke.py b/tools/portable_monitor_smoke.py
new file mode 100644
index 000000000..5f6f42ad8
--- /dev/null
+++ b/tools/portable_monitor_smoke.py
@@ -0,0 +1,255 @@
+#!/usr/bin/env python3
+"""Exercise one portable Monitor bundle with a local fake server.
+
+Run this on each target OS/Python before release. It checks the client and the
+local bundle lifecycle. --interactive also checks packaged Textual rendering.
+Neither mode exercises the engine or GPU drivers.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import platform
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+
+
+BUILDER = Path(__file__).resolve().parents[1] / "packaging" / "monitor_bundle.py"
+INTERACTIVE_CODE = r'''
+import asyncio
+import io
+import json
+import sys
+
+sys.path.insert(0, sys.argv[1])
+from rich.console import Console
+from textual.widgets import Static
+from strata_cli.client import Endpoint
+from strata_cli.monitor import MonitorApp
+from strata_cli.dashboard import render_dashboard
+from strata_cli.detail_dashboard import render_detail_dashboard
+import strata_cli.monitor as monitor_module
+
+async def main():
+ source = str(monitor_module.__file__).replace("\\", "/")
+ bundle_path = sys.argv[1].replace("\\", "/")
+ if not source.startswith(bundle_path + "/"):
+ raise RuntimeError("interactive Monitor was not imported from the bundle")
+ app = MonitorApp(Endpoint(sys.argv[2]), None, interval=0.5,
+ theme="dark", color="never", glyphs="ascii")
+ async with app.run_test(size=(110, 30)) as pilot:
+ for _ in range(30):
+ if app.connection_state == "connected":
+ break
+ await pilot.pause(0.1)
+ if app.connection_state != "connected":
+ raise RuntimeError("interactive Monitor did not connect")
+ output = io.StringIO()
+ Console(file=output, width=110, color_system=None).print(
+ app.query_one("#content", Static).content)
+ shown = output.getvalue()
+ if not all(title in shown for title in
+ ("SERVING", "PERFORMANCE", "BATCHING / PARALLEL",
+ "HARDWARE", "REQUESTS", "ACTIVITY")):
+ raise RuntimeError("packaged one-screen Overview is incomplete")
+ if (app.latest.get("model") or {}).get("id") != "portable-smoke-model":
+ raise RuntimeError("interactive Monitor showed the wrong model")
+ wide = io.StringIO()
+ Console(file=wide, width=140, color_system=None).print(render_dashboard(
+ app.latest, width=138, height=42, history=app.history,
+ glyphs="ascii", color=False))
+ if not all(title in wide.getvalue() for title in
+ ("THROUGHPUT", "GPUS", "CONTEXT / BATCHING", "PARALLEL SLOTS", "REQUESTS")):
+ raise RuntimeError("packaged wide visual Overview is incomplete")
+ for view, title in (("serving", "REQUEST FLOW"), ("requests", "IN FLIGHT"),
+ ("engine", "STAGES / HOST SPAN"), ("hardware", "GPU CARDS"),
+ ("logs", "RECENT EVENT TIMELINE")):
+ detail = io.StringIO()
+ Console(file=detail, width=140, color_system=None).print(render_detail_dashboard(
+ app.latest, view, width=138, height=42, history=app.history,
+ glyphs="ascii", color=False))
+ if title not in detail.getvalue():
+ raise RuntimeError("packaged visual " + view + " page is incomplete")
+ await pilot.press("q")
+ print(json.dumps({"connected": True, "overview_panels": 6,
+ "wide_visual": True, "visual_details": 5,
+ "imported_from_bundle": True, "detached": True}))
+
+asyncio.run(main())
+'''
+
+
+def _run(*argv: str) -> dict:
+ result = subprocess.run([sys.executable, "-I", "-S", *argv],
+ capture_output=True, text=True, timeout=20, check=False)
+ if result.returncode or result.stderr.strip():
+ raise RuntimeError(f"isolated command failed ({result.returncode}): {result.stderr.strip()}")
+ try:
+ return json.loads(result.stdout)
+ except json.JSONDecodeError as exc:
+ raise RuntimeError("isolated command did not return one JSON record") from exc
+
+
+def _server() -> tuple[ThreadingHTTPServer, list[str], threading.Event]:
+ paths: list[str] = []
+ malformed = threading.Event()
+
+ class TelemetryHandler(BaseHTTPRequestHandler):
+ def do_GET(self) -> None:
+ paths.append("GET " + self.path)
+ if self.path != "/v1/telemetry":
+ self.send_error(404)
+ return
+ body = json.dumps({
+ "schema_version": 1, "sampled_at": time.time(),
+ "instance": {"id": "portable-smoke", "state": "ready"},
+ "model": {"id": "portable-smoke-model", "loaded": True},
+ "work": {"active": 0, "queued": 0, "waiting": 0,
+ "slots_requested": 1, "slots_effective": 1, "groups": 1,
+ "slots": [{"slot": 0, "state": "idle", "group": 0}]},
+ "topology": {"mode": "single", "selected_devices": []},
+ "rates": {"output_tokens_server_counter": 0},
+ "devices": [], "quality": {"telemetry": "available"},
+ }).encode() if not malformed.is_set() else b"[" * 1100 + b"0" + b"]" * 1100
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def _reject(self) -> None:
+ paths.append(self.command + " " + self.path)
+ self.send_error(405)
+
+ do_POST = do_PUT = do_PATCH = do_DELETE = do_HEAD = do_OPTIONS = do_TRACE = _reject
+
+ def log_message(self, *args: object) -> None:
+ pass
+
+ return ThreadingHTTPServer(("127.0.0.1", 0), TelemetryHandler), paths, malformed
+
+
+def _malformed_response(bundle: Path, url: str) -> None:
+ result = subprocess.run([sys.executable, "-I", "-S", str(bundle),
+ "status", "--url", url, "--json"],
+ capture_output=True, text=True, timeout=20, check=False)
+ if result.returncode != 3 or result.stderr:
+ raise RuntimeError("deeply nested telemetry escaped the client error boundary")
+ try:
+ response = json.loads(result.stdout)
+ except json.JSONDecodeError as exc:
+ raise RuntimeError("malformed telemetry did not return one JSON error") from exc
+ if (response.get("ok") is not False or
+ (response.get("error") or {}).get("message") != "server returned malformed JSON telemetry"):
+ raise RuntimeError("deeply nested telemetry returned an unexpected error")
+
+
+def _interactive(bundle: Path, url: str) -> dict:
+ result = subprocess.run([sys.executable, "-I", "-c", INTERACTIVE_CODE, str(bundle), url],
+ capture_output=True, text=True, timeout=20, check=False)
+ if result.returncode:
+ raise RuntimeError(f"packaged interactive Monitor failed ({result.returncode}): "
+ f"{result.stderr.strip()[-2000:]}")
+ try:
+ report = json.loads(result.stdout)
+ except json.JSONDecodeError as exc:
+ raise RuntimeError("interactive Monitor did not return one JSON record") from exc
+ if report != {"connected": True, "overview_panels": 6, "wide_visual": True,
+ "visual_details": 5,
+ "imported_from_bundle": True, "detached": True}:
+ raise RuntimeError("packaged interactive Monitor smoke was incomplete")
+ return report
+
+
+def smoke(bundle: Path, *, interactive: bool = False) -> dict:
+ bundle = bundle.resolve(strict=True)
+ manifest = _run(str(BUILDER), "verify", str(bundle))
+ expected_sha = hashlib.sha256(bundle.read_bytes()).hexdigest()
+ if manifest.get("sha256") != expected_sha:
+ raise RuntimeError("bundle digest changed after verification")
+
+ server, paths, malformed = _server()
+ worker = threading.Thread(target=server.serve_forever, daemon=True)
+ worker.start()
+ try:
+ url = f"http://127.0.0.1:{server.server_port}"
+ one_shot = _run(str(bundle), "monitor", "--url", url, "--once", "--json")
+ if (one_shot.get("ok") is not True or
+ (one_shot.get("snapshot") or {}).get("model", {}).get("id") != "portable-smoke-model"):
+ raise RuntimeError("one-shot monitor returned the wrong model or failed")
+
+ with tempfile.TemporaryDirectory(prefix="strata-portable-smoke-") as scratch:
+ target = Path(scratch) / "monitor"
+ preview = _run(str(BUILDER), "install", str(bundle), "--target", str(target), "--plan")
+ if preview.get("sha256") != expected_sha or preview.get("would_install") is not True:
+ raise RuntimeError("bundle install preview did not bind the candidate digest")
+ installed = _run(str(BUILDER), "install", str(bundle), "--target", str(target),
+ "--if-candidate-sha256", expected_sha)
+ if installed.get("installed") is not True:
+ raise RuntimeError("bundle install did not complete")
+ installed_bundle = target / bundle.name
+ _run(str(BUILDER), "verify", str(installed_bundle))
+ status = _run(str(installed_bundle), "status", "--url", url, "--json")
+ if (status.get("ok") is not True or
+ (status.get("snapshot") or {}).get("instance", {}).get("id") != "portable-smoke"):
+ raise RuntimeError("installed client did not reach the fake server")
+ removal = _run(str(BUILDER), "uninstall", "--target", str(target), "--plan")
+ if removal.get("sha256") != expected_sha or removal.get("would_remove") is not True:
+ raise RuntimeError("bundle removal preview did not bind the installed digest")
+ removed = _run(str(BUILDER), "uninstall", "--target", str(target),
+ "--if-active-sha256", expected_sha)
+ if removed.get("removed") is not True or target.exists():
+ raise RuntimeError("bundle uninstall left an installed directory")
+ malformed.set()
+ _malformed_response(bundle, url)
+ malformed.clear()
+ interactive_report = _interactive(bundle, url) if interactive else None
+ finally:
+ server.shutdown()
+ server.server_close()
+ worker.join(timeout=5)
+
+ if (paths[:2] != ["GET /v1/telemetry", "GET /v1/telemetry"] or
+ any(path != "GET /v1/telemetry" for path in paths) or
+ (interactive and len(paths) < 4) or (not interactive and len(paths) != 3)):
+ raise RuntimeError(f"unexpected client HTTP operations: {paths}")
+ report = {"schema_version": 1, "scope": "portable_monitor_stdlib_smoke",
+ "bundle_sha256": expected_sha, "python": platform.python_version(),
+ "platform": platform.platform(), "isolated_no_site_packages": True,
+ "one_shot_monitor": True, "installed_status": True,
+ "digest_pinned_install_uninstall": True,
+ "deep_json_error": True,
+ "http_gets": len(paths),
+ "other_http_methods": 0, "passed": True}
+ if interactive_report is not None:
+ report["interactive"] = interactive_report
+ return report
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__)
+ ap.add_argument("--bundle", type=Path, required=True)
+ ap.add_argument("--report", type=Path, required=True,
+ help="new absolute JSON report file")
+ ap.add_argument("--interactive", action="store_true",
+ help="also load the packaged Textual Overview in a headless terminal")
+ args = ap.parse_args()
+ if not args.report.is_absolute() or args.report.exists():
+ ap.error("--report must be a new absolute file path")
+ report = smoke(args.bundle, interactive=args.interactive)
+ with args.report.open("x", encoding="utf-8") as stream:
+ json.dump(report, stream, indent=2, sort_keys=True)
+ stream.write("\n")
+ print(json.dumps({"report": str(args.report), "passed": True}))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tools/test_calibrate.py b/tools/test_calibrate.py
index 7ce1bdd0f..f9d98c48e 100644
--- a/tools/test_calibrate.py
+++ b/tools/test_calibrate.py
@@ -9,6 +9,7 @@ import json
import os
import sys
import tempfile
+import threading
import unittest
from pathlib import Path
from unittest import mock
@@ -57,6 +58,53 @@ class Calibrate(unittest.TestCase):
res, _ = self.run_with(lambda f, p, w: 50.0)
self.assertEqual(res["settings"], {})
+ def test_measure_reports_bounded_stages_and_stops_between_samples(self):
+ events = []
+ stopped = threading.Event()
+
+ def progress(stage, completed, total):
+ events.append((stage, completed, total))
+ if stage == "pcie_share" and completed == 1:
+ stopped.set()
+
+ with self.assertRaises(CAL.CalibrationCancelled):
+ CAL.measure(BASE, [[1, 2, 3]] * 3,
+ lambda args: FakeEngine(args, lambda *_: 50.0),
+ say=lambda *_: None, progress=progress, cancel_event=stopped)
+ self.assertIn(("loading", 1, 1), events)
+ self.assertIn(("pcie_share", 1, len(CAL.PCIE_FRACS) * CAL.SWEEP_ROUNDS), events)
+ self.assertNotIn("draft_floor", [stage for stage, _, _ in events])
+
+ def test_active_generation_receives_shared_cancel_event(self):
+ stopped = threading.Event()
+ seen = []
+
+ class Engine:
+ def generate(self, ids, max_new, sampling, cancel):
+ seen.append(cancel)
+ cancel.set()
+ yield None
+
+ session = CAL.Session(Engine(), [[1, 2, 3]], stopped)
+ with self.assertRaises(CAL.CalibrationCancelled):
+ session.rate()
+ self.assertEqual(seen, [stopped])
+
+ def test_successful_sweep_covers_every_progress_stage(self):
+ events = []
+ CAL.measure(BASE, [[1, 2, 3]] * 3,
+ lambda args: FakeEngine(args, lambda *_: 50.0),
+ say=lambda *_: None, progress=lambda *item: events.append(item))
+ stages = list(dict.fromkeys(stage for stage, _, _ in events))
+ self.assertEqual(stages, ["loading", "pcie_share", "draft_floor", "confirmation",
+ "cpu_workers", "expert_tier"])
+ for stage in stages:
+ readings = [(done, total) for current, done, total in events if current == stage]
+ self.assertEqual(readings[0][0], 0)
+ self.assertEqual(readings[-1][0], readings[-1][1])
+ self.assertTrue(all(before[0] <= after[0] and before[1] == after[1]
+ for before, after in zip(readings, readings[1:])))
+
def test_small_gain_is_noise(self):
# 2% better at pcie 0.35: below MIN_GAIN, so the default stays
res, _ = self.run_with(lambda f, p, w: 51.0 if abs(f - 0.35) < 1e-6 else 50.0)