Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(regression): establish ownership at write time (#1887)

Call White902a97a8824e
diff --git a/docs/plans/regression-write-ownership.md b/docs/plans/regression-write-ownership.md
new file mode 100644
index 000000000..2e984cb20
--- /dev/null
+++ b/docs/plans/regression-write-ownership.md
@@ -0,0 +1,42 @@
+# Regression Write Ownership
+
+## Problem
+
+Every local Incus deployment recursively changes ownership of the service home,
+source, and dependency environments. An observed master update spent about half
+an hour walking existing runtime directories. The shared VM disk saturated and
+another regression instance's Model Hub management health request timed out.
+
+## Invariants
+
+- Preparing an existing instance visits only its fixed service directories;
+ existing descendants keep their contents, permissions, and ownership metadata.
+- Source extraction, dependency installation, and state seeding create files as
+ the service user. Ownership is established by the writer, not a later walk.
+- New base images install backends as the service user. First boot alone repairs
+ root-owned backend installation paths inherited from older images; it never
+ recursively changes ownership of the home or unrelated runtime directories.
+- Source sync preserves the existing exclusion and stale-file removal contract.
+- A usable Python environment is reused. Creating a missing environment forces
+ dependency installation regardless of prior fingerprints; creation failures
+ stop deployment.
+- Health failures identify the local endpoint, bounded failure category, HTTP
+ status when available, and elapsed time. Logs contain no response bodies,
+ credential values, or arbitrary upstream error text. Repeated identical
+ failures do not create repeated warnings; recovery is recorded.
+
+## Scope
+
+Update the Incus runner and focused tests, plus Model Hub health diagnostics and
+their tests. Preserve product state, reset semantics, runtime health values,
+health deadlines, and deployment fingerprints. Do not move VM storage or change
+machine resources as part of this change.
+
+## Validation
+
+- Execute generated shell commands against test-owned filesystem trees.
+- Verify source payloads, modes, symlinks, and preserved descendants.
+- Exercise fresh, existing, and missing Python environment paths.
+- Test both health endpoints, failure classification, redaction, and recovery.
+- Run focused pytest and Ruff checks, then the required PR review and CI gates.
+- Verify the deployment path in local Incus with accumulated state preserved.
diff --git a/scripts/incus_regression.py b/scripts/incus_regression.py
index 418f655d8..a8eb3bf11 100644
--- a/scripts/incus_regression.py
+++ b/scripts/incus_regression.py
@@ -1308,6 +1308,30 @@ def regression_service_unit() -> str:
).rstrip()
+def prepare_service_directories_command() -> str:
+ """Establish writable roots without visiting existing runtime contents."""
+ directories = shlex.join((SERVICE_HOME, "/opt/avibe", SOURCE_DIR, VENV_DIR, METADATA_DIR, AVIBE_HOME))
+ return f"mkdir -p {directories} && chown -h {SERVICE_USER}:{SERVICE_USER} {directories}"
+
+
+def legacy_image_ownership_command() -> str:
+ """Repair root-owned backend installs from old images on first boot only."""
+ paths = shlex.join(f"{SERVICE_HOME}/{name}" for name in (".local/bin", ".npm-global", ".npmrc", ".npm", ".opencode"))
+ return textwrap.dedent(
+ f"""\
+ set -eu
+ if [ -d {SERVICE_HOME}/.local ]; then
+ chown -h {SERVICE_USER}:{SERVICE_USER} {SERVICE_HOME}/.local
+ fi
+ for path in {paths}; do
+ if [ -e "$path" ] && [ "$(stat -c %u "$path")" = 0 ]; then
+ chown -hR {SERVICE_USER}:{SERVICE_USER} "$path"
+ fi
+ done
+ """
+ ).strip()
+
+
def cloud_init_user_data() -> str:
service = regression_service_unit()
helper = textwrap.dedent(
@@ -1352,8 +1376,8 @@ def cloud_init_user_data() -> str:
" content: |",
yaml_block(helper),
"runcmd:",
- f" - [mkdir, -p, {SOURCE_DIR}, {VENV_DIR}, {METADATA_DIR}, {AVIBE_HOME}]",
- f" - [chown, -R, {SERVICE_USER}:{SERVICE_USER}, {SERVICE_HOME}, /opt/avibe, {METADATA_DIR}]",
+ f" - {json.dumps(prepare_service_directories_command())}",
+ f" - {json.dumps(legacy_image_ownership_command())}",
f" - [ln, -sfn, {AVIBE_HOME}, {LEGACY_HOME}]",
" - [systemctl, daemon-reload]",
f'final_message: "Avibe regression base is ready."',
@@ -1523,9 +1547,8 @@ def ensure_project_and_instance(
target,
(
"if command -v cloud-init >/dev/null 2>&1; then cloud-init status --wait || true; fi; "
- f"mkdir -p {SOURCE_DIR} {VENV_DIR} {METADATA_DIR} {AVIBE_HOME}; "
- f"chown -R {SERVICE_USER}:{SERVICE_USER} {SERVICE_HOME} /opt/avibe {METADATA_DIR}; "
- f"ln -sfn {AVIBE_HOME} {LEGACY_HOME}; "
+ f"{prepare_service_directories_command()} && "
+ f"ln -sfn {AVIBE_HOME} {LEGACY_HOME} && "
"systemctl daemon-reload"
),
remote=remote,
@@ -1702,13 +1725,11 @@ def sync_source(
f"if [ -d {quoted_ui} ]; then find {quoted_ui} -mindepth 1 -maxdepth 1 {keep} -exec rm -rf {{}} +; fi"
)
runner.run(root_exec(target, f"mkdir -p {quoted_source} && {wipe}", remote=remote))
- runner.run(root_exec(target, f"mkdir -p {quoted_source} && chown -R {SERVICE_USER}:{SERVICE_USER} /opt/avibe", remote=remote))
tar_bytes = b"" if runner.dry_run else build_source_tar(repo_root, include_ui_dist=include_ui_dist)
runner.run(
- incus("exec", remote_ref(remote, target.instance), "--", "tar", "-C", SOURCE_DIR, "-xf", "-", project=target.project),
+ tenant_exec(target, f"tar --no-same-owner -C {quoted_source} -xf -", remote=remote),
input_bytes=tar_bytes,
)
- runner.run(root_exec(target, f"chown -R {SERVICE_USER}:{SERVICE_USER} {shlex.quote(SOURCE_DIR)}", remote=remote))
def stop_service_for_update(runner: Runner, target: RegressionTarget, *, remote: str | None) -> None:
@@ -2182,12 +2203,11 @@ def run_prepare_state(runner: Runner, target: RegressionTarget, *, reset_mode: s
)
)
runner.run(
- root_exec(
+ tenant_exec(
target,
f"mkdir -p {AVIBE_HOME} && "
- f"cp -a /home/{SERVICE_USER}/.regression-seed/home/. {SERVICE_HOME}/ && "
- f"chown -R {SERVICE_USER}:{SERVICE_USER} {SERVICE_HOME} && "
- f"ln -sfn {AVIBE_HOME} {LEGACY_HOME} && chown -h {SERVICE_USER}:{SERVICE_USER} {LEGACY_HOME}",
+ f"cp -a --no-preserve=ownership /home/{SERVICE_USER}/.regression-seed/home/. {SERVICE_HOME}/ && "
+ f"ln -sfn {AVIBE_HOME} {LEGACY_HOME}",
remote=remote,
)
)
@@ -2266,10 +2286,20 @@ def update_dependencies_and_build(
precisely because the fingerprint already matched. A key is absent only when
the run never looked, which is what ``--no-build-ui`` does to the UI.
"""
- runner.run(root_exec(target, f"python3 -m venv {shlex.quote(VENV_DIR)} || true", remote=remote))
- runner.run(root_exec(target, f"chown -R {SERVICE_USER}:{SERVICE_USER} {shlex.quote(VENV_DIR)}", remote=remote))
+ venv = shlex.quote(VENV_DIR)
+ venv_exists = runner.run(
+ tenant_exec(
+ target,
+ f"test -f {venv}/pyvenv.cfg && test -x {venv}/bin/python && test -x {venv}/bin/pip",
+ remote=remote,
+ ),
+ check=False,
+ ).returncode == 0
+ if not venv_exists:
+ runner.run(tenant_exec(target, f"python3 -m venv {venv}", remote=remote))
python_changed = (
force_deps
+ or not venv_exists
or previous_fingerprints.get("python") != next_fingerprints.get("python")
or not previous_fingerprints
)
@@ -2449,37 +2479,33 @@ def cmd_build_base(args: argparse.Namespace) -> int:
apt-get install -y bash ca-certificates curl git build-essential python3 python3-pip python3-venv rsync sudo tmux
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt-get install -y nodejs
- # Install the agent backends under the service user's home so the
- # non-root avibe service can self-update them (`claude update`, etc.).
- # Root-global installs under /usr are not writable by the avibe user,
- # which is exactly what breaks self-update in regression. These land
- # root-owned at build time and are made avibe-owned per instance by the
- # `chown -R avibe:avibe /home/avibe` in cloud-init runcmd /
- # ensure_project_and_instance; the service PATH already prefers
- # /home/avibe/.local/bin over /usr.
- avibe_home=/home/avibe
+ # Backends must be service-owned at creation so their updaters
+ # stay writable without a recursive ownership repair at deployment.
+ id -u avibe >/dev/null 2>&1 || useradd --create-home --shell /bin/bash --groups sudo avibe
+ sudo -H -u avibe -- bash -s <<'AVIBE_BACKENDS'
+ set -euo pipefail
+ avibe_home="$HOME"
mkdir -p "$avibe_home/.local/bin" "$avibe_home/.npm-global"
# Persist a user-writable npm prefix so claude-code/codex install here
# AND future npm-based self-updates by the avibe user stay writable.
printf 'prefix=%s/.npm-global\n' "$avibe_home" > "$avibe_home/.npmrc"
- HOME="$avibe_home" npm install -g @anthropic-ai/claude-code @openai/codex
+ npm install -g @anthropic-ai/claude-code @openai/codex
ln -sf "$avibe_home/.npm-global/bin/claude" "$avibe_home/.local/bin/claude"
ln -sf "$avibe_home/.npm-global/bin/codex" "$avibe_home/.local/bin/codex"
# OpenCode installs into the service user's home via its own updater.
- # HOME must be set on the piped `bash` (the installer), not on `curl`.
- curl -fsSL https://opencode.ai/install | HOME="$avibe_home" bash -s -- --no-modify-path
+ curl -fsSL https://opencode.ai/install | bash -s -- --no-modify-path
if [ ! -x "$avibe_home/.opencode/bin/opencode" ]; then
echo "OpenCode installer did not produce an opencode binary" >&2
exit 1
fi
ln -sf "$avibe_home/.opencode/bin/opencode" "$avibe_home/.local/bin/opencode"
- # askill stays system-global: it is a bootstrap dependency, not a
- # self-updated agent backend.
- curl -fsSL https://askill.sh | sh -s -- -b /usr/local/bin
export PATH="$avibe_home/.local/bin:$PATH"
claude --version
codex --version
opencode --version
+ AVIBE_BACKENDS
+ # askill is a system-global bootstrap dependency, not a backend.
+ curl -fsSL https://askill.sh | sh -s -- -b /usr/local/bin
askill --version
node --version
npm --version
diff --git a/tests/test_incus_regression.py b/tests/test_incus_regression.py
index cb9b668f5..413887cb8 100644
--- a/tests/test_incus_regression.py
+++ b/tests/test_incus_regression.py
@@ -7,6 +7,7 @@ import importlib.util
import json
import os
import shlex
+import stat
import subprocess
import sys
import tarfile
@@ -357,6 +358,69 @@ def test_cloud_init_configures_systemd_service_without_source_code() -> None:
assert "/opt/avibe/source" in data
assert "/home/avibe/.vibe_remote" in data
assert "libreoffice-nogui" not in data
+ assert json.dumps(incus_regression.legacy_image_ownership_command()) in data
+
+
+def test_service_directory_preparation_preserves_existing_descendants(tmp_path: Path) -> None:
+ roots = (tmp_path / "home", tmp_path / "install", tmp_path / "metadata")
+ script = incus_regression.prepare_service_directories_command()
+ for original, replacement in zip(
+ (incus_regression.SERVICE_HOME, "/opt/avibe", incus_regression.METADATA_DIR), roots,
+ ):
+ script = script.replace(original, shlex.quote(str(replacement)))
+ script = script.replace("avibe:avibe", f"{os.getuid()}:{os.getgid()}")
+ subprocess.run(["bash", "-c", script], check=True)
+ owned_roots = {path for root in roots for path in (root, *root.rglob("*"))}
+ for root in owned_roots:
+ nested = root / "existing" / "future-runtime"
+ nested.mkdir(parents=True)
+ private = nested / "private"
+ private.write_text("preserved", encoding="utf-8")
+ private.chmod(0o600)
+ (nested / "link").symlink_to(private)
+ roots[0].chmod(0o700)
+ descendants = {path for root in roots for path in root.rglob("*")} - owned_roots
+
+ def metadata(path: Path) -> tuple[int, int, int, int]:
+ value = path.lstat()
+ return value.st_uid, value.st_gid, value.st_mode, value.st_ctime_ns
+
+ before = {path: metadata(path) for path in descendants}
+ subprocess.run(["bash", "-c", script], check=True)
+
+ assert {path: metadata(path) for path in descendants} == before
+ assert stat.S_IMODE(roots[0].stat().st_mode) == 0o700
+ assert all(path.stat().st_uid == os.getuid() for path in owned_roots)
+
+
+def test_legacy_image_repair_only_visits_root_owned_backend_installs(tmp_path: Path) -> None:
+ home = tmp_path / "home"
+ files = {}
+ for name in (".local/bin", ".npm-global", ".npm", ".avibe/runtime", ".local/share/future-runtime"):
+ directory = home / name
+ directory.mkdir(parents=True)
+ files[name] = directory / "existing"
+ files[name].write_text("preserved", encoding="utf-8")
+ (home / ".npmrc").write_text("prefix=preserved", encoding="utf-8")
+ (home / ".opencode").symlink_to(home / ".avibe/runtime", target_is_directory=True)
+ (home / ".npm-global/link").symlink_to(files[".avibe/runtime"])
+ script = incus_regression.legacy_image_ownership_command().replace(
+ incus_regression.SERVICE_HOME, str(home),
+ ).replace("avibe:avibe", f"{os.getuid()}:{os.getgid()}")
+ # Emulate legacy image ownership without requiring root on the test host.
+ stat = 'stat() { case "$3" in */.npm-global|*/.npmrc|*/.opencode) echo 0;; *) echo 1;; esac; };\n'
+ before = {name: path.stat().st_ctime_ns for name, path in files.items()}
+ subprocess.run(["bash", "-c", stat + script], check=True)
+
+ assert files[".npm-global"].stat().st_ctime_ns != before[".npm-global"]
+ assert {name: path.stat().st_ctime_ns for name, path in files.items() if name != ".npm-global"} == {
+ name: value for name, value in before.items() if name != ".npm-global"
+ }
+ assert all(path.read_text(encoding="utf-8") == "preserved" for path in files.values())
+ assert (home / ".opencode").is_symlink()
+ migrated = files[".npm-global"].stat().st_ctime_ns
+ subprocess.run(["bash", "-c", "stat() { echo 1; };\n" + script], check=True)
+ assert files[".npm-global"].stat().st_ctime_ns == migrated
def test_project_config_marks_regression_target() -> None:
@@ -748,6 +812,7 @@ def test_existing_instance_is_not_reinitialised() -> None:
rendered = [" ".join(command) for command, _ in commands]
assert not any(" init " in f" {command} " for command in rendered)
assert not any("soffice" in command or "libreoffice" in command for command in rendered)
+ assert not any("chown -hR" in command or "chown -R" in command for command in rendered)
def test_build_base_uses_publishable_temp_instance() -> None:
@@ -782,17 +847,21 @@ def test_build_base_uses_publishable_temp_instance() -> None:
assert "--ephemeral" not in joined
assert "incus launch images:ubuntu/24.04/cloud avibe-regression-base-build --storage default --network incusbr0" in joined
assert "https://deb.nodesource.com/setup_20.x" in joined
- assert 'HOME="$avibe_home" npm install -g @anthropic-ai/claude-code @openai/codex' in joined
+ assert "useradd --create-home --shell /bin/bash --groups sudo avibe" in joined
+ backend_install = joined.split("sudo -H -u avibe -- bash -s <<'AVIBE_BACKENDS'\n", 1)[1].split("\nAVIBE_BACKENDS", 1)[0]
+ assert 'avibe_home="$HOME"' in backend_install
+ assert 'npm install -g @anthropic-ai/claude-code @openai/codex' in backend_install
assert "https://askill.sh | sh -s -- -b /usr/local/bin" in joined
assert ".npm-global" in joined
assert 'ln -sf "$avibe_home/.npm-global/bin/claude" "$avibe_home/.local/bin/claude"' in joined
assert 'ln -sf "$avibe_home/.npm-global/bin/codex" "$avibe_home/.local/bin/codex"' in joined
- assert 'curl -fsSL https://opencode.ai/install | HOME="$avibe_home" bash -s -- --no-modify-path' in joined
+ assert 'curl -fsSL https://opencode.ai/install | bash -s -- --no-modify-path' in backend_install
assert 'ln -sf "$avibe_home/.opencode/bin/opencode" "$avibe_home/.local/bin/opencode"' in joined
# Backends must not be root-global: the non-root avibe user owns them and self-updates.
assert "/usr/local/bin/opencode" not in joined
assert "cloud-init clean --logs || true" in joined
assert "incus publish avibe-regression-base-build --alias avibe-regression-base-current" in joined
+ subprocess.run(["bash", "-n"], input=next(command[-1] for command in commands if "apt-get update" in command[-1]), text=True, check=True)
def test_source_exclude_drops_runtime_and_dependency_dirs() -> None:
@@ -1032,6 +1101,49 @@ def test_sync_source_clears_stale_files_even_without_clean(tmp_path: Path) -> No
assert f"! -name {kept}" in joined
+def test_source_sync_writes_as_service_user_and_preserves_unshipped_trees(tmp_path: Path) -> None:
+ source = tmp_path / "source"
+ deployed = tmp_path / "deployed"
+ source.mkdir()
+ deployed.mkdir()
+ (source / "ui").mkdir()
+ (source / "ui" / "entry.js").write_text("new source", encoding="utf-8")
+ (source / "tool").write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
+ (source / "tool").chmod(0o755)
+ (source / "tool-link").symlink_to("tool")
+ seed_source_tree(deployed)
+ preserved = {
+ path: path.lstat()
+ for name in incus_regression.UI_NON_SOURCE_DIRS
+ for path in (deployed / "ui" / name).rglob("*")
+ }
+ archive_commands = []
+
+ class LocalRunner:
+ dry_run = False
+
+ def run(self, command, **kwargs):
+ shell_index = command.index("-lc") + 1
+ script = command[shell_index].replace(incus_regression.SOURCE_DIR, str(deployed))
+ if "input_bytes" in kwargs:
+ archive_commands.append(command)
+ # Only the generated extraction runs locally, inside the fixture root.
+ script = script[script.index("tar --no-same-owner"):]
+ return subprocess.run(["bash", "-c", script], input=kwargs.get("input_bytes"), check=True)
+
+ target = incus_regression.RegressionTarget("master", "master", "avr-master", "avibe-master", 15130, "127.0.0.1", 5123)
+ incus_regression.sync_source(LocalRunner(), target, source, remote=None, clean=False)
+
+ assert len(archive_commands) == 1
+ assert ["sudo", "-H", "-u", "avibe"] == archive_commands[0][archive_commands[0].index("sudo"):][:4]
+ assert (deployed / "ui" / "entry.js").read_text() == "new source"
+ assert stat.S_IMODE((deployed / "tool").stat().st_mode) == 0o755
+ assert (deployed / "tool-link").readlink() == Path("tool")
+ assert (deployed / "tool").stat().st_uid == os.getuid()
+ assert not (deployed / "stale.py").exists()
+ assert all(path.lstat().st_ctime_ns == before.st_ctime_ns for path, before in preserved.items())
+
+
def test_sync_source_without_clean_keeps_every_ui_non_source_dir(tmp_path: Path) -> None:
"""A sync must leave ui/node_modules and ui/dist for the fingerprints to judge.
@@ -1346,6 +1458,10 @@ def test_prepare_state_reseeds_when_reset_requested(monkeypatch: pytest.MonkeyPa
assert "rm -rf /home/avibe/.avibe/config /home/avibe/.avibe/state /home/avibe/.avibe/runtime" in joined
assert "rm -rf /home/avibe/.regression-seed" in joined
assert "prepare_regression.py" in joined
+ copy_command = next(command for command in commands if "cp -a" in " ".join(command))
+ assert "sudo -H -u avibe" in " ".join(copy_command)
+ assert "--no-preserve=ownership" in " ".join(copy_command)
+ assert "chown" not in " ".join(copy_command)
def test_prepare_state_reset_all_deletes_target_home_before_copy(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -4162,6 +4278,52 @@ def test_update_builds_ui_before_editable_install() -> None:
assert build_index < install_index
[email protected]("venv_exists", [False, True])
+def test_python_environment_is_created_by_its_owner_and_reinstalled_only_when_needed(venv_exists: bool) -> None:
+ commands = []
+
+ class RecordingRunner:
+ def run(self, command, **kwargs):
+ commands.append(" ".join(command))
+ result = 0 if venv_exists else 1
+ return subprocess.CompletedProcess(command, result if "pyvenv.cfg" in commands[-1] else 0)
+
+ target = incus_regression.RegressionTarget("master", "master", "avr-master", "avibe-master", 15130, "127.0.0.1", 5123)
+ fingerprints = {"python": "p", "ui_deps": "d", "ui_source": "s"}
+ incus_regression.update_dependencies_and_build(
+ RecordingRunner(), target, previous_fingerprints=fingerprints, next_fingerprints=fingerprints,
+ force_deps=False, build_ui=True, force_ui=False, remote=None,
+ )
+
+ creation = [command for command in commands if "python3 -m venv" in command]
+ assert len(creation) == (0 if venv_exists else 1)
+ assert all("sudo -H -u avibe" in command for command in creation)
+ assert any("pip install -e ." in command for command in commands) is not venv_exists
+ assert all("chown" not in command for command in commands)
+
+
+def test_python_environment_creation_failure_stops_deployment() -> None:
+ commands = []
+
+ class FailingRunner:
+ def run(self, command, **kwargs):
+ joined = " ".join(command)
+ commands.append(joined)
+ if "pyvenv.cfg" in joined:
+ return subprocess.CompletedProcess(command, 1)
+ assert "python3 -m venv" in joined
+ assert "|| true" not in joined
+ raise subprocess.CalledProcessError(1, command)
+
+ target = incus_regression.RegressionTarget("master", "master", "avr-master", "avibe-master", 15130, "127.0.0.1", 5123)
+ with pytest.raises(subprocess.CalledProcessError):
+ incus_regression.update_dependencies_and_build(
+ FailingRunner(), target, previous_fingerprints={}, next_fingerprints={},
+ force_deps=False, build_ui=True, force_ui=False, remote=None,
+ )
+ assert len(commands) == 2
+
+
def test_force_ui_rebuilds_with_realtime_enabled_by_default() -> None:
commands = []
diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.py
index 0de336426..6042cf3d8 100644
--- a/tests/test_model_hub_runtime.py
+++ b/tests/test_model_hub_runtime.py
@@ -443,6 +443,90 @@ def test_engine_health_projects_only_required_facts_from_large_responses(
assert reads and all(size == client_module._STREAM_CHUNK_BYTES for size in reads)
[email protected]("endpoint", ["/v1/models", "/v0/management/config"])
+ ("status", "error_type", "reason"),
+ [(None, "TimeoutError", "timeout"), (401, "private-error", "http_error"),
+ (None, "invalid_json", "invalid_response"), (None, "private-error", "unavailable")],
+)
+def test_health_failure_retains_only_local_diagnostic_facts(
+ monkeypatch: pytest.MonkeyPatch, endpoint: str, status: int | None, error_type: str, reason: str,
+) -> None:
+ client = EngineClient(EngineConnection("http://127.0.0.1:15220", "private-management", "private-gateway"))
+ calls = []
+
+ def request(_method, path, _projector, **kwargs):
+ calls.append(path)
+ assert kwargs["timeout"] == 1.0
+ if path == endpoint:
+ raise EngineClientError("private-response", status_code=status, error_type=error_type)
+ return True
+
+ monkeypatch.setattr(client, "_request_json_projection", request)
+ assert client.health() is False
+ failure = client.health_failure
+ assert failure is not None
+ assert (failure.path, failure.reason, failure.http_status) == (endpoint, reason, status)
+ assert failure.elapsed_seconds >= 0
+ assert calls[-1] == endpoint
+ assert "private" not in repr(failure)
+
+ monkeypatch.setattr(client, "_request_json_projection", lambda *_args, **_kwargs: True)
+ assert client.health() is True
+ assert client.health_failure is None
+
+
[email protected]("endpoint", ["/v1/models", "/v0/management/config"])
+def test_health_rejects_an_unexpected_success_response(monkeypatch: pytest.MonkeyPatch, endpoint: str) -> None:
+ client = EngineClient(EngineConnection("http://127.0.0.1:15220", "management", "gateway"))
+ monkeypatch.setattr(client, "_request_json_projection", lambda _method, path, *_args, **_kwargs: path != endpoint)
+
+ assert client.health() is False
+ assert client.health_failure is not None
+ assert client.health_failure.path == endpoint
+ assert client.health_failure.reason == "invalid_response"
+
+
+def test_supervisor_records_health_transitions_without_repeating_or_leaking_errors(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture,
+) -> None:
+ installer = SimpleNamespace(
+ status=lambda: {"installed": True, "version": "fixture"},
+ contract_manifest=lambda: {"name": "cliproxyapi", "version": "fixture", "assets": []},
+ )
+ supervisor = EngineSupervisor(installer=installer, state_store=EngineStateStore(tmp_path / "state"))
+ supervisor._process = SimpleNamespace(poll=lambda: None)
+ supervisor._connection = EngineConnection("http://127.0.0.1:15220", "private-management", "private-gateway")
+ failure = [EngineClientError("private-body", error_type="TimeoutError")]
+
+ def request(_client, _method, path, *_args, **_kwargs):
+ if path == "/v0/management/config" and failure[0] is not None:
+ raise failure[0]
+ return True
+
+ monkeypatch.setattr(EngineClient, "_request_json_projection", request)
+ with caplog.at_level(logging.INFO, logger="vibe.model_hub_runtime.supervisor"):
+ for _ in range(3):
+ assert supervisor.status()["status"]["health"] == "degraded"
+ failure[0] = EngineClientError("private-body", status_code=403, error_type="private-error")
+ assert supervisor.status()["status"]["health"] == "degraded"
+ failure[0] = None
+ for _ in range(2):
+ assert supervisor.status()["status"]["health"] == "ok"
+ failure[0] = EngineClientError("private-body", error_type="TimeoutError")
+ assert supervisor.status()["status"]["health"] == "degraded"
+
+ messages = [record.getMessage() for record in caplog.records]
+ failures = [message for message in messages if "health outcome=failed" in message]
+ assert len(failures) == 3
+ assert all("endpoint=/v0/management/config" in message for message in failures)
+ assert "reason=timeout" in failures[0]
+ assert "reason=http_error http_status=403" in failures[1]
+ assert sum("health outcome=recovered" in message for message in messages) == 1
+ assert all("private" not in message for message in messages)
+ supervisor._process = None
+
+
def test_engine_error_projection_does_not_materialize_unrelated_payload(
monkeypatch: pytest.MonkeyPatch,
) -> None:
diff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.py
index f3ef40314..5e2b34ef8 100644
--- a/vibe/model_hub_runtime/client.py
+++ b/vibe/model_hub_runtime/client.py
@@ -13,7 +13,7 @@ import urllib.request
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field, replace
from decimal import Decimal
-from typing import Any, AsyncIterator, BinaryIO, Mapping, TypeVar, cast
+from typing import Any, AsyncIterator, BinaryIO, Literal, Mapping, TypeVar, cast
import aiohttp
import ijson
@@ -229,6 +229,14 @@ class EngineConnection:
gateway_token: str = field(repr=False)
+@dataclass(frozen=True)
+class EngineHealthFailure:
+ path: str
+ reason: Literal["timeout", "http_error", "invalid_response", "unavailable"]
+ elapsed_seconds: float
+ http_status: int | None = None
+
+
class EngineInvokeHandle:
"""Concrete InvokeHandle with one-shot streaming ownership."""
@@ -290,26 +298,36 @@ class EngineClient:
raise ValueError("engine client requires a credential-free 127.0.0.1 URL")
self.connection = connection
self.timeout = timeout
+ self.health_failure: EngineHealthFailure | None = None
def health(self) -> bool:
- try:
- models_ok = self._request_json_projection(
- "GET",
- "/v1/models",
- _project_models_health,
- headers={"Authorization": f"Bearer {self.connection.gateway_token}"},
- timeout=min(self.timeout, 1.0),
- )
- config_ok = self._request_json_projection(
- "GET",
- "/v0/management/config",
- _project_root_map,
- headers={"X-Management-Key": self.connection.management_key},
- timeout=min(self.timeout, 1.0),
- )
- except EngineClientError:
- return False
- return models_ok and config_ok
+ self.health_failure = None
+ for path, projector, headers in (
+ ("/v1/models", _project_models_health, {"Authorization": f"Bearer {self.connection.gateway_token}"}),
+ ("/v0/management/config", _project_root_map, {"X-Management-Key": self.connection.management_key}),
+ ):
+ started_at = time.monotonic()
+ try:
+ valid = self._request_json_projection(
+ "GET", path, projector, headers=headers, timeout=min(self.timeout, 1.0),
+ )
+ except EngineClientError as exc:
+ reason = (
+ "http_error" if exc.status_code is not None
+ else "timeout" if exc.error_type == "TimeoutError"
+ else "invalid_response" if exc.error_type == "invalid_json"
+ else "unavailable"
+ )
+ self.health_failure = EngineHealthFailure(
+ path, reason, time.monotonic() - started_at, exc.status_code,
+ )
+ return False
+ if not valid:
+ self.health_failure = EngineHealthFailure(
+ path, "invalid_response", time.monotonic() - started_at,
+ )
+ return False
+ return True
def management_request(
self,
diff --git a/vibe/model_hub_runtime/supervisor.py b/vibe/model_hub_runtime/supervisor.py
index d798a3911..07ac6cf78 100644
--- a/vibe/model_hub_runtime/supervisor.py
+++ b/vibe/model_hub_runtime/supervisor.py
@@ -59,6 +59,7 @@ class EngineSupervisor:
self._connection: EngineConnection | None = None
self._last_check: str | None = None
self._start_attempted = False
+ self._health_failure_signature: tuple[str, str, int | None] | None = None
def ensure_running(self) -> EngineConnection:
with self._lock:
@@ -220,7 +221,7 @@ class EngineSupervisor:
if remaining <= 0:
break
client = EngineClient(connection, timeout=min(1.0, remaining / 2))
- if client.health():
+ if self._check_health_locked(client):
try:
self.state_store.audit_auth_permissions()
except Exception as exc:
@@ -251,8 +252,25 @@ class EngineSupervisor:
def _healthy_locked(self) -> bool:
if not self._is_running_locked() or self._connection is None:
return False
- healthy = EngineClient(self._connection, timeout=1.0).health()
+ return self._check_health_locked(EngineClient(self._connection, timeout=1.0))
+
+ def _check_health_locked(self, client: EngineClient) -> bool:
+ healthy = client.health()
self._last_check = _utc_now()
+ failure = client.health_failure
+ if failure is not None:
+ signature = (failure.path, failure.reason, failure.http_status)
+ if signature != self._health_failure_signature:
+ logger.warning(
+ "Model Hub engine health outcome=failed endpoint=%s reason=%s "
+ "http_status=%s elapsed_seconds=%.3f",
+ failure.path, failure.reason, failure.http_status, failure.elapsed_seconds,
+ )
+ self._health_failure_signature = signature
+ elif healthy:
+ if self._health_failure_signature is not None:
+ logger.info("Model Hub engine health outcome=recovered")
+ self._health_failure_signature = None
return healthy
def _is_running_locked(self) -> bool:
@@ -262,6 +280,7 @@ class EngineSupervisor:
process = self._process
self._process = None
self._connection = None
+ self._health_failure_signature = None
if process is None or process.poll() is not None:
return
signal_process_tree(process, signal.SIGTERM, logger, "Model Hub engine")