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(model-hub): cover CLIProxyAPI cold starts (#1655)

Call White80621f6b6a50
diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.md
index f09cc7a52..500190445 100644
--- a/docs/plans/model-hub.md
+++ b/docs/plans/model-hub.md
@@ -1557,6 +1557,22 @@ binary): pinned version + SHA256, 127.0.0.1-only listener, random management
key and gateway token, lifecycle owned by Avibe. Its YAML/auth files/manage
UI are **not** product surface.
+An explicit start has one bounded 30-second readiness budget; it succeeds only
+after both the gateway model endpoint and management config endpoint respond.
+The operational budget is based on local live evidence: the first process was
+still alive when the former 10-second window ended, while the next start reached
+both health surfaces in 7.4 seconds. It adds bounded cold-start margin without
+claiming an unobserved internal engine phase or introducing a retry loop. If
+readiness is not established, Avibe terminates the child and preserves the
+existing runtime failure contract.
+CLIProxyAPI stdout and stderr are directed to the operating system's null sink
+when the process is created. Child bytes therefore never enter Avibe's Python
+memory or service logs and cannot create pipe backpressure. Startup diagnostics
+contain only bounded supervisor-owned structured fields: outcome, managed
+version, exit code when applicable, elapsed time, readiness budget, and the
+existing error contract. Avibe does not retain, inspect, redact, or publish child
+output.
+
**v3 routing requires no new engine policy.** Failover is ours, not the engine's: the engine
runs as a single global instance with its own cooling and request-retry disabled
(`vibe/model_hub_runtime/config.py`), model prefixes pin the source, and Python
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 1e6bc0bb8..22154f7f8 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -132,6 +132,18 @@ scenarios:
kind: concurrency
layer: unit
test: tests/test_opencode_server.py::test_mh_runtime_004_overlay_reservation_promotes_atomically_to_active_run
+ - id: MH-RUNTIME-005
+ name: First CLIProxyAPI cold start remains pending until both health surfaces are ready
+ status: covered
+ kind: recovery
+ layer: unit
+ test: tests/test_model_hub_runtime.py::test_mh_runtime_005_first_cold_start_waits_for_readiness_within_bounded_budget
+ - id: MH-RUNTIME-006
+ name: CLIProxyAPI readiness timeout stops the child, discards its output, and leaves bounded structured diagnostics
+ status: covered
+ kind: timeout_cancel
+ layer: unit
+ test: tests/test_model_hub_runtime.py::test_mh_runtime_006_timeout_stops_engine_with_bounded_structured_diagnostics
- id: MH-USAGE-001
name: Tokens an upstream reported before the turn ended are still metered
status: covered
diff --git a/tests/scenarios/model_hub/observations.yaml b/tests/scenarios/model_hub/observations.yaml
index 27e0e343d..72d01564f 100644
--- a/tests/scenarios/model_hub/observations.yaml
+++ b/tests/scenarios/model_hub/observations.yaml
@@ -28,3 +28,9 @@ observations:
affects:
- MH-AC29-001
- MH-MIG-001
+ - id: MH-OBS-005
+ source: local-incus-cold-start-2026-08-23
+ summary: A first CLIProxyAPI process remained alive when Avibe ended the fixed 10-second readiness window; the next start reached both health surfaces in 7.4 seconds.
+ affects:
+ - MH-RUNTIME-005
+ - MH-RUNTIME-006
diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.py
index a379dbfbb..7cf05c261 100644
--- a/tests/test_model_hub_runtime.py
+++ b/tests/test_model_hub_runtime.py
@@ -55,7 +55,11 @@ from vibe.model_hub_runtime.state import (
EngineStateStore,
SourceRecord,
)
-from vibe.model_hub_runtime.supervisor import EngineSupervisor, EngineUnavailableError
+from vibe.model_hub_runtime.supervisor import (
+ MODEL_HUB_STARTUP_TIMEOUT_SECONDS,
+ EngineSupervisor,
+ EngineUnavailableError,
+)
MODEL_HUB_FIXTURES = Path(__file__).parent / "fixtures" / "model_hub"
@@ -1327,7 +1331,15 @@ def test_adapter_provisions_probes_and_revokes_credential(tmp_path: Path) -> Non
asyncio.run(run(base_url, handler))
-def _write_mock_engine(path: Path) -> None:
+def _write_mock_engine(
+ path: Path,
+ *,
+ startup_delay: float = 0.0,
+ startup_output: bytes = b"",
+ startup_output_repeat: int = 1,
+ echo_runtime_secrets: bool = False,
+ exit_before_ready: int | None = None,
+) -> None:
script = f"""#!{sys.executable}
import json
import sys
@@ -1341,6 +1353,30 @@ with open(config_path, encoding='utf-8') as handle:
config = yaml.safe_load(handle)
gateway = config['api-keys'][0]
management = config['remote-management']['secret-key']
+startup_output = {startup_output!r} * {startup_output_repeat!r}
+if startup_output:
+ sys.stdout.buffer.write(startup_output)
+ sys.stdout.buffer.flush()
+ sys.stderr.buffer.write(startup_output)
+ sys.stderr.buffer.flush()
+if {echo_runtime_secrets!r}:
+ sys.stderr.buffer.write(
+ f'management-key={{management}} gateway-token={{gateway}}'.encode()
+ )
+ sys.stderr.buffer.flush()
+with open('startup-output-complete', 'w', encoding='utf-8') as handle:
+ handle.write(str(len(startup_output) * 2))
+exit_before_ready = {exit_before_ready!r}
+if exit_before_ready is not None:
+ raise SystemExit(exit_before_ready)
+time.sleep({startup_delay!r})
+health_surfaces = set()
+
+def mark_health_surface(surface):
+ health_surfaces.add(surface)
+ if len(health_surfaces) == 2:
+ with open('health-surfaces-complete', 'w', encoding='utf-8') as handle:
+ handle.write(','.join(sorted(health_surfaces)))
class Handler(BaseHTTPRequestHandler):
def log_message(self, *args):
@@ -1356,9 +1392,11 @@ class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/v1/models' and self.headers.get('Authorization') == f'Bearer {{gateway}}':
+ mark_health_surface('gateway')
self._json(200, {{'object': 'list', 'data': []}})
return
if self.path == '/v0/management/config' and self.headers.get('X-Management-Key') == management:
+ mark_health_surface('management')
self._json(200, {{'host': config['host']}})
return
if self.path.startswith('/v0/management/auth-files/models'):
@@ -1485,17 +1523,30 @@ def _fixture_supervisor(
tmp_path: Path,
*,
process_factory=subprocess.Popen,
+ startup_timeout: float = 5,
+ startup_delay: float = 0.0,
+ startup_output: bytes = b"",
+ startup_output_repeat: int = 1,
+ echo_runtime_secrets: bool = False,
+ exit_before_ready: int | None = None,
) -> tuple[EngineSupervisor, EngineStateStore]:
tmp_path.mkdir(parents=True, exist_ok=True)
binary = tmp_path / "mock-engine"
- _write_mock_engine(binary)
+ _write_mock_engine(
+ binary,
+ startup_delay=startup_delay,
+ startup_output=startup_output,
+ startup_output_repeat=startup_output_repeat,
+ echo_runtime_secrets=echo_runtime_secrets,
+ exit_before_ready=exit_before_ready,
+ )
installer = _FixtureInstaller(binary, tmp_path / "versions" / "install-1")
store = EngineStateStore(tmp_path / "state")
return (
EngineSupervisor(
installer=installer,
state_store=store,
- startup_timeout=5,
+ startup_timeout=startup_timeout,
process_factory=process_factory,
),
store,
@@ -1594,9 +1645,11 @@ def test_supervisor_starts_checks_health_and_stops_mock_engine(
monkeypatch: pytest.MonkeyPatch,
) -> None:
captured_env: dict[str, str] = {}
+ captured_stdio: dict[str, int] = {}
def spawn(*args, **kwargs):
captured_env.update(kwargs["env"])
+ captured_stdio.update(stdout=kwargs["stdout"], stderr=kwargs["stderr"])
return subprocess.Popen(*args, **kwargs)
monkeypatch.setenv("MANAGEMENT_PASSWORD", "untrusted-management-secret")
@@ -1615,6 +1668,10 @@ def test_supervisor_starts_checks_health_and_stops_mock_engine(
assert "GITHUB_TOKEN" not in captured_env
assert "HTTP_PROXY" not in captured_env
assert captured_env == engine_subprocess_environment()
+ assert captured_stdio == {
+ "stdout": subprocess.DEVNULL,
+ "stderr": subprocess.DEVNULL,
+ }
assert supervisor.status()["status"]["health"] == "ok"
config_path = store.root / "instances" / "install-1" / "config.yaml"
first_config = yaml.safe_load(config_path.read_text(encoding="utf-8"))
@@ -1629,6 +1686,221 @@ def test_supervisor_starts_checks_health_and_stops_mock_engine(
supervisor.stop()
+def _assert_supervisor_owned_startup_log(
+ message: str,
+ *,
+ outcome: str,
+ exit_code: int | None = None,
+ readiness_budget: float | None = None,
+) -> None:
+ prefix = "Model Hub engine startup "
+ assert message.startswith(prefix)
+ tokens = message.removeprefix(prefix).split()
+ assert all("=" in token for token in tokens)
+ fields = dict(token.split("=", 1) for token in tokens)
+ assert len(fields) == len(tokens)
+
+ expected_fields = {
+ "outcome",
+ "managed_version",
+ "elapsed_seconds",
+ "child_output_retained",
+ }
+ if readiness_budget is not None:
+ expected_fields.update({"exit_code", "readiness_budget_seconds"})
+ assert set(fields) == expected_fields
+ assert fields["outcome"] == outcome
+ assert fields["managed_version"] == "v7.2.95"
+ assert float(fields["elapsed_seconds"]) >= 0
+ assert fields["child_output_retained"] == "false"
+ if readiness_budget is not None:
+ assert fields["exit_code"] == str(exit_code)
+ assert float(fields["readiness_budget_seconds"]) == readiness_budget
+ assert len(message.encode("utf-8")) < 512
+
+
+def _assert_child_payload_absent(log_text: str, payload: bytes) -> None:
+ printable_run = bytearray()
+ candidates: list[bytes] = []
+ for byte in payload + b"\x00":
+ if 32 <= byte <= 126:
+ printable_run.append(byte)
+ continue
+ if len(printable_run) >= 8:
+ if len(printable_run) <= 128:
+ candidates.append(bytes(printable_run))
+ else:
+ candidates.extend((bytes(printable_run[:64]), bytes(printable_run[-64:])))
+ printable_run.clear()
+
+ assert candidates
+ assert all(candidate.decode("ascii") not in log_text for candidate in candidates)
+ assert "\ufffd" not in log_text
+
+
+def test_mh_runtime_005_first_cold_start_waits_for_readiness_within_bounded_budget(
+ tmp_path: Path,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """MH-RUNTIME-005: first cold start waits past an early probe and becomes ready."""
+
+ assert MODEL_HUB_STARTUP_TIMEOUT_SECONDS == 30.0
+ caplog.set_level(logging.INFO, logger="vibe.model_hub_runtime.supervisor")
+ child_payload = b"\n".join(
+ (
+ b"cold-start-safe-diagnostic-marker",
+ b'id_token="opaque-id-token-value"',
+ b'private_key="opaque-private-key-value"',
+ b'future_unknown_auth_material="opaque-unknown-value"',
+ b"binary-boundary-before-\xff\xfe-binary-boundary-after",
+ )
+ )
+ supervisor, store = _fixture_supervisor(
+ tmp_path,
+ startup_timeout=3.0,
+ startup_delay=0.25,
+ startup_output=child_payload,
+ echo_runtime_secrets=True,
+ )
+
+ started_at = time.monotonic()
+ connection = supervisor.ensure_running()
+ elapsed = time.monotonic() - started_at
+ runtime_secrets = store.prepare_instance("install-1", rotate=False)[1]
+ instance_dir = store.root / "instances" / "install-1"
+ ready_log = next(
+ record.getMessage()
+ for record in caplog.records
+ if "startup outcome=ready" in record.getMessage()
+ )
+
+ assert connection.base_url.startswith("http://127.0.0.1:")
+ assert 0.2 <= elapsed < 3.0
+ _assert_supervisor_owned_startup_log(ready_log, outcome="ready")
+ _assert_child_payload_absent(caplog.text, child_payload)
+ for secret in (runtime_secrets.management_key, runtime_secrets.gateway_token):
+ midpoint = len(secret) // 2
+ assert secret[:midpoint] not in caplog.text
+ assert secret[midpoint:] not in caplog.text
+ assert (instance_dir / "startup-output-complete").read_text(encoding="utf-8") == str(
+ len(child_payload) * 2
+ )
+ assert (instance_dir / "health-surfaces-complete").read_text(encoding="utf-8") == (
+ "gateway,management"
+ )
+ supervisor.stop()
+
+
+def test_supervisor_process_exit_discards_all_child_output(
+ tmp_path: Path,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ child_payload = b"\n".join(
+ (
+ b"process-exit-safe-diagnostic-marker",
+ b'id_token="process-exit-oauth-secret"',
+ b'private_key="process-exit-private-key"',
+ b'unknown_field="process-exit-opaque-value"',
+ b"process-exit-binary-before-\xff-process-exit-binary-after",
+ )
+ )
+ caplog.set_level(logging.WARNING, logger="vibe.model_hub_runtime.supervisor")
+ supervisor, store = _fixture_supervisor(
+ tmp_path,
+ startup_timeout=2.0,
+ startup_output=child_payload,
+ echo_runtime_secrets=True,
+ exit_before_ready=23,
+ )
+
+ with pytest.raises(EngineUnavailableError, match="models.engine.health_failed") as exc_info:
+ supervisor.ensure_running()
+
+ runtime_secrets = store.prepare_instance("install-1", rotate=False)[1]
+ instance_dir = store.root / "instances" / "install-1"
+ warning = next(
+ record.getMessage()
+ for record in caplog.records
+ if "startup outcome=process_exit" in record.getMessage()
+ )
+ assert exc_info.value.error_key == "models.engine.health_failed"
+ assert supervisor.status()["status"]["health"] == "down"
+ _assert_supervisor_owned_startup_log(
+ warning,
+ outcome="process_exit",
+ exit_code=23,
+ readiness_budget=2.0,
+ )
+ _assert_child_payload_absent(caplog.text, child_payload)
+ for secret in (runtime_secrets.management_key, runtime_secrets.gateway_token):
+ midpoint = len(secret) // 2
+ assert secret[:midpoint] not in caplog.text
+ assert secret[midpoint:] not in caplog.text
+ assert (instance_dir / "startup-output-complete").read_text(encoding="utf-8") == str(
+ len(child_payload) * 2
+ )
+ assert not (instance_dir / "health-surfaces-complete").exists()
+
+
+def test_mh_runtime_006_timeout_stops_engine_with_bounded_structured_diagnostics(
+ tmp_path: Path,
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ """MH-RUNTIME-006: readiness timeout is terminal with bounded diagnostics."""
+
+ caplog.set_level(logging.WARNING, logger="vibe.model_hub_runtime.supervisor")
+ child_payload = b"\n".join(
+ (
+ b"timeout-safe-diagnostic-marker",
+ b'id_token="timeout-oauth-secret"',
+ b'private_key="timeout-private-key"',
+ b'future_unknown_field="timeout-opaque-value"',
+ b"oversized-child-output-" + b"x" * 4_096,
+ b"timeout-binary-before-\xff\xfe-timeout-binary-after",
+ )
+ )
+ output_repeat = 256
+ supervisor, store = _fixture_supervisor(
+ tmp_path,
+ startup_timeout=1.0,
+ startup_delay=60.0,
+ startup_output=child_payload,
+ startup_output_repeat=output_repeat,
+ echo_runtime_secrets=True,
+ )
+
+ started_at = time.monotonic()
+ with pytest.raises(EngineUnavailableError, match="models.engine.health_failed") as exc_info:
+ supervisor.ensure_running()
+ elapsed = time.monotonic() - started_at
+ runtime_secrets = store.prepare_instance("install-1", rotate=False)[1]
+ instance_dir = store.root / "instances" / "install-1"
+ warning = next(
+ record.getMessage()
+ for record in caplog.records
+ if "startup outcome=timeout" in record.getMessage()
+ )
+
+ assert exc_info.value.error_key == "models.engine.health_failed"
+ assert elapsed < 2.5
+ assert supervisor.status()["status"]["health"] == "down"
+ _assert_supervisor_owned_startup_log(
+ warning,
+ outcome="timeout",
+ readiness_budget=1.0,
+ )
+ _assert_child_payload_absent(caplog.text, child_payload)
+ for secret in (runtime_secrets.management_key, runtime_secrets.gateway_token):
+ midpoint = len(secret) // 2
+ assert secret[:midpoint] not in caplog.text
+ assert secret[midpoint:] not in caplog.text
+ observed_output_bytes = int(
+ (instance_dir / "startup-output-complete").read_text(encoding="utf-8")
+ )
+ assert observed_output_bytes == len(child_payload) * output_repeat * 2
+ assert observed_output_bytes > 512 * 1024
+
+
def test_mh_runtime_001_service_restart_reports_installed_engine_as_not_started(
tmp_path: Path,
) -> None:
diff --git a/vibe/model_hub_runtime/supervisor.py b/vibe/model_hub_runtime/supervisor.py
index ab82d0033..4c24b5bd7 100644
--- a/vibe/model_hub_runtime/supervisor.py
+++ b/vibe/model_hub_runtime/supervisor.py
@@ -23,6 +23,10 @@ from vibe.model_hub_runtime.state import EngineStateStore
logger = logging.getLogger(__name__)
+MODEL_HUB_STARTUP_TIMEOUT_SECONDS = 30.0
+_STARTUP_POLL_INTERVAL_SECONDS = 0.05
+
+
class EngineUnavailableError(RuntimeError):
"""The Hub path is unavailable; callers may use explicitly configured Direct mode."""
@@ -41,7 +45,7 @@ class EngineSupervisor:
*,
installer: EngineRuntimeManager | Any | None = None,
state_store: EngineStateStore | None = None,
- startup_timeout: float = 10.0,
+ startup_timeout: float = MODEL_HUB_STARTUP_TIMEOUT_SECONDS,
process_factory: Callable[..., subprocess.Popen[bytes]] = subprocess.Popen,
port_allocator: Callable[[], int] | None = None,
) -> None:
@@ -195,11 +199,17 @@ class EngineSupervisor:
raise EngineUnavailableError("models.engine.start_failed") from exc
self._process = process
self._connection = connection
- deadline = time.monotonic() + self.startup_timeout
- client = EngineClient(connection, timeout=1.0)
- while time.monotonic() < deadline:
- if process.poll() is not None:
+ started_at = time.monotonic()
+ deadline = started_at + self.startup_timeout
+ exit_code: int | None = None
+ while True:
+ exit_code = process.poll()
+ if exit_code is not None:
break
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ break
+ client = EngineClient(connection, timeout=min(1.0, remaining / 2))
if client.health():
try:
self.state_store.audit_auth_permissions()
@@ -208,12 +218,24 @@ class EngineSupervisor:
raise EngineUnavailableError("models.engine.unsafe_permissions") from exc
self._last_check = _utc_now()
logger.info(
- "Model Hub engine started on 127.0.0.1 with managed version %s",
+ "Model Hub engine startup outcome=ready managed_version=%s "
+ "elapsed_seconds=%.3f child_output_retained=false",
managed.get("version"),
+ time.monotonic() - started_at,
)
return connection
- time.sleep(0.05)
+ time.sleep(min(_STARTUP_POLL_INTERVAL_SECONDS, max(0.0, deadline - time.monotonic())))
self._stop_locked()
+ logger.warning(
+ "Model Hub engine startup outcome=%s managed_version=%s exit_code=%s "
+ "elapsed_seconds=%.3f readiness_budget_seconds=%.3f "
+ "child_output_retained=false",
+ "process_exit" if exit_code is not None else "timeout",
+ managed.get("version"),
+ exit_code,
+ time.monotonic() - started_at,
+ self.startup_timeout,
+ )
raise EngineUnavailableError("models.engine.health_failed")
def _healthy_locked(self) -> bool: