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): show local OS errors in notification details (#2246)

Call White846d7bf1f5cd
diff --git a/core/backend_failure.py b/core/backend_failure.py
index b682b3869..967e00b0b 100644
--- a/core/backend_failure.py
+++ b/core/backend_failure.py
@@ -134,9 +134,9 @@ def _controller_language(controller: Any) -> str:
return str(getattr(getattr(controller, "config", None), "language", "en") or "en")
-def _model_hub_failure_text(
+def _model_hub_failure(
controller: Any, context: Any, request: Any, backend: str
-) -> str | None:
+) -> tuple[str | None, str | None] | None:
"""Render exact live Hub evidence, never parse a native exception wrapper.
The registry owns ambiguity, pending-request, and Stop guards. Without that
@@ -162,7 +162,10 @@ def _model_hub_failure_text(
projection = project(turn_id.strip(), backend=backend)
if not isinstance(projection, TurnOutcomeProjectionInput):
continue
- return render_turn_outcome_copy(projection, _controller_language(controller))
+ return (
+ render_turn_outcome_copy(projection, _controller_language(controller)),
+ projection.local_error_detail,
+ )
return None
@@ -239,6 +242,11 @@ def terminal_backend_failure_output(
metadata = dict(terminal.metadata)
existing = metadata.get("turn_failure_notification")
existing_notification = dict(existing) if isinstance(existing, dict) else {}
+ local_detail = metadata.pop("local_error_detail", None)
+ if local_detail:
+ # The failure-delivery contract is already carried through immediate,
+ # deferred, and late-attached Run settlement. Keep its snapshot there.
+ existing_notification["local_error_detail"] = local_detail
identity = str(existing_notification.get("failure_id") or "").strip()
if not identity:
identity = _failure_identity(context, request, failure_id)
@@ -272,6 +280,7 @@ async def emit_replayed_backend_failure(
*,
failure_id: str,
turn_id: str | None = None,
+ local_error_detail: str | None = None,
display_text: str | None = None,
delivery: DeliveryEvidence | None = None,
) -> None:
@@ -328,7 +337,11 @@ async def emit_replayed_backend_failure(
failure_id=failure_id,
failure_id_authoritative=True,
output=MessageOutput(
- metadata={"turn_id": str(turn_id or "").strip() or None, "replayed": True},
+ metadata={
+ "turn_id": str(turn_id or "").strip() or None,
+ "replayed": True,
+ **({"local_error_detail": local_error_detail} if local_error_detail else {}),
+ },
),
)
# ``delivery`` is passed ONLY when a caller asked for it: controller-like objects
@@ -374,10 +387,14 @@ async def emit_backend_failure(
backend_name = str(backend or "backend").strip() or "backend"
error, visible = _failure_texts(backend_name, diagnostic, display_text)
- hub_visible = _model_hub_failure_text(controller, context, request, backend_name)
- if hub_visible is not None:
- visible = hub_visible
+ hub_failure = _model_hub_failure(controller, context, request, backend_name)
+ if hub_failure is not None and hub_failure[0] is not None:
+ visible = hub_failure[0]
terminal = _terminal_output(request, output)
+ if hub_failure is not None and hub_failure[1] and not getattr(controller, "shutdown_requested", False):
+ terminal = replace(
+ terminal, metadata={**terminal.metadata, "local_error_detail": hub_failure[1]},
+ )
harness_run_id = _harness_run_identity(context, request)
owns_failure_contract = bool(
_turn_failure_identity(context, request) or harness_run_id
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.py
index bf7dc8206..88a6bbe34 100644
--- a/core/handlers/model_hub/adapter.py
+++ b/core/handlers/model_hub/adapter.py
@@ -151,6 +151,9 @@ class RawCallOutcome:
# by L1. Display-only: classification never reads it, it is never persisted
# into events or provenance, and it stays out of repr so logs cannot echo it.
upstream_detail: str | None = field(default=None, repr=False)
+ # Recognized local OS failure only, never an upstream code or error prose.
+ # Display-only; does not participate in classification or Source health.
+ os_errno: int | None = None
class ObservationOutcome(str, Enum):
diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.py
index 78c547ad0..6f520ba9d 100644
--- a/core/handlers/model_hub/provenance.py
+++ b/core/handlers/model_hub/provenance.py
@@ -13,6 +13,7 @@ from pathlib import Path
from typing import Any, Callable, Iterable, Literal, Mapping, Optional
from config.v2_config import ModelHubConfig
+from core.os_errors import format_os_errno
from core.run_settlement import (
SETTLED_BY_BACKEND_REFRESH,
@@ -220,6 +221,8 @@ class TurnOutcomeProjectionInput:
source_transition_persisted: bool | None = None
# Redacted, bounded upstream error text for this turn's reply only.
upstream_detail: str | None = None
+ # An OS-generated reason, separate from summary copy and upstream text.
+ local_error_detail: str | None = None
class TurnOutcomeProductionError(ValueError):
@@ -684,11 +687,12 @@ class GatewayTurnTerminalizer:
force=True,
)
- def engine_down(self) -> None:
+ def engine_down(self, *, local_error_detail: str | None = None) -> None:
self._registry._terminalize_gateway_exit(
self.turn_id,
request_id=self._request_id,
reason="engine_down",
+ local_error_detail=local_error_detail,
stream_started=self._stream_started,
force=True,
)
@@ -1762,6 +1766,7 @@ class TurnCorrelationRegistry:
] = "protocol_error",
stream_started: bool,
force: bool = False,
+ local_error_detail: str | None = None,
) -> None:
if turn_id is None:
return
@@ -1791,6 +1796,7 @@ class TurnCorrelationRegistry:
"channel": None,
"reason": reason,
"stream_started": stream_started,
+ **({"local_error_detail": local_error_detail} if local_error_detail else {}),
}
return
identity = trace.pending_attempts.get(request_id)
@@ -2025,6 +2031,7 @@ class TurnCorrelationRegistry:
request_id=request_id,
reason="engine_down",
stream_started=outcome.stream_started,
+ local_error_detail=format_os_errno(outcome.os_errno),
force=True,
)
return
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 17025d0f7..ac66418d2 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -41,6 +41,7 @@ from config.v2_config import (
validate_model_hub_source_client_nonce,
)
from core.agent_auth_service import BackendLoginInProgressError
+from core.os_errors import format_os_errno, local_error_detail
from core.services.settings import default_config
from storage.db import get_cached_sqlite_engine
from storage.models import agent_sessions, messages
@@ -305,6 +306,7 @@ class ModelHubError(Exception):
data: Optional[Mapping[str, Any]] = None,
blockers: Iterable[ExactHopBlocker] = (),
turn_outcome: TurnOutcomeProjectionInput | None = None,
+ local_error_detail: str | None = None,
):
detail_key = detail or f"modelHub.errors.{code}"
super().__init__(detail_key)
@@ -315,6 +317,7 @@ class ModelHubError(Exception):
self.data = dict(data or {})
self.blockers = tuple(blockers)
self.turn_outcome = turn_outcome
+ self.local_error_detail = local_error_detail
class CredentialCleanupUnsettledError(ModelHubError):
@@ -874,6 +877,7 @@ async def ensure_runtime_dependency(
"engine_down",
status=503,
data={"reason": reason} if isinstance(reason, str) and reason else None,
+ local_error_detail=local_error_detail(exc),
) from None
except ModelHubError:
raise
@@ -888,6 +892,7 @@ async def ensure_runtime_dependency(
"engine_down",
status=503,
data={"reason": safe_reason} if safe_reason else None,
+ local_error_detail=local_error_detail(exc),
) from None
@@ -1129,15 +1134,15 @@ class ModelHubService:
raise ModelHubError("discovery_failed", status=502) from None
except RuntimePlatformUnsupportedError:
raise ModelHubError("runtime_platform_unsupported", status=422) from None
- except EngineUnavailableError:
- raise ModelHubError("engine_down", status=503) from None
+ except EngineUnavailableError as exc:
+ raise ModelHubError("engine_down", status=503, local_error_detail=local_error_detail(exc)) from None
except NativeOAuthUnavailableError:
raise ModelHubError("engine_down", status=503) from None
except ModelHubError:
raise
- except Exception:
+ except Exception as exc:
# Engine failures may carry upstream context. Never expose or log it.
- raise ModelHubError("engine_down", status=503) from None
+ raise ModelHubError("engine_down", status=503, local_error_detail=local_error_detail(exc)) from None
async def _oauth_call(self, awaitable, *, flow_id: Optional[str] = None):
try:
@@ -7233,9 +7238,9 @@ class ModelHubService:
# a request-incompatible projection would misclassify the failure.
return None
if category == "engine_down":
- return produce_turn_outcome(
- "turn.engine_down",
- stream_started=outcome.stream_started,
+ return replace(
+ produce_turn_outcome("turn.engine_down", stream_started=outcome.stream_started),
+ local_error_detail=format_os_errno(outcome.os_errno),
)
if (
category == "fallback_source"
@@ -8107,6 +8112,7 @@ class ModelHubService:
)
raise ModelHubError(
decision.error_code or outcome.error_code or "engine_down",
+ local_error_detail=format_os_errno(outcome.os_errno),
status=decision.downstream_status or (
outcome.http_status
if outcome.http_status is not None and 400 <= outcome.http_status <= 599
@@ -8143,6 +8149,7 @@ class ModelHubService:
decision.error_code or "engine_down",
status=502,
turn_outcome=ENGINE_DOWN_TURN_OUTCOME,
+ local_error_detail=format_os_errno(outcome.os_errno),
)
final_config, final_resolution = self._inspect_terminal_chain(
backend=cast(BackendName, backend),
diff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.py
index 4e8a936d3..889703917 100644
--- a/core/handlers/model_hub/turn_gateway.py
+++ b/core/handlers/model_hub/turn_gateway.py
@@ -11,7 +11,7 @@ import tempfile
from collections import deque
from collections.abc import AsyncIterator, Callable, Mapping
from contextlib import AsyncExitStack, asynccontextmanager, contextmanager, suppress
-from dataclasses import dataclass, field
+from dataclasses import dataclass, field, replace
from datetime import datetime, timezone
from typing import BinaryIO, Final, Optional
@@ -64,6 +64,7 @@ from .service import (
ModelHubService,
ResolvedInvocation,
)
+from core.os_errors import local_error_detail
_MAX_REQUEST_BYTES: Final = 128 * 1024 * 1024
@@ -198,6 +199,9 @@ class _TurnExecution:
# The downstream event stream once its headers left before resolution
# finished. From then on every ending of this turn travels inside it.
stream_response: web.StreamResponse | None = None
+ # A large buffered JSON body whose headers have already left. A local disk
+ # failure can no longer replace its HTTP status or append an SSE ending.
+ buffered_response: web.StreamResponse | None = None
@property
def upstream_observation(self) -> ProtocolSSEState | None:
@@ -953,7 +957,8 @@ class ModelHubTurnGateway:
if turn_outcome is None and exc.code == "engine_down":
turn_outcome = ENGINE_DOWN_TURN_OUTCOME
if turn_outcome is not None and turn_outcome.discriminator == "engine_down":
- terminalizer.engine_down()
+ turn_outcome = replace(turn_outcome, local_error_detail=exc.local_error_detail)
+ terminalizer.engine_down(local_error_detail=exc.local_error_detail)
elif turn_outcome is not None and turn_outcome.outcome == "no_candidate" and exc.supply_state is not None:
terminalizer.mark_no_candidate(exc.supply_state, exc.blockers)
if exc.code == RECOVERY_EXHAUSTED_CODE:
@@ -1104,70 +1109,82 @@ class ModelHubTurnGateway:
)
if not stream:
- with tempfile.SpooledTemporaryFile(
- max_size=_BUFFERED_RESPONSE_MEMORY_BYTES
- ) as payload:
- async for chunk in handle.stream:
- await run_owned_in_thread(payload.write, chunk)
- execution.completed_at = self._now()
- outcome, settlement, rendered = await self._settle_metered_turn(
+ try:
+ response = None
+ with tempfile.SpooledTemporaryFile(max_size=_BUFFERED_RESPONSE_MEMORY_BYTES) as payload:
+ async for chunk in handle.stream:
+ await run_owned_in_thread(payload.write, chunk)
+ execution.completed_at = self._now()
+ outcome, settlement, _rendered = await self._settle_metered_turn(
+ execution, terminalizer, termination_origin="upstream_terminal",
+ defer_projection=True,
+ )
+ assert outcome is not None
+ assert settlement is not None
+ assert settlement.decision is not None
+ if settlement.decision.action == "return":
+ await run_owned_in_thread(payload.seek, 0)
+ rewritten_payload = await run_owned_in_thread(
+ rewrite_buffered_tool_names_file, payload, execution.response_tool_aliases,
+ )
+ response_payload = rewritten_payload or payload
+ try:
+ response_size = await run_owned_in_thread(_rewind_and_measure, response_payload)
+ if response_size <= _BUFFERED_RESPONSE_MEMORY_BYTES:
+ body = await run_owned_in_thread(response_payload.read)
+ response = web.Response(
+ status=200, body=body, content_type="application/json",
+ headers={"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff"},
+ )
+ else:
+ response = web.StreamResponse(
+ status=200,
+ headers={
+ "Cache-Control": "no-store", "Content-Length": str(response_size),
+ "Content-Type": "application/json", "X-Content-Type-Options": "nosniff",
+ },
+ )
+ await self._downstream_io(response.prepare(request))
+ execution.buffered_response = response
+ while chunk := await run_owned_in_thread(response_payload.read, _RESPONSE_CHUNK_BYTES):
+ await self._downstream_io(response.write(chunk))
+ finally:
+ if rewritten_payload is not None:
+ await run_owned_in_thread(rewritten_payload.close)
+ except OSError as exc:
+ # The upstream result still owns usage and source health. Only
+ # this gateway's delivery failed; publish that failure after
+ # settling the real producer instead of rewriting its outcome.
+ _outcome, _settlement, _rendered = await self._settle_metered_turn(
execution,
terminalizer,
termination_origin="upstream_terminal",
+ defer_projection=True,
+ )
+ detail = local_error_detail(exc)
+ terminalizer.engine_down(local_error_detail=detail)
+ failure = self._terminal_error_response(
+ execution, terminalizer, status=502, code="engine_down",
+ turn_outcome=replace(ENGINE_DOWN_TURN_OUTCOME, local_error_detail=detail),
)
- assert outcome is not None
- assert settlement is not None
+ if execution.buffered_response is not None:
+ # Content-Length exposes the truncated JSON to the caller.
+ # Do not send a second HTTP response after committed headers.
+ execution.buffered_response.force_close()
+ return execution.buffered_response
+ return failure
+ rendered = self._commit_and_render_handle_settlement(execution, terminalizer, settlement)
+ if response is None:
assert settlement.decision is not None
- if settlement.decision.action != "return":
- return self._outcome_response(
- outcome,
- error_code=settlement.decision.error_code,
- status_override=settlement.decision.downstream_status,
- rendered=rendered,
- )
- await run_owned_in_thread(payload.seek, 0)
- rewritten_payload = await run_owned_in_thread(
- rewrite_buffered_tool_names_file,
- payload,
- execution.response_tool_aliases,
+ return self._outcome_response(
+ outcome,
+ error_code=settlement.decision.error_code,
+ status_override=settlement.decision.downstream_status,
+ rendered=rendered,
)
- response_payload = rewritten_payload or payload
- try:
- response_size = await run_owned_in_thread(
- _rewind_and_measure,
- response_payload,
- )
- if response_size <= _BUFFERED_RESPONSE_MEMORY_BYTES:
- body = await run_owned_in_thread(response_payload.read)
- return web.Response(
- status=200,
- body=body,
- content_type="application/json",
- headers={
- "Cache-Control": "no-store",
- "X-Content-Type-Options": "nosniff",
- },
- )
- response = web.StreamResponse(
- status=200,
- headers={
- "Cache-Control": "no-store",
- "Content-Length": str(response_size),
- "Content-Type": "application/json",
- "X-Content-Type-Options": "nosniff",
- },
- )
- await self._downstream_io(response.prepare(request))
- while chunk := await run_owned_in_thread(
- response_payload.read,
- _RESPONSE_CHUNK_BYTES,
- ):
- await self._downstream_io(response.write(chunk))
- await self._downstream_io(response.write_eof())
- return response
- finally:
- if rewritten_payload is not None:
- await run_owned_in_thread(rewritten_payload.close)
+ if response is execution.buffered_response:
+ await self._downstream_io(response.write_eof())
+ return response
response = execution.stream_response
if response is None:
@@ -1315,6 +1332,7 @@ class ModelHubTurnGateway:
terminalizer: GatewayTurnTerminalizer,
*,
termination_origin: HandleTerminationOrigin,
+ defer_projection: bool = False,
) -> tuple[RawCallOutcome | None, HandleSettlement | None, _RenderedTurnOutcome | None]:
"""End one turn: meter the call, then settle it, then commit what it was.
@@ -1336,6 +1354,10 @@ class ModelHubTurnGateway:
without settling a second time. An ending that arrives after the turn was
already committed gets the committed rendering and no settlement, which is
the same thing the projection choke would have handed it.
+
+ A buffered response settles the producer before reading or rewriting its
+ local bytes, but defers the Turn projection until those operations finish.
+ It uses this same owner for metering and settlement, including failures.
"""
if execution.settlement_recorded:
@@ -1347,6 +1369,8 @@ class ModelHubTurnGateway:
terminalizer,
termination_origin=termination_origin,
)
+ if defer_projection:
+ return outcome, settlement, None
rendered = self._commit_and_render_handle_settlement(
execution,
terminalizer,
diff --git a/core/managed_runtime.py b/core/managed_runtime.py
index 19fe98af0..d2ddabdd7 100644
--- a/core/managed_runtime.py
+++ b/core/managed_runtime.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import contextlib
+import errno
import hashlib
import importlib.resources as package_resources
import json
@@ -31,6 +32,7 @@ from core.dependency_network import (
probe_url,
redact_url,
)
+from core.os_errors import local_os_errno
from storage.lock import (
MigrationFileLock,
MigrationLockTimeout,
@@ -68,6 +70,7 @@ _ENSURE_FAILURE_SUFFIXES = frozenset(
"install_already_running",
"install_claim_failed",
"install_failed",
+ "install_inspection_failed",
"install_lock_failed",
"install_missing_binary",
"install_target_changed",
@@ -93,6 +96,20 @@ def _is_exclusive_regular_file(info: os.stat_result) -> bool:
return not (reparse and attrs & reparse)
+def _is_regular_file(path: Path) -> bool:
+ """Absence is normal; an unreadable required input must retain its errno."""
+ try:
+ return stat.S_ISREG(path.stat().st_mode)
+ except (FileNotFoundError, NotADirectoryError):
+ return False
+
+
+def _require_execute_permission(path: Path) -> None:
+ """Make the existing execute-access rejection an explicit permission error."""
+ if not os.access(path, os.X_OK):
+ raise PermissionError(errno.EACCES, os.strerror(errno.EACCES))
+
+
def _is_reparse_point(info: os.stat_result) -> bool:
attrs = getattr(info, "st_file_attributes", 0)
reparse = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0)
@@ -156,6 +173,12 @@ class _ManagedRuntimeInstall:
mtime: float
+@dataclass(frozen=True)
+class _ManagedRuntimeFailure:
+ reason: str | None
+ os_errno: int | None = None
+
+
class ManagedRuntimeManager:
"""Shared manifest/download/verify/install core for managed runtimes."""
@@ -173,12 +196,25 @@ class ManagedRuntimeManager:
self.manifest_path = Path(manifest_path).expanduser() if manifest_path else None
self.manifest_url = manifest_url
self.offline = offline
- self._install_reason: str | None = None
+ self._install_failure = _ManagedRuntimeFailure(None)
self._download_error: dict[str, Any] | None = None
self._install_lock = install_lock_for(spec.runtime_id)
self._install_file_lock_path = self.runtime_dir / ".install.lock"
self._archive_provenance_path = self.runtime_dir / _ARCHIVE_PROVENANCE_FILENAME
+ @property
+ def _install_reason(self) -> str | None:
+ return self._install_failure.reason
+
+ @_install_reason.setter
+ def _install_reason(self, reason: str | None) -> None:
+ # Existing classification-only writers replace the complete failure.
+ # A new reason must never inherit an earlier operation's OS diagnostic.
+ self._install_failure = _ManagedRuntimeFailure(reason)
+
+ def _set_install_failure(self, reason: str, error: BaseException) -> None:
+ self._install_failure = _ManagedRuntimeFailure(reason, local_os_errno(error))
+
def ensure(
self,
*,
@@ -191,7 +227,7 @@ class ManagedRuntimeManager:
file_lock = self._acquire_mutation_lock()
except Exception as exc: # noqa: BLE001
logger.exception("Failed to acquire managed %s runtime lock", self.spec.runtime_id)
- return self._failure(self._reason("install_lock_failed"), message=str(exc))
+ return self._failure(self._reason("install_lock_failed"), message=str(exc), error=exc)
if file_lock is None:
return self._failure(
self._reason("install_already_running"),
@@ -235,6 +271,7 @@ class ManagedRuntimeManager:
manifest=manifest,
archive=archive,
message=str(exc),
+ error=exc,
)
install_dir = self._manifest_install_dir(manifest, archive)
@@ -262,20 +299,23 @@ class ManagedRuntimeManager:
existing = candidate
break
if existing is not None and not force:
+ validation_error = None
try:
validation_reason = validate_candidate(existing) if validate_candidate else None
- except Exception: # noqa: BLE001
+ except Exception as exc: # noqa: BLE001
logger.warning(
"Managed %s runtime candidate validation failed",
self.spec.runtime_id,
exc_info=True,
)
validation_reason = self._reason("candidate_validation_failed")
+ validation_error = exc
if validation_reason:
return self._failure(
validation_reason,
manifest=manifest,
archive=archive,
+ error=validation_error,
)
return self._reuse_existing_install(
existing,
@@ -307,7 +347,7 @@ class ManagedRuntimeManager:
with tarfile.open(archive_path, "r:gz") as archive_file:
safe_extract_tar(archive_file, staging_dir)
staged_binary = staging_dir / archive.bin_path
- if not staged_binary.is_file():
+ if not _is_regular_file(staged_binary):
return self._failure(
self._reason("install_missing_binary"),
manifest=manifest,
@@ -370,24 +410,27 @@ class ManagedRuntimeManager:
archive,
binary_sha256=binary_sha256,
)
+ validation_error = None
try:
validation_reason = (
validate_candidate(installed_binary)
if validate_candidate is not None
else None
)
- except Exception: # noqa: BLE001
+ except Exception as exc: # noqa: BLE001
logger.warning(
"Managed %s runtime candidate validation failed",
self.spec.runtime_id,
exc_info=True,
)
validation_reason = self._reason("candidate_validation_failed")
+ validation_error = exc
if validation_reason:
return self._failure(
validation_reason,
manifest=manifest,
archive=archive,
+ error=validation_error,
)
self._write_current_pointer(install_dir, manifest, archive)
candidate_install_dir = None
@@ -452,18 +495,20 @@ class ManagedRuntimeManager:
manifest=manifest,
archive=archive,
message=str(error),
+ error=error,
)
def resolve_binary(self) -> Path | None:
"""Resolve an already installed runtime without performing network I/O."""
+ self._install_reason = None
inspection_reason = f"{self.spec.runtime_id}_install_inspection_failed"
try:
pointer = json.loads((self.runtime_dir / "current.json").read_text(encoding="utf-8"))
except FileNotFoundError:
return None
- except (OSError, RecursionError, UnicodeError, ValueError):
- self._install_reason = inspection_reason
+ except (OSError, RecursionError, UnicodeError, ValueError) as exc:
+ self._set_install_failure(inspection_reason, exc)
return None
self._install_reason = inspection_reason
@@ -540,12 +585,13 @@ class ManagedRuntimeManager:
and all(metadata.get(field) == pointer.get(field) for field in digest_fields)
and metadata_bin_path == bin_path
and binary_integrity_valid
- and binary.is_file()
- and (not self.spec.binary_artifact or os.access(binary, os.X_OK))
+ and _is_regular_file(binary)
and self._record_matches_configured_source(metadata)
and self._record_install_dir_matches(install_dir, metadata)
):
return None
+ if self.spec.binary_artifact:
+ _require_execute_permission(binary)
manifest = self._load_manifest(allow_network=False)
selected_is_installed = False
@@ -561,22 +607,26 @@ class ManagedRuntimeManager:
archive.sha256,
)
if selected_is_installed:
+ self._install_reason = None
if self._verified_manifest_binary(install_dir, manifest, archive) != binary:
- self._install_reason = inspection_reason
+ self._install_failure = _ManagedRuntimeFailure(
+ inspection_reason, self._install_failure.os_errno,
+ )
return None
elif self.spec.binary_artifact and file_sha256(binary) != binary_sha256:
self._install_reason = inspection_reason
return None
self._install_reason = None
return binary
- except (OSError, RecursionError, RuntimeError, UnicodeError, ValueError):
- self._install_reason = inspection_reason
+ except (OSError, RecursionError, RuntimeError, UnicodeError, ValueError) as exc:
+ self._set_install_failure(inspection_reason, exc)
logger.debug("Failed to resolve managed %s runtime", self.spec.runtime_id, exc_info=True)
return None
def status(self) -> dict[str, Any]:
manifest = self._load_manifest(allow_network=False)
archive = self._manifest_archive_for_platform(manifest) if manifest else None
+ manifest_failure = self._install_failure
pointer_path = self.runtime_dir / "current.json"
pointer: dict[str, Any] = {}
binary: Path | None = None
@@ -600,6 +650,10 @@ class ManagedRuntimeManager:
else:
binary = None
self._install_reason = self._reason("install_inspection_failed")
+ if binary is None and self._install_reason is None:
+ # A missing pointer does not erase this status read's manifest
+ # failure; an actual installed-inspection failure takes priority.
+ self._install_failure = manifest_failure
matches_manifest = False if binary is not None and manifest and archive else None
if matches_manifest is not None and isinstance(pointer.get("install_dir"), str):
with contextlib.suppress(Exception): # noqa: BLE001
@@ -618,6 +672,7 @@ class ManagedRuntimeManager:
"manifest": self._manifest_status_payload(manifest),
"archive": self._archive_status_payload(archive),
"reason": self._install_reason if binary is None else None,
+ "os_errno": self._install_failure.os_errno if binary is None else None,
"download_error": self._download_error,
}
@@ -1587,6 +1642,7 @@ class ManagedRuntimeManager:
raise NotImplementedError
def _binary_matches_manifest(self, binary: Path, manifest: ManagedRuntimeManifest) -> bool:
+ self._install_reason = None
return self._binary_version(binary) == manifest.runtime_version
def load_manifest_for_diagnostics(self) -> ManagedRuntimeManifest | None:
@@ -1603,29 +1659,30 @@ class ManagedRuntimeManager:
allow_network: bool,
persist_remote_cache: bool = True,
) -> ManagedRuntimeManifest | None:
+ self._install_reason = None
payload: bytes
loaded_from: str
cache_remote = False
if self.manifest_path is not None:
- if not self.manifest_path.is_file():
- self._install_reason = self._reason("manifest_missing")
- return None
try:
+ if not _is_regular_file(self.manifest_path):
+ self._install_reason = self._reason("manifest_missing")
+ return None
payload = self.manifest_path.read_bytes()
- except OSError:
- self._install_reason = self._manifest_path_read_error_reason()
+ except OSError as exc:
+ self._set_install_failure(self._manifest_path_read_error_reason(), exc)
return None
loaded_from = str(self.manifest_path)
elif self.manifest_url:
cached_manifest = self._remote_manifest_cache_path()
if self.offline or not allow_network:
- if not cached_manifest.is_file():
- self._install_reason = self._reason("manifest_unavailable_offline")
- return None
try:
+ if not _is_regular_file(cached_manifest):
+ self._install_reason = self._reason("manifest_unavailable_offline")
+ return None
payload = cached_manifest.read_bytes()
- except OSError:
- self._install_reason = self._reason("manifest_unavailable_offline")
+ except OSError as exc:
+ self._set_install_failure(self._reason("manifest_unavailable_offline"), exc)
return None
loaded_from = f"cache:{self.manifest_url}"
else:
@@ -1641,7 +1698,7 @@ class ManagedRuntimeManager:
)
except Exception as exc: # noqa: BLE001
logger.exception("Failed to download %s manifest", self.spec.runtime_id)
- self._install_reason = self._reason("manifest_download_failed")
+ self._set_install_failure(self._reason("manifest_download_failed"), exc)
self._download_error = dependency_error_details(exc, self.manifest_url)
return None
loaded_from = self.manifest_url
@@ -1649,15 +1706,18 @@ class ManagedRuntimeManager:
else:
try:
resource = package_resources.files(self.spec.package).joinpath(self.spec.manifest_resource)
- except Exception: # noqa: BLE001
- resource = None
- if resource is None or not resource.is_file():
- self._install_reason = self._reason("manifest_missing")
+ except Exception as exc: # noqa: BLE001
+ self._set_install_failure(self._reason("manifest_missing"), exc)
return None
try:
+ if resource is None or not (
+ _is_regular_file(resource) if isinstance(resource, Path) else resource.is_file()
+ ):
+ self._install_reason = self._reason("manifest_missing")
+ return None
payload = resource.read_bytes()
- except OSError:
- self._install_reason = self._reason("manifest_missing")
+ except OSError as exc:
+ self._set_install_failure(self._reason("manifest_missing"), exc)
return None
loaded_from = f"package:{self.spec.manifest_resource}"
@@ -1771,8 +1831,9 @@ class ManagedRuntimeManager:
return archive
def _resolve_manifest_archive(self, archive: ManagedRuntimeArchive) -> Path | None:
+ self._install_reason = None
cached = self.runtime_dir / "downloads" / self._archive_cache_name(archive)
- if cached.is_file() and self._downloaded_archive_matches(cached, archive):
+ if _is_regular_file(cached) and self._downloaded_archive_matches(cached, archive):
return cached
if self.offline:
self._install_reason = self._reason("archive_unavailable_offline")
@@ -1801,7 +1862,7 @@ class ManagedRuntimeManager:
except Exception as exc: # noqa: BLE001
logger.exception("Failed to download %s archive", self.spec.runtime_id)
temporary.unlink(missing_ok=True)
- self._install_reason = self._reason("archive_download_failed")
+ self._set_install_failure(self._reason("archive_download_failed"), exc)
self._download_error = dependency_error_details(exc, archive.url)
return None
@@ -1859,7 +1920,12 @@ class ManagedRuntimeManager:
) -> Path | None:
try:
metadata = json.loads((install_dir / self.spec.metadata_filename).read_text(encoding="utf-8"))
- except Exception: # noqa: BLE001
+ except FileNotFoundError:
+ # Alternate candidate directories may not exist. Their absence
+ # must not replace a failure from an actual installed candidate.
+ return None
+ except Exception as exc: # noqa: BLE001
+ self._set_install_failure(self._reason("install_inspection_failed"), exc)
return None
bin_path = metadata.get("bin_path", self.spec.default_bin_path)
if not isinstance(bin_path, str) or archive_path_is_unsafe(bin_path):
@@ -1867,15 +1933,17 @@ class ManagedRuntimeManager:
try:
install_dir_resolved = install_dir.resolve(strict=True)
binary = (install_dir_resolved / bin_path).resolve(strict=True)
- except (OSError, RuntimeError):
+ regular_file = _is_regular_file(binary)
+ if install_dir_resolved not in binary.parents or not regular_file:
+ return None
+ if self.spec.binary_artifact:
+ _require_execute_permission(binary)
+ except FileNotFoundError:
return None
- if (
- install_dir_resolved not in binary.parents
- or not binary.is_file()
- or self.spec.binary_artifact
- and not os.access(binary, os.X_OK)
- ):
+ except (OSError, RuntimeError) as exc:
+ self._set_install_failure(self._reason("install_inspection_failed"), exc)
return None
+ self._install_reason = None
target = self._install_target_identity(manifest, archive)
target_platform = target.pop("platform")
metadata_platform = metadata.get("platform")
@@ -1913,7 +1981,8 @@ class ManagedRuntimeManager:
):
return None
if not self._binary_matches_manifest(binary, manifest):
- self._install_reason = self._reason("binary_not_runnable")
+ if self._install_reason != self._reason("binary_not_runnable"):
+ self._install_reason = self._reason("binary_not_runnable")
return None
return binary
@@ -2055,6 +2124,7 @@ class ManagedRuntimeManager:
manifest=manifest,
archive=archive,
message=str(exc),
+ error=exc,
)
payload = self._success_payload(binary, install_dir, manifest, archive, changed=False)
if reason:
@@ -2090,8 +2160,14 @@ class ManagedRuntimeManager:
archive: ManagedRuntimeArchive | None = None,
message: str | None = None,
skipped: bool = False,
+ error: Exception | None = None,
) -> dict[str, Any]:
- self._install_reason = reason
+ failure = (
+ _ManagedRuntimeFailure(reason, local_os_errno(error))
+ if error is not None or self._install_failure.reason != reason
+ else self._install_failure
+ )
+ self._install_failure = failure
return {
"ok": False,
"installed": False,
@@ -2108,6 +2184,7 @@ class ManagedRuntimeManager:
"platform": archive.platform if archive else runtime_platform_tag(),
"path": None,
"download_error": self._download_error,
+ **({"os_errno": failure.os_errno} if failure.os_errno is not None else {}),
}
def _reason(self, suffix: str) -> str:
diff --git a/core/message_mirror.py b/core/message_mirror.py
index b496b3d12..d6eb7b989 100644
--- a/core/message_mirror.py
+++ b/core/message_mirror.py
@@ -112,7 +112,9 @@ def _append_quietly(conn, **kwargs) -> Optional[dict]:
the realtime ``message.new`` publish for a row that didn't materialize.
"""
try:
- return messages_service.append(conn, **kwargs)
+ # Internal publication retains this snapshot; each browser recipient is
+ # projected by the SSE boundary, independently of transcript reads.
+ return messages_service.append(conn, include_local_error_detail=True, **kwargs)
except IntegrityError:
logger.debug(
"mirror: skipped duplicate native_message_id %s on platform %s",
@@ -459,6 +461,7 @@ def persist_agent_message(
text=text,
content=content,
metadata=metadata,
+ include_local_error_detail=True,
)
# Recompute the session's inbox row so the realtime event can patch
# the browser without a refetch. avibe-only: the workbench inbox is
diff --git a/core/os_errors.py b/core/os_errors.py
new file mode 100644
index 000000000..d9692e483
--- /dev/null
+++ b/core/os_errors.py
@@ -0,0 +1,41 @@
+"""Safe OS diagnostics shared by runtime results and user-facing failures."""
+
+import errno
+import os
+import ssl
+import urllib.error
+
+
+def local_os_errno(error: BaseException | None) -> int | None:
+ """Read a recognized OS code through explicit wrappers, never error prose."""
+
+ seen: set[int] = set()
+ while error is not None and id(error) not in seen:
+ seen.add(id(error))
+ # SSL errno values name SSL_ERROR_* categories, not operating-system
+ # errors, even though SSLError inherits OSError.
+ code = (
+ error.errno if isinstance(error, OSError) and not isinstance(error, ssl.SSLError)
+ else getattr(error, "os_errno", None)
+ )
+ if type(code) is int and code in errno.errorcode:
+ return code
+ cause = error.__cause__
+ if cause is None and isinstance(error, urllib.error.URLError) and isinstance(error.reason, BaseException):
+ cause = error.reason
+ error = cause
+ return None
+
+
+def local_error_detail(error: BaseException) -> str | None:
+ """Publish the system message without filenames, credentials, or payloads."""
+
+ return format_os_errno(local_os_errno(error))
+
+
+def format_os_errno(code: int | None) -> str | None:
+ """Format only recognized numeric OS codes from internal result contracts."""
+
+ if type(code) is not int or code not in errno.errorcode:
+ return None
+ return f"[Errno {code}] {os.strerror(code)}"
diff --git a/core/process_isolation.py b/core/process_isolation.py
index 6c4cb335f..01fc04e20 100644
--- a/core/process_isolation.py
+++ b/core/process_isolation.py
@@ -13,7 +13,7 @@ import signal
import subprocess
import time
from dataclasses import dataclass
-from typing import Any, Literal
+from typing import Any, Callable, Literal
import psutil
@@ -72,12 +72,18 @@ def process_identity_subprocess_env(marker: str) -> dict[str, str]:
def capture_spawned_process_identity(
pid: int,
marker: str,
+ *,
+ on_error: Callable[[BaseException], None] | None = None,
) -> PersistedProcessIdentity | None:
if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:
return None
try:
create_time = float(psutil.Process(pid).create_time())
- except (psutil.Error, OSError, TypeError, ValueError, OverflowError):
+ except (psutil.Error, OSError, TypeError, ValueError, OverflowError) as exc:
+ # Callers may retain a safe diagnostic without changing the fail-closed
+ # identity result or gaining authority to signal an unverified pid.
+ if on_error is not None:
+ on_error(exc)
return None
if not math.isfinite(create_time) or create_time <= 0:
return None
@@ -860,6 +866,7 @@ def reap_marked_processes(
*,
worker_fingerprint: str,
terminate_timeout: float = DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS,
+ on_error: Callable[[BaseException], None] | None = None,
) -> ProcessReapOutcome:
"""Stop every process that inherited a managed tree's marker, wherever it is.
@@ -890,7 +897,9 @@ def reap_marked_processes(
_gone, alive = psutil.wait_procs(alive, timeout=terminate_timeout)
if not alive and not _processes_carrying_marker(worker_fingerprint):
return "reaped"
- except Exception:
+ except Exception as exc:
+ if on_error is not None:
+ on_error(exc)
logger.warning("Could not confirm every %s process carrying its marker exited", label, exc_info=True)
return "unconfirmed"
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index f204efb14..a2273f7f4 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -6543,6 +6543,7 @@ class ScheduledTaskService:
if session_id and session_id == run.get("session_id")
else None
),
+ local_error_detail=notice.get("local_error_detail"),
delivery=rung,
)
except Exception as exc:
diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.py
index bf7dc8206..88a6bbe34 100644
--- a/docs/plans/model-hub-contracts/adapter-interface.py
+++ b/docs/plans/model-hub-contracts/adapter-interface.py
@@ -151,6 +151,9 @@ class RawCallOutcome:
# by L1. Display-only: classification never reads it, it is never persisted
# into events or provenance, and it stays out of repr so logs cannot echo it.
upstream_detail: str | None = field(default=None, repr=False)
+ # Recognized local OS failure only, never an upstream code or error prose.
+ # Display-only; does not participate in classification or Source health.
+ os_errno: int | None = None
class ObservationOutcome(str, Enum):
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index cec6a0a3f..7be0bbb36 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -1274,6 +1274,18 @@ canceled or other record without a terminal error supersedes older error display
Success uses exactly `{ok: true, contract_version: 10, provenance: TurnProvenance | null}`;
there is no `success` field or envelope exception.
+Local `engine_down` records may also contain `local_error_detail`, an OS-generated
+errno and system message. Failure notifications snapshot the same field in their
+metadata so the collapsed details remain available if the provenance read fails.
+The snapshot is management-only: transcript and live-event responses remove it
+for chat-only readers. Durable owed notices retain and replay the same snapshot.
+It never contains exception filenames, arbitrary exception text, or upstream
+payloads; it does not change summary copy, classification, or authorization.
+The internal `RawCallOutcome.os_errno` optionally carries a recognized local OS
+code through an engine-down completed/streamed handle. L2 and provenance format
+it using the same validated OS formatter; upstream error codes cannot populate
+it. Runtime status retains path, reason, and errno from one installed inspection.
+
New `terminal_error` records may contain `http_status` (integer 100-599 or null) and
`upstream_error_code` (a recognized upstream machine code or null). The existing
`UPSTREAM_MACHINE_ERROR_CODES` authority owns code membership. When `model_not_found`
diff --git a/docs/plans/model-hub-contracts/turn-provenance.schema.json b/docs/plans/model-hub-contracts/turn-provenance.schema.json
index 48c325279..826bf93bc 100644
--- a/docs/plans/model-hub-contracts/turn-provenance.schema.json
+++ b/docs/plans/model-hub-contracts/turn-provenance.schema.json
@@ -167,6 +167,10 @@
]
},
"stream_started": { "type": "boolean" },
+ "local_error_detail": {
+ "type": "string",
+ "description": "Optional local OS errno and system message. Produced from numeric errno only; never contains exception paths, upstream text, credentials, or request bodies. Historical records may omit it."
+ },
"http_status": {
"type": ["integer", "null"],
"minimum": 100,
diff --git a/docs/plans/model-hub-local-error-details.md b/docs/plans/model-hub-local-error-details.md
new file mode 100644
index 000000000..47fb38d03
--- /dev/null
+++ b/docs/plans/model-hub-local-error-details.md
@@ -0,0 +1,112 @@
+# Local gateway error details
+
+## Contract
+
+- Keep the existing localized gateway-failure summary and retry behavior.
+- Preserve the operating-system reason for local runtime failures, including
+ ENOSPC, EACCES, EROFS, and EMFILE, through runtime installation and gateway
+ preparation. Only a numeric OS errno and its system message are public:
+ exception filenames, credentials, request bodies, and arbitrary exception
+ text are not diagnostic inputs.
+- The exact gateway Turn owns the diagnostic. Preserve existing ambiguity,
+ cancellation, and concurrent-request ownership guards.
+- Store the optional `local_error_detail` on the terminal provenance error and
+ the notification metadata. Reuse `FailureDetails` for a collapsed plain-text
+ display, including when the provenance read is unavailable. Management-only
+ visibility is enforced by transcript and live-event projections, not just the
+ existing details panel. Public metadata reads recursively redact the field.
+- Carry the snapshot inside the existing `turn_failure_notification` settlement
+ contract so immediate, deferred, and late-attached Runs retain it. Owed notices
+ copy it and replay it without depending on a still-retained provenance record.
+- Read OS reasons through explicit exception causes and preserve errno at each
+ exception-to-result conversion in runtime installation. Do not infer a cause
+ from arbitrary exception text or unrelated implicit exception context.
+- Existing records and notifications without the optional field keep their
+ current behavior. No migration, new dependency, restart, or deployment.
+
+## Validation
+
+Exercise a real runtime-lock OSError through the installer, runtime adapter,
+service, gateway, notification, and persisted provenance. Assert the summary
+is unchanged and the diagnostic survives. Verify the UI expands/collapses the
+diagnostic with and without a provenance record, including remounting, and
+retains its authorization boundary. Run focused Python/UI tests, Ruff, and the
+UI production build. GitHub CI and current-head Codex review gate delivery.
+
+Review regressions additionally cover real supervisor spawn failures, installer
+claim/pointer/candidate-validation failures, immediate/deferred durable replay,
+and manager versus chat-only history/live-event reads.
+
+## Boundary audit and scope decision
+
+The installer-loss class recurred on reviewed heads `11a2165ea` and `9b4b150dc`.
+Forwarding caught exceptions only at `_failure()` call sites is insufficient:
+manifest/archive helpers convert exceptions to a stored reason and a sentinel
+before the caller builds its failure result. Evolve that existing reason owner
+into a reason/errno pair, clear diagnostics whenever a reason is replaced, and
+preserve explicit causes through the shared OS-error extractor. Do not change
+download retries, cache fallback, or best-effort cleanup into terminal failures.
+Verify failed -> successful -> unrelated failed operations do not reuse errno.
+
+The other consumer boundaries are independent of retry permission and of how a
+message became visible. A management-authorized local snapshot can be expanded
+on a detached/cross-Session replay without a Turn read or Retry action. Normal
+append and suppressed-message promotion must both retain the internal snapshot
+until recipient projection. Reuse their existing projection option and the
+existing backend-failure identity check instead of creating another detail path.
+
+The class recurred on `83a304338`: installed-runtime inspection and the admitted
+call's completed `engine_down` outcome also erase errors. Audit the three entry
+paths (installation, installed inspection, invocation) and their neighboring
+record/health/loopback conversions before another push. Use the existing status
+snapshot as the supervisor's single inspection result (path, reason, errno);
+do not mix two inspections. Add optional numeric errno to the existing
+`RawCallOutcome`, with one validated formatter at the service boundary.
+Preserve errno in process-record and health sentinels as well, scoped to the
+failed operation and captured before cleanup can replace it. Keep cleanup,
+retry, process exclusion, source health, and transport ownership policies
+unchanged. No exception prose or upstream body becomes a local diagnostic.
+
+On `1c1f52c50`, inspect the remaining consumers of those owners: Retry reloads a
+notice into both a POST reply and `message.updated`, and process identity capture
+has its own fail-closed sentinel. Preserve internal message diagnostics until
+both HTTP and event recipient projection; cover new and updated event types.
+Keep process capture's existing `None` behavior for all callers, adding an
+optional error observer used by the supervisor to retain only numeric errno.
+Neither capture failures nor diagnostics authorize killing an unverified process.
+Preserve the current status operation's manifest failure when there is no
+installed pointer; an actual inspection failure replaces it. CI's existing Git
+runtime, Doctor localization, and interface-mirror checks cover those consumers.
+
+On `0586e6bcd`, boolean filesystem probes, marker recovery, and the gateway's
+own response spool erase local failures. The reported Harness exposure was
+disproved by real list/detail/bootstrap requests: `_harness_store` already
+requests public metadata, and `_enrich_runs` applies the recursive redactor.
+Keep that existing owner and add regressions rather than another filter. Use
+errno-preserving regular-file probes for required runtime inputs. Recovery's
+marker sweep remains the authority for retaining a record; retain its failed
+operation's errno across the subsequent record write, without changing reap
+policy. Keep upstream settlement/metering separate from a gateway buffer failure:
+the original call still owns usage and source health, while the gateway owns
+the failed local delivery and its Turn diagnostic. Do not commit buffered
+success before the local reads/rewrites needed to produce the response finish.
+The CI structure guards also require every ending to use `_settle_metered_turn`
+and capture completion where the body is consumed. Keep buffered consumption in
+the response owner and defer only projection through that existing settlement
+wrapper; do not introduce another route to handle settlement or weaken guards.
+
+On `a057c8ed1`, pair a failed spawn rollback with the record error that actually
+blocks recovery, rather than the superseded spawn cause. For required executable
+files, the permission predicate is itself a policy rejection: preserve that
+denial as EACCES at one shared check instead of retaining a bare boolean.
+Keep required-file stat failures distinct, and do not run or chmod rejected
+binaries to obtain a diagnostic. Cover status, candidate verification, actual
+non-executable mode bits, and a denied-access predicate, alongside two different
+spawn/rollback failures and successful cleanup.
+
+## Known by design
+
+- Historical errors cannot acquire diagnostics that were discarded before this
+ change. Ambiguous or canceled turns do not borrow another request's details.
+- This change reports local OS errors; it does not retain arbitrary upstream
+ error bodies or alter gateway recovery.
diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.md
index 05b560fb6..496d90cfa 100644
--- a/docs/plans/model-hub.md
+++ b/docs/plans/model-hub.md
@@ -1276,6 +1276,19 @@ land as standalone prose.
never written to resolution events, probes, or persisted provenance, and lives only on
the in-memory turn projection that renders this turn's reply.
+For `turn.engine_down`, an optional `local_error_detail` carries the numeric OS
+errno and its system message, such as `[Errno 28] No space left on device`.
+It does not change summary copy or classification. The exact Turn retains it
+in `terminal_error.local_error_detail` and the failure notification's metadata.
+The existing collapsed notification details display it even when the provenance
+read is unavailable. Only recognized OS errno values produce this field; paths,
+arbitrary exception strings, request bodies, and credentials are excluded.
+Existing provenance attribution and details authorization rules still apply.
+Installation, installed-runtime inspection, and invocation preserve the code,
+including process-record/health failures and local response-buffer errors.
+Invocation outcomes carry optional numeric `os_errno` without changing the
+existing completed-handle, stream settlement, or Source-health contracts.
+
`source_transition_persisted` is an optional backend projection fact whose presence is
required only for `turn.streamed_fallback`. UI consumers deliberately do not consume it:
the selected copy key already carries the complete user-visible truth, following the
diff --git a/storage/background.py b/storage/background.py
index dffb46d3a..b3347dfba 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -2046,6 +2046,11 @@ def _owed_failure_notice_for_transition(
"turn_id": turn_id,
"turn_notification_delivered": bool(turn_notification.get("delivered")),
"turn_notification_ack_evidence": turn_notification.get("ack_evidence"),
+ **(
+ {"local_error_detail": turn_notification["local_error_detail"]}
+ if isinstance(turn_notification.get("local_error_detail"), str)
+ else {}
+ ),
"turn_fallback_run_id": fallback_run_id or None,
TURN_PARTICIPANT_RUN_IDS_METADATA_KEY: participant_run_ids if turn_id else [],
# Optional, and only ever a copy selector. The lane a notice belongs to is
diff --git a/storage/message_deliveries.py b/storage/message_deliveries.py
index b30d78fcf..b623a8adc 100644
--- a/storage/message_deliveries.py
+++ b/storage/message_deliveries.py
@@ -555,14 +555,17 @@ def metadata_without_delegated_owner(metadata: object) -> dict[str, Any]:
return result
-def public_message_metadata(metadata: dict[str, Any]) -> dict[str, Any]:
- """Hide execution identity in both queued and accepted public messages."""
+def public_message_metadata(
+ metadata: dict[str, Any], *, include_local_error_detail: bool = False,
+) -> dict[str, Any]:
+ """Hide execution identity and management-only diagnostics on public reads."""
def without_private_fields(value: Any) -> Any:
if isinstance(value, dict):
return {
key: without_private_fields(item) for key, item in value.items()
if key not in {"resource_user_context", "delegated_memory_owner"}
and not str(key).startswith(("_web_push_", "_memory_"))
+ and (include_local_error_detail or key != "local_error_detail")
}
if isinstance(value, list):
return [without_private_fields(item) for item in value]
diff --git a/storage/messages_service.py b/storage/messages_service.py
index 347fbeff2..c80c6588c 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -92,6 +92,7 @@ def _row_to_payload(
row: dict[str, Any],
*,
include_private_metadata: bool = False,
+ include_local_error_detail: bool = False,
conn: Connection | None = None,
) -> dict[str, Any]:
try:
@@ -120,7 +121,7 @@ def _row_to_payload(
elif not include_private_metadata:
from storage.message_deliveries import public_message_metadata
- metadata = public_message_metadata(metadata)
+ metadata = public_message_metadata(metadata, include_local_error_detail=include_local_error_detail)
return {
"id": row["id"],
"scope_id": row.get("scope_id"),
@@ -575,6 +576,7 @@ def append(
parent_native_message_id: Optional[str] = None,
delivered_at: Optional[str] = None,
read_at: Optional[str] = None,
+ include_local_error_detail: bool = False,
) -> dict[str, Any]:
"""Insert a new message row and return its payload.
@@ -622,7 +624,7 @@ def append(
"read_at": read_at,
}
conn.execute(messages.insert().values(**payload))
- return _row_to_payload(payload)
+ return _row_to_payload(payload, include_local_error_detail=include_local_error_detail)
def get_message(
@@ -630,6 +632,7 @@ def get_message(
message_id: str,
*,
session_id: Optional[str] = None,
+ include_local_error_detail: bool = False,
) -> Optional[dict[str, Any]]:
"""Load one message by id, optionally requiring its owning session."""
@@ -642,7 +645,7 @@ def get_message(
# The ``message.new`` publisher loads the live row through here, so the
# sender resolved on delivery is the one the following reload shows.
return attach_sender_labels(
- conn, [_row_to_payload(dict(row), conn=conn)]
+ conn, [_row_to_payload(dict(row), conn=conn, include_local_error_detail=include_local_error_detail)]
)[0]
@@ -671,6 +674,7 @@ def get_native_message(
platform: str,
scope_id: str | None,
native_message_id: str,
+ include_local_error_detail: bool = False,
) -> Optional[dict[str, Any]]:
"""Load one accepted Message by its conversation-scoped native identity."""
@@ -690,7 +694,7 @@ def get_native_message(
.where(messages.c.native_message_id == native_message_id)
.limit(1)
).mappings().first()
- return _row_to_payload(dict(row)) if row else None
+ return _row_to_payload(dict(row), include_local_error_detail=include_local_error_detail) if row else None
def promote_suppressed_native_message(
@@ -704,6 +708,7 @@ def promote_suppressed_native_message(
text: str,
content: Optional[dict[str, Any]] = None,
metadata: Optional[dict[str, Any]] = None,
+ include_local_error_detail: bool = False,
) -> Optional[dict[str, Any]]:
"""Turn local-only history into a receipt after outward delivery succeeds.
@@ -754,6 +759,7 @@ def promote_suppressed_native_message(
platform=platform,
scope_id=scope_id,
native_message_id=native_message_id,
+ include_local_error_detail=include_local_error_detail,
)
@@ -860,6 +866,10 @@ def list_session_messages(
and returns no forward cursor.
"""
+ include_local_error_detail = (
+ authorization_context is not None
+ and require_instance_role(authorization_context, "viewer").can_manage_instance
+ )
query = select(messages).where(messages.c.session_id == session_id)
if types is not None:
query = query.where(messages.c.type.in_(list(types)))
@@ -951,7 +961,8 @@ def list_session_messages(
)
older = [
_row_to_payload(
- dict(row), include_private_metadata=include_private_metadata, conn=conn
+ dict(row), include_private_metadata=include_private_metadata,
+ include_local_error_detail=include_local_error_detail, conn=conn,
)
for row in conn.execute(older_q).mappings().all()
]
@@ -961,7 +972,8 @@ def list_session_messages(
anchor_rows = [
_row_to_payload(
- dict(row), include_private_metadata=include_private_metadata, conn=conn
+ dict(row), include_private_metadata=include_private_metadata,
+ include_local_error_detail=include_local_error_detail, conn=conn,
)
for row in conn.execute(query.where(messages.c.id == anchor_id)).mappings().all()
]
@@ -978,7 +990,8 @@ def list_session_messages(
)
newer = [
_row_to_payload(
- dict(row), include_private_metadata=include_private_metadata, conn=conn
+ dict(row), include_private_metadata=include_private_metadata,
+ include_local_error_detail=include_local_error_detail, conn=conn,
)
for row in conn.execute(newer_q).mappings().all()
]
@@ -1006,7 +1019,8 @@ def list_session_messages(
conn,
[
_row_to_payload(
- dict(row), include_private_metadata=include_private_metadata, conn=conn
+ dict(row), include_private_metadata=include_private_metadata,
+ include_local_error_detail=include_local_error_detail, conn=conn,
)
for row in conn.execute(query).mappings().all()
],
@@ -1039,7 +1053,8 @@ def list_session_messages(
conn,
[
_row_to_payload(
- dict(row), include_private_metadata=include_private_metadata, conn=conn
+ dict(row), include_private_metadata=include_private_metadata,
+ include_local_error_detail=include_local_error_detail, conn=conn,
)
for row in conn.execute(query).mappings().all()
],
@@ -1073,7 +1088,8 @@ def list_session_messages(
conn,
[
_row_to_payload(
- dict(row), include_private_metadata=include_private_metadata, conn=conn
+ dict(row), include_private_metadata=include_private_metadata,
+ include_local_error_detail=include_local_error_detail, conn=conn,
)
for row in conn.execute(query).mappings().all()
],
diff --git a/tests/test_backend_failure_retry.py b/tests/test_backend_failure_retry.py
index 87aaf18f5..87d82d742 100644
--- a/tests/test_backend_failure_retry.py
+++ b/tests/test_backend_failure_retry.py
@@ -193,6 +193,44 @@ def _retry_notice(tmp_path, *, backend="claude", not_written=False, content=None
return session_id, notice, turn, inputs
[email protected]("can_manage", [True, False])
+def test_retry_notice_preserves_authorized_local_details(isolated_state, tmp_path, monkeypatch, can_manage):
+ # Retry replaces the existing UI row from its POST reply/event. A default
+ # public reload used to erase the only snapshot when provenance is absent.
+ from types import SimpleNamespace
+ from vibe import ui_server
+ from vibe.sse_broker import broker
+
+ session_id, notice, _turn, _inputs = _retry_notice(tmp_path)
+ detail = "[Errno 28] No space left on device"
+ with create_sqlite_engine().begin() as conn:
+ conn.execute(
+ update(messages).where(messages.c.id == notice["id"]).values(
+ metadata_json=json.dumps({**notice["metadata"], "local_error_detail": detail}),
+ )
+ )
+ monkeypatch.setattr(ui_server, "_has_runtime_management_access", lambda _context: can_manage)
+ published = []
+ monkeypatch.setattr(broker, "publish", lambda event, data: published.append((event, data)))
+ client = ui_server.app.test_client()
+ with patch("vibe.internal_client.dispatch_async", _accepted_dispatch(session_id)):
+ response = client.post(
+ f"/api/sessions/{session_id}/messages", headers=csrf_headers(client),
+ json={"retry_for": notice["id"]},
+ )
+ assert response.status_code == 201
+ returned = response.get_json()["retry_notice"]
+ assert ("local_error_detail" in returned["metadata"]) is can_manage
+ if can_manage:
+ assert returned["metadata"]["local_error_detail"] == detail
+ event, internal = next((event, data) for event, data in published if event == "message.updated")
+ assert internal["metadata"]["local_error_detail"] == detail
+ projected = ui_server._workbench_event_payload_for_context(
+ SimpleNamespace(), event, json.dumps({"type": event, "data": internal}),
+ )
+ assert ("local_error_detail" in json.loads(projected)["data"]["metadata"]) is can_manage
+
+
@pytest.mark.parametrize("backend", ["claude", "codex", "opencode"])
def test_failure_retry_canonical_continue_and_draft(isolated_state, tmp_path, backend):
from vibe.ui_server import app
diff --git a/tests/test_model_hub_local_error_details.py b/tests/test_model_hub_local_error_details.py
new file mode 100644
index 000000000..3963bf569
--- /dev/null
+++ b/tests/test_model_hub_local_error_details.py
@@ -0,0 +1,822 @@
+"""Local OS failures survive the real gateway-to-notification boundaries."""
+
+from __future__ import annotations
+
+import errno
+import json
+import os
+import ssl
+from types import SimpleNamespace
+from unittest.mock import AsyncMock
+
+import aiohttp
+import pytest
+
+from core.backend_failure import emit_backend_failure
+from core.os_errors import local_error_detail
+from core.handlers.model_hub.provenance import BoundedProvenanceStore
+from core.handlers.model_hub.service import ModelHubError
+from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway
+from core.run_settlement import SETTLED_BY_TERMINAL_RESULT
+from modules.im import MessageContext
+from tests.test_model_hub_l3 import _assert_valid, _service, _source
+from tests.test_ui_session_stream import isolated_state # noqa: F401
+from vibe.i18n import t as i18n_t
+from vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter
+from vibe.model_hub_runtime.installer import EngineRuntimeManager
+from vibe.model_hub_runtime.state import EngineStateStore
+from vibe.model_hub_runtime.supervisor import EngineSupervisor, EngineUnavailableError
+
+
[email protected]("code", [errno.ENOSPC, errno.EACCES, errno.EROFS, errno.EMFILE])
[email protected]("stage", ["install_lock", "invoke_spawn", "record_read", "record_write"])
+async def test_runtime_error_reaches_notice_and_persisted_details(tmp_path, monkeypatch, code, stage):
+ # Existing gateway tests replace sync_sources with a generic failure, which
+ # misses the installer -> adapter boundary that discarded the real errno.
+ installer = EngineRuntimeManager(runtime_dir=tmp_path / "engine", offline=True)
+
+ def fail_lock():
+ raise OSError(code, "private credential=fixture-secret", "/private/凭证.json")
+
+ monkeypatch.setattr(installer, "_acquire_mutation_lock", fail_lock)
+ state = EngineStateStore(tmp_path / "engine-state")
+ runtime = CLIProxyEngineAdapter(
+ supervisor=EngineSupervisor(installer=installer, state_store=state),
+ )
+ service = _service(tmp_path, sources=[_source("src_primary01", "Primary")])
+ # Only the external model is fake. Installation, error conversion,
+ # correlation, notification, and provenance storage use production code.
+ service.adapter.ensure_installed = runtime.ensure_installed
+ expected_status = 503
+ if stage != "install_lock":
+ from pathlib import Path
+ from tests.test_model_hub_runtime import _binding, _fixture_supervisor
+
+ def fail(*_args, **_kwargs):
+ fail_lock()
+
+ supervisor, state = _fixture_supervisor(tmp_path / "invocation", process_factory=fail)
+ credential = state.store_api_key("fixture-key", base_url="https://api.example.test/v1")
+ state.sync_sources([_binding(credential, source_id="src_primary01")])
+ runtime = CLIProxyEngineAdapter(supervisor=supervisor)
+ # Keep preparation successful so the real adapter's invocation boundary,
+ # not sync_sources/ensure_installed, owns the failure.
+ service.adapter.ensure_installed = AsyncMock()
+ service.adapter.invoke = runtime.invoke
+ if stage == "record_read":
+ read_text = Path.read_text
+
+ def read(path, *args, **kwargs):
+ if path == supervisor._engine_record_path:
+ fail()
+ return read_text(path, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "read_text", read)
+ elif stage == "record_write":
+ monkeypatch.setattr("vibe.model_hub_runtime.supervisor.write_atomic", fail)
+ expected_status = 502
+ gateway = ModelHubTurnGateway(service, language_provider=lambda: "zh")
+ turn_id = "turn-local-error"
+ base_url, token = await gateway.endpoint(
+ "codex", process_scope="/repo", turn_id=turn_id,
+ requested_model_id="shared-model", resolved_model_id="shared-model",
+ source_id="src_primary01",
+ )
+ expected = f"[Errno {code}] {os.strerror(code)}"
+ context = MessageContext(
+ user_id="U1", channel_id="C1", platform="avibe",
+ platform_specific={"turn_token": turn_id},
+ )
+ controller = SimpleNamespace(
+ config=SimpleNamespace(language="zh"),
+ model_hub_turn_gateway=gateway,
+ emit_agent_message=AsyncMock(),
+ )
+ try:
+ async with aiohttp.ClientSession(trust_env=False) as client:
+ response = await client.post(
+ f"{base_url}/v1/responses",
+ json={"model": "shared-model", "input": "ping", "stream": False},
+ headers={"Authorization": f"Bearer {token}"},
+ )
+ assert response.status == expected_status
+ payload = await response.json()
+ summary = i18n_t("modelHub.errors.engine_down", "zh")
+ assert payload["error"]["message"] == summary
+ await emit_backend_failure(controller, context, "codex", f"API Error: {expected_status} {summary}")
+ notify, terminal = controller.emit_agent_message.call_args_list
+ assert notify.args[1:3] == ("notify", summary)
+ assert notify.kwargs["output"].metadata["local_error_detail"] == expected
+ assert terminal.kwargs["output"].metadata["turn_failure_notification"]["local_error_detail"] == expected
+ assert "private" not in json.dumps(notify.kwargs["output"].metadata)
+ finally:
+ await gateway.close()
+
+ gateway.correlation.settle(turn_id, settled_by=SETTLED_BY_TERMINAL_RESULT)
+ # A fresh store proves this is retained for later reads, not just live UI.
+ record = BoundedProvenanceStore(service.provenance.path).get(turn_id)
+ assert record["terminal_error"]["local_error_detail"] == expected
+ assert record["terminal_error"]["reason"] == "engine_down"
+ _assert_valid("turn-provenance.schema.json", record)
+ assert "fixture-secret" not in service.provenance.path.read_text()
+ assert "凭证" not in service.provenance.path.read_text()
+
+
[email protected]("stage", ["pointer", "metadata", "binary", "probe"])
[email protected]("code", [errno.EACCES, errno.EMFILE])
+def test_installed_inspection_keeps_errno_without_stale_diagnostics(tmp_path, monkeypatch, stage, code):
+ # Real installed inspection used to swallow errors before the supervisor
+ # raised; fresh installation and synthetic supervisor errors miss that gap.
+ from pathlib import Path
+ from tests.test_managed_runtime import _write_subclass_runtime_fixture
+
+ _archive, manifest = _write_subclass_runtime_fixture(tmp_path, "model-hub")
+ installer = EngineRuntimeManager(runtime_dir=tmp_path / "runtime", manifest_path=manifest)
+ installed = installer.ensure()
+ assert installed["ok"]
+ supervisor = EngineSupervisor(installer=installer, state_store=EngineStateStore(tmp_path / "state"))
+ binary = Path(installed["path"])
+ target = {
+ "pointer": installer.runtime_dir / "current.json",
+ "metadata": binary.parent / installer.spec.metadata_filename,
+ "binary": binary,
+ }.get(stage)
+ open_path = Path.open
+
+ def fail(*_args, **_kwargs):
+ raise OSError(code, "private reason", "/private/凭证")
+
+ def open_file(path, *args, **kwargs):
+ if path == target:
+ fail()
+ return open_path(path, *args, **kwargs)
+
+ installer._verified_binary_cache = None
+ with monkeypatch.context() as patch:
+ if stage == "probe":
+ patch.setattr("vibe.model_hub_runtime.installer.subprocess.run", fail)
+ else:
+ patch.setattr(Path, "open", open_file)
+ with pytest.raises(EngineUnavailableError) as raised:
+ supervisor._prepare_instance_locked()
+ assert local_error_detail(raised.value) == f"[Errno {code}] {os.strerror(code)}"
+ assert installer.status()["installed"]
+ (installer.runtime_dir / "current.json").write_text("{}")
+ with pytest.raises(EngineUnavailableError) as raised:
+ supervisor._prepare_instance_locked()
+ assert local_error_detail(raised.value) is None
+
+
+def test_supervisor_health_error_keeps_errno_before_cleanup(tmp_path, monkeypatch):
+ # Health projects request exceptions into a bool. Drive the real urllib
+ # wrapper and supervisor, whose stop operation must not replace the cause.
+ import urllib.error
+ from tests.test_model_hub_runtime import _fixture_supervisor
+
+ supervisor, _state = _fixture_supervisor(tmp_path, startup_timeout=0.05)
+
+ def fail(*_args, **_kwargs):
+ raise urllib.error.URLError(OSError(errno.EMFILE, "private", "/private/凭证"))
+
+ monkeypatch.setattr(
+ "vibe.model_hub_runtime.client.urllib.request.build_opener",
+ lambda *_args: SimpleNamespace(open=fail),
+ )
+ with pytest.raises(EngineUnavailableError) as raised:
+ supervisor.ensure_running()
+ assert local_error_detail(raised.value) == f"[Errno {errno.EMFILE}] {os.strerror(errno.EMFILE)}"
+
+
[email protected]("code", [errno.EACCES, errno.EMFILE])
+def test_spawn_identity_error_keeps_errno_and_stops_child(tmp_path, monkeypatch, code):
+ # Popen succeeds; the shared process identity capture swallows the next OS
+ # failure. Exercise that helper without changing safe orphan/stop policy.
+ import subprocess
+ import psutil
+ from tests.test_model_hub_runtime import _fixture_supervisor
+
+ spawned = []
+
+ def spawn(*args, **kwargs):
+ process = subprocess.Popen(*args, **kwargs)
+ spawned.append(process)
+ return process
+
+ original_create_time = psutil.Process.create_time
+ failed = False
+
+ def create_time(process):
+ nonlocal failed
+ if spawned and process.pid == spawned[0].pid and not failed:
+ failed = True
+ raise OSError(code, "private reason", "/private/凭证")
+ return original_create_time(process)
+
+ monkeypatch.setattr(psutil.Process, "create_time", create_time)
+ supervisor, state = _fixture_supervisor(tmp_path, process_factory=spawn)
+ try:
+ with pytest.raises(EngineUnavailableError) as raised:
+ supervisor.ensure_running()
+ assert failed and spawned[0].poll() is not None
+ assert not (state.root / "engine-process.json").exists()
+ assert local_error_detail(raised.value) == f"[Errno {code}] {os.strerror(code)}"
+ finally:
+ for process in spawned:
+ if process.poll() is None:
+ process.kill()
+ process.wait(timeout=5)
+
+
[email protected]("spawn_code", [None, errno.EMFILE])
+def test_spawn_rollback_reports_the_record_failure_that_blocks_recovery(tmp_path, monkeypatch, spawn_code):
+ from pathlib import Path
+ from tests.test_model_hub_runtime import _fixture_supervisor
+
+ def spawn(*_args, **_kwargs):
+ if spawn_code is None:
+ raise ValueError("private launch error")
+ raise OSError(spawn_code, "private launch error", "/private/凭证")
+
+ supervisor, state = _fixture_supervisor(tmp_path, process_factory=spawn)
+ record = state.root / "engine-process.json"
+ original_unlink = Path.unlink
+
+ def unlink(path, *args, **kwargs):
+ if path == record and path.exists():
+ raise PermissionError(errno.EACCES, "private cleanup error", "/private/凭证")
+ return original_unlink(path, *args, **kwargs)
+
+ with monkeypatch.context() as patch:
+ patch.setattr(Path, "unlink", unlink)
+ with pytest.raises(EngineUnavailableError) as raised:
+ supervisor.ensure_running()
+ assert raised.value.reason == "engine_untracked"
+ assert local_error_detail(raised.value) == f"[Errno {errno.EACCES}] {os.strerror(errno.EACCES)}"
+ assert record.exists()
+ assert supervisor._reap_recorded_engines_locked()
+ assert not record.exists()
+ with pytest.raises(EngineUnavailableError) as raised:
+ supervisor.ensure_running()
+ expected = f"[Errno {spawn_code}] {os.strerror(spawn_code)}" if spawn_code else None
+ assert local_error_detail(raised.value) == expected
+ assert not record.exists()
+
+
[email protected]("inspection", ["status", "candidate"])
[email protected]("denial", ["mode", "access"])
+def test_runtime_execute_permission_denial_is_a_local_diagnostic(tmp_path, monkeypatch, inspection, denial):
+ from pathlib import Path
+ from tests.test_managed_runtime import _write_subclass_runtime_fixture
+
+ if denial == "mode" and os.name == "nt":
+ pytest.skip("POSIX executable mode bits")
+ _archive, manifest_path = _write_subclass_runtime_fixture(tmp_path, "model-hub")
+ manager = EngineRuntimeManager(runtime_dir=tmp_path / "runtime", manifest_path=manifest_path)
+ installed = manager.ensure()
+ assert installed["ok"]
+ binary = Path(installed["path"])
+ manifest = manager._load_manifest(allow_network=False)
+ archive = manager._manifest_archive_for_platform(manifest)
+ mode = binary.stat().st_mode
+ original_access = os.access
+ with monkeypatch.context() as patch:
+ if denial == "mode":
+ binary.chmod(mode & ~0o111)
+ else:
+ patch.setattr(os, "access", lambda path, flags: False if Path(path) == binary else original_access(path, flags))
+ try:
+ if inspection == "status":
+ result = manager.status()
+ assert not result["installed"]
+ code = result.get("os_errno")
+ else:
+ assert manager._verified_manifest_binary(binary.parent, manifest, archive) is None
+ code = manager._install_failure.os_errno
+ assert code == errno.EACCES
+ finally:
+ binary.chmod(mode)
+ assert manager.status()["installed"]
+ assert manager._install_failure.os_errno is None
+
+
[email protected]("code", [errno.ENOSPC, None, 999999, True])
+async def test_streamed_engine_outcome_retains_safe_detail_in_projection_and_record(tmp_path, code):
+ # Stream settlement bypasses ModelHubError. Its live projection and durable
+ # terminal record are separate consumers of the actual adapter outcome.
+ from core.handlers.model_hub.adapter import RawCallOutcome, RawOutcomeKind
+ from core.handlers.model_hub.service import ResolvedInvocation
+ from tests.test_model_hub_provenance import _live_registry
+
+ service = _service(tmp_path, sources=[_source("src_primary01", "Primary")])
+ registry = _live_registry(tmp_path)
+ registry.begin_attempt(
+ "turn-live", source_id="src_primary01", resolved_model_id="shared-model",
+ channel="hub", via_mapping=False,
+ )
+ outcome = RawCallOutcome(
+ kind=RawOutcomeKind.NETWORK_ERROR, http_status=200, error_code="engine_down",
+ redacted_message=None, stream_started=True, model_id="shared-model",
+ source_id="src_primary01", os_errno=code,
+ )
+ settlement = await service.settle_handle_outcome(
+ ResolvedInvocation(
+ backend="codex", requested_model_id="shared-model",
+ source_id="src_primary01", source_label="Primary", model_id="shared-model",
+ handle=None, outcome=None,
+ ),
+ outcome,
+ termination_origin="upstream_terminal",
+ record_attempt=lambda raw, decision: registry.finish_attempt("turn-live", outcome=raw, decision=decision),
+ )
+ expected = "[Errno 28] No space left on device" if code == errno.ENOSPC else None
+ assert settlement.turn_outcome.local_error_detail == expected
+ registry.settle("turn-live", settled_by=SETTLED_BY_TERMINAL_RESULT)
+ record = BoundedProvenanceStore(tmp_path / "records.json").get("turn-live")
+ assert record["terminal_error"].get("local_error_detail") == expected
+ assert service.store.load().sources[0].state.status == "standby"
+ assert service.events.list() == []
+
+
[email protected]("error,expected", [
+ (OSError(errno.ENOSPC, "private text"), f"[Errno {errno.ENOSPC}] {os.strerror(errno.ENOSPC)}"),
+ (OSError("private text"), None),
+ (RuntimeError("private text"), None),
+ (OSError(999999, "private text"), None),
+ (ssl.SSLError(ssl.SSL_ERROR_SSL, "private TLS detail"), None),
+])
+async def test_engine_call_only_exposes_recognized_os_reasons(tmp_path, error, expected):
+ service = _service(tmp_path, sources=[_source("src_primary01", "Primary")])
+
+ async def fail():
+ raise error
+
+ with pytest.raises(ModelHubError) as raised:
+ await service._engine_call(fail())
+ assert raised.value.code == "engine_down"
+ assert raised.value.local_error_detail == expected
+
+
[email protected]("code", [errno.EACCES, errno.EMFILE])
+def test_spawn_failure_keeps_its_os_reason(tmp_path, code):
+ # A real supervisor wraps Popen failures; a synthetic adapter exception
+ # cannot catch the loss of its explicit cause.
+ from tests.test_model_hub_runtime import _fixture_supervisor
+
+ def spawn(*_args, **_kwargs):
+ raise OSError(code, "private credential=fixture-secret", "/private/凭证")
+
+ supervisor, _state = _fixture_supervisor(tmp_path, process_factory=spawn)
+ with pytest.raises(EngineUnavailableError) as raised:
+ supervisor.ensure_running()
+ assert local_error_detail(raised.value) == f"[Errno {code}] {os.strerror(code)}"
+
+
[email protected]("code", [errno.EACCES, errno.EMFILE])
+def test_engine_binary_probe_failure_keeps_errno(tmp_path, monkeypatch, code):
+ # The engine installer's version probe is another exception -> sentinel
+ # boundary; a generic fixture installer does not execute that code.
+ from tests.test_managed_runtime import _write_subclass_runtime_fixture
+
+ _archive, manifest = _write_subclass_runtime_fixture(tmp_path, "model-hub")
+ installer = EngineRuntimeManager(runtime_dir=tmp_path / "runtime", manifest_path=manifest)
+
+ def fail(*_args, **_kwargs):
+ raise OSError(code, "private reason", "/private/凭证")
+
+ monkeypatch.setattr("vibe.model_hub_runtime.installer.subprocess.run", fail)
+ result = installer.ensure()
+ assert result["reason"] == "model_hub_engine_binary_not_runnable"
+ assert result["os_errno"] == code
+
+
[email protected]("stage", ["claim", "pointer", "existing_validation", "new_validation"])
[email protected]("code", [errno.ENOSPC, errno.EACCES])
+def test_structured_installer_failures_keep_errno(tmp_path, monkeypatch, stage, code):
+ # Every exception -> failure-dict boundary must preserve errno. The original
+ # runtime-lock regression never enters the already-installed reuse branch.
+ from tests.test_managed_runtime import _fixture_runtime_manager, _write_fixture_runtime_release
+
+ manifest = tmp_path / "manifest.json"
+ _write_fixture_runtime_release(tmp_path, manifest, label="errno", version="1.0.0")
+ manager = _fixture_runtime_manager(tmp_path / "runtime", manifest_path=manifest)
+ if stage in {"pointer", "existing_validation"}:
+ assert manager.ensure()["ok"]
+
+ def fail(*_args, **_kwargs):
+ raise OSError(code, "private reason", "/private/凭证")
+
+ kwargs = {}
+ if stage == "claim":
+ kwargs["on_resolved"] = fail
+ elif stage == "pointer":
+ (manager.runtime_dir / "current.json").unlink()
+ monkeypatch.setattr(manager, "_write_current_pointer", fail)
+ else:
+ kwargs["validate_candidate"] = fail
+ result = manager.ensure(**kwargs)
+ assert not result["ok"]
+ assert result["os_errno"] == code
+
+
[email protected]("deferred", [False, True])
+async def test_failure_snapshot_survives_durable_notice_replay(tmp_path, deferred):
+ # Exercise the terminal-output -> durable Run -> owed notice -> replay path,
+ # without any live gateway or retained provenance record to fall back to.
+ from core.backend_failure import terminal_backend_failure_output
+ from core.delivery_evidence import DeliveryEvidence
+ from core.message_output import MessageOutput
+ from core.scheduled_tasks import parse_scope_id
+ from tests.test_harness_failure_visibility import _drain_service, _store
+
+ store, requests = _store(tmp_path)
+ run = requests.enqueue_agent_run(
+ message="work", session_id="ses-local-error", agent_name="worker", agent_backend="codex",
+ )
+ assert requests.claim(run.id)
+ context = MessageContext(
+ user_id="U1", channel_id="C1", platform="avibe",
+ platform_specific={"turn_token": "turn-local-error"},
+ )
+ expected = "[Errno 28] No space left on device"
+ terminal = terminal_backend_failure_output(
+ context, output=MessageOutput(metadata={"local_error_detail": expected}),
+ )
+ store.record_turn_run_outputs(
+ [run.id], output_id="terminal", text="",
+ provenance=terminal.provenance(context), terminal_status="failed", error="engine down",
+ deferred_run_ids=[run.id] if deferred else [],
+ )
+ if deferred:
+ assert store.owed_failure_notice(run.id) is None
+ assert store.settle_deferred_run(run.id)
+ notice = store.owed_failure_notice(run.id)
+ assert notice["local_error_detail"] == expected
+ controller = SimpleNamespace(emit_agent_message=AsyncMock())
+ service = _drain_service(tmp_path, controller, store, requests)
+ service._failure_notice_targets = lambda _run: [
+ (parse_scope_id("avibe::project::local-error"), "ses-local-error"),
+ ]
+ service._build_context = AsyncMock(return_value=context)
+ await service._emit_failure_notice(store.get_run(run.id), notice, DeliveryEvidence())
+ output = controller.emit_agent_message.call_args.kwargs["output"]
+ assert output.metadata["local_error_detail"] == expected
+ assert output.metadata["replayed"] is True
+
+
[email protected]("role,visible", [("owner", True), ("member", True), ("editor", False), ("viewer", False)])
[email protected]("promoted", [False, True])
+def test_local_details_authorized_in_history_and_live_events(
+ isolated_state, tmp_path, monkeypatch, role, visible, promoted,
+):
+ # React gating is not authorization. The persisted transcript and the actual
+ # mirror publication must each be projected before reaching a chat-only reader.
+ from core import message_mirror
+ from storage import messages_service
+ from storage.db import create_sqlite_engine
+ from tests.test_ui_session_stream import _make_session
+ from vibe import ui_server
+ from vibe.authorization import AuthorizationContext
+
+ scope_id, session_id = _make_session(tmp_path)
+ context = AuthorizationContext(instance_role=role, is_remote=True)
+ metadata = {"event": "backend_failure", "local_error_detail": "[Errno 28] No space left on device"}
+ if promoted:
+ with create_sqlite_engine().begin() as conn:
+ messages_service.append(
+ conn, scope_id=scope_id, session_id=session_id, platform="avibe",
+ author="agent", message_type="notify", text="hidden failure",
+ native_message_id="local-failure", metadata={"delivery_suppressed": True},
+ )
+ published = []
+ monkeypatch.setattr(message_mirror, "_publish_session_message", published.append)
+ monkeypatch.setattr("core.web_push_notifications.maybe_notify_inbox_message", lambda *_args: None)
+ message_mirror.persist_agent_message(
+ MessageContext(
+ user_id="U1", channel_id="C1", platform="avibe",
+ platform_specific={"agent_session_id": session_id},
+ ),
+ "notify", "gateway unavailable", metadata=metadata, native_message_id="local-failure",
+ )
+ [row] = published
+ with create_sqlite_engine().connect() as conn:
+ for window in ({}, {"tail": True}, {"around_id": row["id"]}):
+ history = messages_service.list_session_messages(
+ conn, session_id=session_id, authorization_context=context, **window,
+ )
+ assert ("local_error_detail" in history["messages"][0]["metadata"]) is visible
+ public = messages_service.get_message(conn, row["id"])
+ assert "local_error_detail" not in public["metadata"]
+ for event in ("message.new", "message.updated"):
+ payload = ui_server._workbench_event_payload_for_context(
+ context, event, json.dumps({"type": event, "data": row}),
+ )
+ assert ("local_error_detail" in json.loads(payload)["data"]["metadata"]) is visible
+
+
[email protected]("role", ["owner", "member", "editor"])
+def test_local_details_redacted_in_every_harness_run_projection(isolated_state, monkeypatch, role):
+ from storage.background import SQLiteBackgroundTaskStore
+ from vibe import ui_server
+ from vibe.authorization import AuthorizationContext
+
+ metadata = {
+ "owed_failure_notice": {"local_error_detail": "[Errno 28] No space left on device"},
+ "turn_failure_notification": {"local_error_detail": "[Errno 28] No space left on device"},
+ "ordinary": "retained",
+ }
+ store = SQLiteBackgroundTaskStore()
+ try:
+ store.enqueue_run({
+ "id": "diagnostic-run", "run_type": "agent_run", "status": "failed",
+ "created_at": "2026-09-28T00:00:00+00:00", "updated_at": "2026-09-28T00:00:00+00:00",
+ "metadata": metadata,
+ })
+ finally:
+ store.close()
+ monkeypatch.setattr(
+ ui_server, "_request_authorization_context",
+ lambda: AuthorizationContext(instance_role=role, is_remote=True),
+ )
+ client = ui_server.app.test_client()
+ for route in (
+ "/api/harness/runs", "/api/harness/runs/diagnostic-run",
+ "/api/harness/bootstrap?tab=runs",
+ ):
+ response = client.get(route)
+ assert response.status_code == 200
+ body = response.get_json()
+ if route.startswith("/api/harness/bootstrap"):
+ body = body["page"]
+ run = body.get("run") or body["runs"][0]
+ # Harness has always requested public metadata, even for managers.
+ # The notification/provenance panel remains the authorized detail read.
+ assert "local_error_detail" not in json.dumps(run["metadata"])
+ assert run["metadata"]["ordinary"] == "retained"
+ store = SQLiteBackgroundTaskStore()
+ try:
+ assert store.get_run("diagnostic-run")["metadata"] == metadata
+ finally:
+ store.close()
+
+
[email protected]("stage", ["manifest_path", "manifest_cache", "manifest_package"])
[email protected]("code", [errno.EACCES, errno.EMFILE])
+def test_manifest_stat_errors_survive_boolean_probe_suppression(tmp_path, monkeypatch, stage, code):
+ from pathlib import Path
+ from core import managed_runtime
+ from tests.test_managed_runtime import _fixture_runtime_manager, _write_fixture_runtime_release
+
+ manifest = tmp_path / "unused.json"
+ _write_fixture_runtime_release(tmp_path, manifest, label="stat-errno", version="1.0.0")
+ manager = _fixture_runtime_manager(tmp_path / "runtime", manifest_path=manifest)
+ target = manifest
+ if stage == "manifest_cache":
+ manager.manifest_path = None
+ manager.manifest_url = manifest.as_uri()
+ manager.offline = True
+ target = manager._remote_manifest_cache_path()
+ elif stage == "manifest_package":
+ manager.manifest_path = None
+ monkeypatch.setattr(managed_runtime.package_resources, "files", lambda _package: tmp_path)
+ original_stat, original_is_file = Path.stat, Path.is_file
+
+ def stat(path, *args, **kwargs):
+ if path == target:
+ raise OSError(code, "private reason", "/private/凭证")
+ return original_stat(path, *args, **kwargs)
+
+ # Python 3.14's is_file returns False for every OSError. Emulate it on the
+ # CI interpreter so the required-input probe cannot silently lose errno.
+ def is_file(path):
+ return False if path == target else original_is_file(path)
+
+ monkeypatch.setattr(Path, "stat", stat)
+ monkeypatch.setattr(Path, "is_file", is_file)
+ result = manager.ensure()
+ assert not result["ok"]
+ assert result.get("os_errno") == code
+
+
[email protected]("code", [errno.EACCES, errno.EMFILE])
+def test_recorded_engine_recovery_preserves_errno_after_record_write(tmp_path, monkeypatch, code):
+ import psutil
+ from core.process_isolation import fingerprint_process_marker
+ from tests.test_model_hub_runtime import _fixture_supervisor
+
+ supervisor, state = _fixture_supervisor(tmp_path)
+ record = state.root / "engine-process.json"
+ record.parent.mkdir(parents=True, exist_ok=True)
+ record.write_text(json.dumps({
+ "engines": [{"worker_fingerprint": fingerprint_process_marker("recorded-engine")}],
+ }))
+
+ def fail(*_args, **_kwargs):
+ raise OSError(code, "private reason", "/private/凭证")
+
+ with monkeypatch.context() as patch:
+ patch.setattr(psutil, "process_iter", fail)
+ with pytest.raises(EngineUnavailableError) as raised:
+ supervisor.ensure_running()
+ assert raised.value.reason == "previous_engine_alive"
+ assert local_error_detail(raised.value) == f"[Errno {code}] {os.strerror(code)}"
+ assert json.loads(record.read_text())["engines"]
+ # A later conclusive pass retires the record and its previous diagnostic.
+ monkeypatch.setattr(psutil, "process_iter", lambda *_args: iter(()))
+ assert supervisor._reap_recorded_engines_locked()
+ assert supervisor._record_os_errno is None
+
+
[email protected]("stage", ["create", "rollover", "seek", "read", "rewrite", "close"])
[email protected]("code", [errno.ENOSPC, errno.EMFILE])
+async def test_gateway_owned_buffer_failure_is_diagnostic_and_still_metered(tmp_path, monkeypatch, stage, code):
+ import tempfile
+ from core.handlers.model_hub import turn_gateway
+ from core.handlers.model_hub.adapter import RawOutcomeKind
+ from tests.test_model_hub_l3 import (
+ LiveInvokeHandle, _canonicalize_fixed_test_routes, _outcome, _prepared_gateway_request, _usage_of,
+ )
+
+ def fail(*_args, **_kwargs):
+ raise OSError(code, "private reason", "/private/凭证")
+
+ original_spool = tempfile.SpooledTemporaryFile
+
+ class FailingSpool(original_spool):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ if stage == "create":
+ self.close()
+ fail()
+
+ def rollover(self):
+ if stage == "rollover":
+ fail()
+ return super().rollover()
+
+ def seek(self, *args, **kwargs):
+ if stage == "seek":
+ fail()
+ return super().seek(*args, **kwargs)
+
+ def read(self, *args, **kwargs):
+ if stage == "read":
+ fail()
+ return super().read(*args, **kwargs)
+
+ def __exit__(self, *args):
+ super().__exit__(*args)
+ if stage == "close":
+ fail()
+
+ source = _source("src_buffer01", "Buffered response")
+ body = b'{"output":"ok"}'
+ if stage == "rollover":
+ body = b"x" * (512 * 1024)
+ service = _service(tmp_path, sources=[source], live_handles=[
+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, status=200, source_id=source.id), (body,)),
+ ])
+ model = _canonicalize_fixed_test_routes(service)["codex"]
+ gateway = ModelHubTurnGateway(service, language_provider=lambda: "zh")
+ turn_id = "turn-local-buffer"
+ request = _prepared_gateway_request(
+ gateway, turn_id=turn_id, requested_model=model, source_id=source.id, stream=False,
+ )
+ monkeypatch.setattr(turn_gateway.tempfile, "SpooledTemporaryFile", FailingSpool)
+ if stage == "rewrite":
+ monkeypatch.setattr(turn_gateway, "rewrite_buffered_tool_names_file", fail)
+ try:
+ response = await gateway._handle_request(request)
+ assert response.status == 502
+ assert json.loads(response.body)["error"]["code"] == "engine_down"
+ assert _usage_of(service, source.id)["requests"] == 1
+ controller = SimpleNamespace(
+ config=SimpleNamespace(language="zh"), model_hub_turn_gateway=gateway,
+ emit_agent_message=AsyncMock(),
+ )
+ context = MessageContext(
+ user_id="U1", channel_id="C1", platform="avibe", platform_specific={"turn_token": turn_id},
+ )
+ await emit_backend_failure(controller, context, "codex", "API Error: 502 engine_down")
+ expected = f"[Errno {code}] {os.strerror(code)}"
+ notify = controller.emit_agent_message.call_args_list[0]
+ assert notify.kwargs["output"].metadata["local_error_detail"] == expected
+ gateway.correlation.settle(turn_id, settled_by=SETTLED_BY_TERMINAL_RESULT)
+ record = BoundedProvenanceStore(service.provenance.path).get(turn_id)
+ assert record["terminal_error"]["local_error_detail"] == expected
+ assert record["outcome"] == "failed_terminal"
+ assert record["served"] is None
+ finally:
+ await gateway.close()
+
+
+async def test_gateway_buffer_read_failure_after_headers_closes_truncated_response(tmp_path, monkeypatch):
+ import tempfile
+ from core.handlers.model_hub import turn_gateway
+ from core.handlers.model_hub.adapter import RawOutcomeKind
+ from tests.test_model_hub_l3 import LiveInvokeHandle, _outcome, _usage_of
+
+ original_spool = tempfile.SpooledTemporaryFile
+
+ class UnreadableSpool(original_spool):
+ def read(self, *_args, **_kwargs):
+ raise OSError(errno.EMFILE, "private reason", "/private/凭证")
+
+ source = _source("src_posthead1", "Large buffered response")
+ service = _service(tmp_path, sources=[source], live_handles=[
+ LiveInvokeHandle(
+ _outcome(RawOutcomeKind.SUCCESS, status=200, source_id=source.id),
+ (b"x" * (512 * 1024),),
+ ),
+ ])
+ gateway = ModelHubTurnGateway(service)
+ turn_id = "turn-buffer-after-headers"
+ base_url, token = await gateway.endpoint(
+ "codex", process_scope="/repo", turn_id=turn_id,
+ requested_model_id="shared-model", resolved_model_id="shared-model", source_id=source.id,
+ )
+ monkeypatch.setattr(turn_gateway.tempfile, "SpooledTemporaryFile", UnreadableSpool)
+ try:
+ async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=3), trust_env=False) as client:
+ response = await client.post(
+ f"{base_url}/v1/responses", json={"model": "shared-model", "input": "ping"},
+ headers={"Authorization": f"Bearer {token}"},
+ )
+ assert response.status == 200 # Already committed; it cannot be rewritten.
+ with pytest.raises(aiohttp.ClientPayloadError):
+ await response.read()
+ assert _usage_of(service, source.id)["requests"] == 1
+ gateway.correlation.settle(turn_id, settled_by=SETTLED_BY_TERMINAL_RESULT)
+ record = BoundedProvenanceStore(service.provenance.path).get(turn_id)
+ assert record["outcome"] == "failed_terminal"
+ assert record["terminal_error"]["local_error_detail"] == f"[Errno {errno.EMFILE}] {os.strerror(errno.EMFILE)}"
+ finally:
+ await gateway.close()
+
+
[email protected]("stage", ["manifest_path", "manifest_cache", "manifest_package", "manifest_download", "archive"])
[email protected]("code", [errno.ENOSPC, errno.EMFILE])
+def test_installer_helper_failures_keep_only_the_current_errno(tmp_path, monkeypatch, stage, code):
+ # Helpers return sentinels before ensure builds its failure result. Exercise
+ # actual dependency wrappers and reads, not a fixture failure dictionary.
+ import urllib.error
+ from core import managed_runtime
+ from pathlib import Path
+ from tests.test_managed_runtime import _fixture_runtime_manager, _write_fixture_runtime_release
+
+ manifest = tmp_path / "unused.json"
+ _write_fixture_runtime_release(tmp_path, manifest, label="helper-errno", version="1.0.0")
+ manager = _fixture_runtime_manager(tmp_path / "runtime", manifest_path=manifest)
+ failed_read = manifest
+ if stage in {"manifest_cache", "manifest_download"}:
+ manager.manifest_path = None
+ manager.manifest_url = manifest.as_uri()
+ if stage == "manifest_cache":
+ manager.offline = True
+ failed_read = manager._remote_manifest_cache_path()
+ failed_read.parent.mkdir(parents=True)
+ failed_read.write_bytes(manifest.read_bytes())
+ if stage == "manifest_package":
+ manager.manifest_path = None
+
+ read_bytes, open_path, urlopen = Path.read_bytes, Path.open, managed_runtime.urllib.request.urlopen
+
+ def fail():
+ raise OSError(code, "private reason", "/private/凭证")
+
+ def read(path):
+ if path == failed_read:
+ fail()
+ return read_bytes(path)
+
+ def open_file(path, *args, **kwargs):
+ if path.parent == manager.runtime_dir / "downloads" and path.suffix == ".tmp":
+ fail()
+ return open_path(path, *args, **kwargs)
+
+ def open_url(url, *args, **kwargs):
+ if url == manager.manifest_url:
+ raise urllib.error.URLError(OSError(code, "private reason", "/private/凭证"))
+ return urlopen(url, *args, **kwargs)
+
+ with monkeypatch.context() as patch:
+ if stage == "manifest_package":
+ patch.setattr(managed_runtime.package_resources, "files", lambda _package: tmp_path)
+ if stage in {"manifest_path", "manifest_cache", "manifest_package"}:
+ patch.setattr(Path, "read_bytes", read)
+ elif stage == "manifest_download":
+ patch.setattr(managed_runtime.urllib.request, "urlopen", open_url)
+ else:
+ patch.setattr(Path, "open", open_file)
+ failed = manager.ensure()
+ if stage in {"manifest_path", "manifest_cache", "manifest_package"}:
+ # Status reads the same failed manifest, then finds no installed
+ # pointer. That second fact must not erase this operation's cause.
+ assert manager.status()["os_errno"] == code
+ assert not failed["ok"]
+ assert failed["os_errno"] == code
+ manager.manifest_path, manager.manifest_url, manager.offline = manifest, None, False
+ succeeded = manager.ensure()
+ assert succeeded["ok"] and "os_errno" not in succeeded
+ manifest.write_text("{}")
+ invalid = manager.ensure()
+ assert not invalid["ok"] and "os_errno" not in invalid
diff --git a/tests/test_model_hub_provenance.py b/tests/test_model_hub_provenance.py
index 36918577e..7e6f1a153 100644
--- a/tests/test_model_hub_provenance.py
+++ b/tests/test_model_hub_provenance.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import asyncio
import json
+from dataclasses import replace
from datetime import timedelta
from pathlib import Path
from types import SimpleNamespace
@@ -38,7 +39,10 @@ def _live_registry(tmp_path, callback=None):
])
def test_live_terminal_projection_requires_exact_unfrozen_owner(tmp_path, guard):
registry = _live_registry(tmp_path)
- projection = produce_turn_outcome("turn.engine_down")
+ projection = replace(
+ produce_turn_outcome("turn.engine_down"),
+ local_error_detail="[Errno 28] No space left on device",
+ )
registry.record_turn_outcome("turn-live", projection)
if guard == "pending":
registry.begin_attempt(
diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.py
index d41c3d97a..7635a5275 100644
--- a/tests/test_model_hub_runtime.py
+++ b/tests/test_model_hub_runtime.py
@@ -2816,6 +2816,7 @@ class _FixtureInstaller:
"installed": True,
"version": "v7.2.95",
"install_dir": str(self.install_dir),
+ "path": str(self.binary),
}
def resolve_engine_path(self):
@@ -3329,7 +3330,7 @@ def test_supervisor_refuses_an_engine_whose_identity_was_not_captured(
) -> None:
from vibe.model_hub_runtime import supervisor as supervisor_module
- monkeypatch.setattr(supervisor_module, "capture_spawned_process_identity", lambda *_: None)
+ monkeypatch.setattr(supervisor_module, "capture_spawned_process_identity", lambda *_, **__: None)
supervisor, store = _fixture_supervisor(tmp_path)
with pytest.raises(EngineUnavailableError):
@@ -3667,7 +3668,7 @@ def test_supervisor_failed_tracking_reaps_a_descendant_that_ignores_sigterm(
time.sleep(0.5)
return process
- monkeypatch.setattr(supervisor_module, "capture_spawned_process_identity", lambda *_: None)
+ monkeypatch.setattr(supervisor_module, "capture_spawned_process_identity", lambda *_, **__: None)
supervisor, store = _fixture_supervisor(tmp_path, process_factory=spawn)
with pytest.raises(EngineUnavailableError) as raised:
@@ -4611,6 +4612,7 @@ def test_runtime_install_state_survives_adapter_reload_and_settles_once(
"installed": installed,
"version": "v7.2.95" if installed else None,
"install_dir": str(self.binary.parent),
+ "path": str(self.binary) if installed else None,
"platform": self.host_platform(),
"reason": None,
}
@@ -4710,6 +4712,7 @@ def test_cancelled_install_admission_keeps_owned_worker_and_shutdown_joins_it(
"installed": installed,
"version": "v7.2.95" if installed else None,
"install_dir": str(self.binary.parent),
+ "path": str(self.binary) if installed else None,
"platform": self.host_platform(),
"reason": None,
}
@@ -4788,6 +4791,7 @@ def test_install_finalization_never_projects_a_verified_installing_state(
"installed": installed,
"version": "v7.2.95" if installed else None,
"install_dir": str(self.binary.parent),
+ "path": str(self.binary) if installed else None,
"platform": self.host_platform(),
"reason": None,
}
@@ -4867,6 +4871,7 @@ def test_orphaned_install_state_is_reclaimed_before_runtime_status(
"installed": installed,
"version": "v7.2.95" if installed else None,
"install_dir": str(self.binary.parent),
+ "path": str(self.binary) if installed else None,
"platform": self.host_platform(),
"reason": None,
}
@@ -4956,6 +4961,7 @@ def test_recovery_retries_a_transient_shared_install_lock_collision(
"installed": installed,
"version": "v7.2.95" if installed else None,
"install_dir": str(self.binary.parent),
+ "path": str(self.binary) if installed else None,
"platform": self.host_platform(),
"reason": None,
}
@@ -5257,6 +5263,7 @@ def test_runtime_start_after_install_obeys_latest_explicit_lifecycle_action(
"installed": installed,
"version": "v7.2.95" if installed else None,
"install_dir": str(self.binary.parent),
+ "path": str(self.binary) if installed else None,
"platform": self.host_platform(),
"reason": None,
}
@@ -6758,8 +6765,10 @@ def test_closing_an_unstarted_stream_publishes_an_observed_terminal(
asyncio.run(run())
[email protected]("code", [28, 24, None])
def test_stream_replay_failure_preserves_observed_usage(
monkeypatch: pytest.MonkeyPatch,
+ code: int | None,
) -> None:
async def run() -> None:
class FailingPrelude(client_module._StreamPrelude):
@@ -6767,7 +6776,7 @@ def test_stream_replay_failure_preserves_observed_usage(
super().__init__(memory_limit=1)
def write(self, data: bytes) -> None:
- raise OSError("temporary storage unavailable")
+ raise OSError(code, "private temporary storage unavailable", "/private/凭证")
first = (
b'event: message_start\ndata: {"type":"message_start","message":'
@@ -6820,6 +6829,7 @@ def test_stream_replay_failure_preserves_observed_usage(
outcome = await handle.outcome()
assert outcome.kind is RawOutcomeKind.NETWORK_ERROR
assert outcome.error_code == "engine_down"
+ assert outcome.os_errno == code
assert outcome.usage == ProtocolUsageReport.of(
input_tokens=77,
cached_input_tokens=0,
diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.py
index 64ccfba3f..5e4ff94d5 100644
--- a/tests/test_session_delivery_fsm.py
+++ b/tests/test_session_delivery_fsm.py
@@ -1924,6 +1924,7 @@ def test_legacy_delivery_hydration_preserves_admitted_author(managers, user):
def test_public_metadata_recursively_redacts_legacy_identity_without_mutating_rows():
private = {"delegated_memory_owner": {"user_id": "private"}, "_memory_user_id": "private",
"_memory_arbitrary": True, "_web_push_user_key": "private",
+ "local_error_detail": "[Errno 28] No space left on device",
"resource_user_context": {"sub": "private"}, "visible": "keep"}
metadata = {**private, "scheduled_provenance": {"platform_specific": {
"message_metadata": private}}, "items": [{"nested": private}]}
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
index fb812c6d8..ef0dafd43 100644
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@ -624,6 +624,7 @@ export type TurnProvenance = {
stream_started: boolean;
http_status?: number | null;
upstream_error_code?: string | null;
+ local_error_detail?: string;
stripped_reasoning_efforts?: string[];
declared_reasoning_efforts?: string[];
} | null;
diff --git a/ui/src/components/workbench/FailureDetails.test.tsx b/ui/src/components/workbench/FailureDetails.test.tsx
index 9e3171d9b..8688551d7 100644
--- a/ui/src/components/workbench/FailureDetails.test.tsx
+++ b/ui/src/components/workbench/FailureDetails.test.tsx
@@ -8,6 +8,7 @@ import type { WorkbenchMessage } from '../../context/ApiContext';
import { InstanceAuthorizationContext } from '../../context/InstanceAuthorizationContext';
import { ToastProvider } from '../../context/ToastProvider';
import { DENIED_INSTANCE_CAPABILITIES } from '../../lib/sessionInfo';
+import { isRetryableFailureNotice } from '../../lib/chatMessageTypes';
import zh from '../../i18n/zh.json';
import { ApiCallError, modelsApi } from '../settings/models/modelsApi';
import type { TurnProvenance } from '../settings/models/types';
@@ -74,11 +75,62 @@ describe('failed-turn upstream details', () => {
it('does not read Model Hub provenance for a chat-only role', () => {
const read = vi.spyOn(modelsApi, 'getTurnProvenance');
- mount(notice, false);
+ mount({
+ ...notice, metadata: { ...notice.metadata, local_error_detail: '[Errno 28] No space left on device' },
+ } as WorkbenchMessage, false);
expect(screen.queryByRole('button', { name: '查看详情' })).toBeNull();
expect(read).not.toHaveBeenCalled();
});
+ it('shows a local diagnostic after a failed record read and after remounting', async () => {
+ vi.spyOn(modelsApi, 'getTurnProvenance')
+ .mockRejectedValue(new ApiCallError('provenance_unavailable', 'not found'));
+ const diagnostic = '[Errno 28] No space left on device';
+ const message = {
+ ...notice, metadata: { ...notice.metadata, local_error_detail: diagnostic },
+ } as WorkbenchMessage;
+ for (let mountCount = 0; mountCount < 2; mountCount += 1) {
+ mount(JSON.parse(JSON.stringify(message)));
+ await act(async () => { await Promise.resolve(); });
+ expect(screen.queryByText(diagnostic)).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: '查看详情' }));
+ expect(screen.getByText('本地错误')).toBeTruthy();
+ expect(screen.getByText(diagnostic)).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: '收起详情' }));
+ expect(screen.queryByText(diagnostic)).toBeNull();
+ cleanup();
+ resetFailureDetailsCache();
+ }
+ });
+
+ it('reads the local diagnostic from history when the notice has no snapshot', async () => {
+ const diagnostic = '[Errno 13] Permission denied';
+ vi.spyOn(modelsApi, 'getTurnProvenance').mockResolvedValue({
+ ...record,
+ terminal_error: { ...record.terminal_error, reason: 'engine_down', local_error_detail: diagnostic },
+ } as TurnProvenance);
+ mount();
+ fireEvent.click(await screen.findByRole('button', { name: '查看详情' }));
+ expect(screen.getByText(diagnostic)).toBeTruthy();
+ });
+
+ it.each([null, 'original-turn'])('shows detached replay details without provenance or Retry (%s)', (turnId) => {
+ const read = vi.spyOn(modelsApi, 'getTurnProvenance');
+ const diagnostic = '[Errno 28] No space left on device';
+ const message = {
+ ...notice,
+ metadata: {
+ ...notice.metadata, turn_id: turnId, detached: true, replayed: true,
+ local_error_detail: diagnostic,
+ },
+ } as WorkbenchMessage;
+ mount(message);
+ fireEvent.click(screen.getByRole('button', { name: '查看详情' }));
+ expect(screen.getByText(diagnostic)).toBeTruthy();
+ expect(read).not.toHaveBeenCalled();
+ expect(isRetryableFailureNotice(message)).toBe(false);
+ });
+
it('shares one Sources read across the notices of a transcript', async () => {
vi.spyOn(modelsApi, 'getTurnProvenance').mockResolvedValue(record);
const sources = vi.mocked(modelsApi.listSources);
diff --git a/ui/src/components/workbench/FailureDetails.tsx b/ui/src/components/workbench/FailureDetails.tsx
index 9df5486e2..fc3c6c91f 100644
--- a/ui/src/components/workbench/FailureDetails.tsx
+++ b/ui/src/components/workbench/FailureDetails.tsx
@@ -6,16 +6,15 @@
// HTTP status and machine error code, and why it moved on. That is what lets a
// user see the refusal came from the upstream API and not from the gateway.
//
-// Raw upstream response prose is never retained — the record keeps closed
-// machine codes and status only, so a credential echoed in an error body can
-// never reach the transcript. The details say so rather than implying more.
+// Raw upstream response prose is never retained. Local OS reasons are also
+// carried by the notice, so details survive an unavailable provenance read.
import * as React from 'react';
import { ChevronDown, ChevronRight } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import type { WorkbenchMessage } from '../../context/ApiContext';
import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
-import { isRetryableFailureNotice } from '../../lib/chatMessageTypes';
+import { isBackendFailureNotice, isRetryableFailureNotice } from '../../lib/chatMessageTypes';
import type { TurnProvenance } from '../settings/models/types';
import { ApiCallError } from '../settings/models/modelsApi';
import { CopyButton } from '../ui/copy-button';
@@ -36,9 +35,7 @@ const RECORD_RETRY_MS = 1_000;
type Detail = { record: TurnProvenance; names: Record<string, string> };
// Drawn as the notice bubble's second line. The record is read up front, and
-// a turn with no readable record (direct mode, no gateway record, an ambiguous
-// attribution, a failed read) offers no details at all rather than a toggle
-// that opens onto an apology.
+// a turn with neither a readable record nor a local diagnostic offers no toggle.
export function FailureDetails({ message }: { message: WorkbenchMessage }) {
const { t } = useTranslation();
const [open, setOpen] = React.useState(false);
@@ -46,8 +43,13 @@ export function FailureDetails({ message }: { message: WorkbenchMessage }) {
// The record names Sources and routes, so it is Model Hub management data:
// a chat-only role gets the notice and its retry, not a read bound to fail.
const { capabilities } = useInstanceAuthorization();
- const eligible = capabilities.can_manage_instance && isRetryableFailureNotice(message);
- const turnId = typeof message.metadata?.turn_id === 'string' ? message.metadata.turn_id : '';
+ const eligible = capabilities.can_manage_instance && isBackendFailureNotice(message);
+ // A cross-Session replay may display its snapshot but cannot read another
+ // Session's Turn record or acquire Retry eligibility.
+ const turnId = isRetryableFailureNotice(message) ? message.metadata!.turn_id as string : '';
+ const localErrorDetail = (
+ typeof message.metadata?.local_error_detail === 'string' ? message.metadata.local_error_detail : ''
+ ).trim() || detail?.record.terminal_error?.local_error_detail;
React.useEffect(() => {
if (!eligible || !turnId) return;
@@ -76,7 +78,7 @@ export function FailureDetails({ message }: { message: WorkbenchMessage }) {
};
}, [eligible, turnId]);
- if (!eligible || !turnId || !detail) return null;
+ if (!eligible || (!detail && !localErrorDetail)) return null;
// Blockers carry the event-reason vocabulary (`cooldown`, `credential_expired`,
// …); only a source detail arrives as a full i18n key.
@@ -111,6 +113,7 @@ export function FailureDetails({ message }: { message: WorkbenchMessage }) {
};
const body = (() => {
+ if (!detail) return null;
const { record, names } = detail;
const attempts = rows(record, names);
// A terminal failure is an upstream refusal only when the upstream refused
@@ -171,7 +174,17 @@ export function FailureDetails({ message }: { message: WorkbenchMessage }) {
{open ? <ChevronDown className="size-3" aria-hidden /> : <ChevronRight className="size-3" aria-hidden />}
{t(open ? 'chat.failureDetails.hide' : 'chat.failureDetails.show')}
</button>
- {open && <div className="mt-1.5 text-[12px] leading-relaxed">{body}</div>}
+ {open && (
+ <div className="mt-1.5 flex min-w-0 flex-col gap-2 text-[12px] leading-relaxed">
+ {localErrorDetail && (
+ <div className="flex min-w-0 flex-col gap-1">
+ <span className="text-gold-ink/70">{t('chat.failureDetails.localError')}</span>
+ <pre className="whitespace-pre-wrap break-words font-mono text-gold-ink">{localErrorDetail}</pre>
+ </div>
+ )}
+ {body}
+ </div>
+ )}
</>
);
}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index c69e60140..cb8a519f7 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -4699,6 +4699,7 @@
}
},
"failureDetails": {
+ "localError": "Local error",
"show": "Show details",
"hide": "Hide details",
"outcome": {
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 17941140e..ad4a7901c 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -4699,6 +4699,7 @@
}
},
"failureDetails": {
+ "localError": "本地错误",
"show": "查看详情",
"hide": "收起详情",
"outcome": {
diff --git a/ui/src/lib/chatMessageTypes.ts b/ui/src/lib/chatMessageTypes.ts
index 2f9a55735..f0cbc9247 100644
--- a/ui/src/lib/chatMessageTypes.ts
+++ b/ui/src/lib/chatMessageTypes.ts
@@ -59,9 +59,7 @@ export const isBoundaryMessage = (message: TerminalMessageCandidate): boolean =>
type TerminalAgentMessageCandidate = TerminalMessageCandidate & { author: string };
-// This is action eligibility, not transcript visibility. The server additionally
-// rechecks the durable failed-Turn boundary and current Session authority.
-export function isRetryableFailureNotice(
+export function isBackendFailureNotice(
message: TerminalAgentMessageCandidate & { source?: string | null },
): boolean {
const metadata = message.metadata;
@@ -70,8 +68,17 @@ export function isRetryableFailureNotice(
&& message.source === 'agent'
&& metadata?.event === 'backend_failure'
&& typeof metadata.failure_id === 'string'
- && !!metadata.failure_id
- && typeof metadata.turn_id === 'string'
+ && !!metadata.failure_id;
+}
+
+// This is action eligibility, not transcript visibility. The server additionally
+// rechecks the durable failed-Turn boundary and current Session authority.
+export function isRetryableFailureNotice(
+ message: TerminalAgentMessageCandidate & { source?: string | null },
+): boolean {
+ const metadata = message.metadata;
+ return isBackendFailureNotice(message)
+ && typeof metadata?.turn_id === 'string'
&& !!metadata.turn_id
&& !metadata.detached;
}
diff --git a/vibe/cli.py b/vibe/cli.py
index 73481c8a8..42538381a 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -240,6 +240,7 @@ DOCTOR_DISPLAY_PROJECTIONS = {
"candidate_validation_failed": "doctor.repair.dependencyCandidateValidationFailed",
"install_missing_binary": "doctor.repair.dependencyInstallMissingBinary",
"install_failed": "doctor.repair.installError",
+ "install_inspection_failed": "doctor.repair.dependencyInstallInspectionFailed",
"install_lock_failed": "doctor.repair.dependencyInstallLockFailed",
"install_claim_failed": "doctor.repair.dependencyInstallClaimFailed",
"install_target_changed": "doctor.repair.dependencyInstallTargetChanged",
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 0194ed62f..792efce1c 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -1410,6 +1410,7 @@
"dependencyBinaryNotRunnable": "The {target} binary is not runnable.",
"dependencyBinaryPrepareFailed": "The {target} binary could not be prepared.",
"dependencyCandidateValidationFailed": "The {target} installation candidate could not be validated.",
+ "dependencyInstallInspectionFailed": "The installed {target} runtime could not be inspected.",
"dependencyInstallMissingBinary": "The {target} archive did not contain its binary.",
"dependencyInstallLockFailed": "The {target} installation lock could not be acquired: {error}.",
"dependencyInstallClaimFailed": "The {target} installation claim could not be recorded: {error}.",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 21d1b9c0c..b75ce6648 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -1410,6 +1410,7 @@
"dependencyBinaryNotRunnable": "{target} 二进制无法运行。",
"dependencyBinaryPrepareFailed": "无法准备 {target} 二进制。",
"dependencyCandidateValidationFailed": "无法验证 {target} 安装候选项。",
+ "dependencyInstallInspectionFailed": "无法检查已安装的 {target} 运行时。",
"dependencyInstallMissingBinary": "{target} 归档不包含其二进制文件。",
"dependencyInstallLockFailed": "无法获取 {target} 安装锁:{error}。",
"dependencyInstallClaimFailed": "无法记录 {target} 安装声明:{error}。",
diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.py
index c83d69f61..78ebd3c8b 100644
--- a/vibe/model_hub_runtime/adapter.py
+++ b/vibe/model_hub_runtime/adapter.py
@@ -47,6 +47,7 @@ from core.handlers.model_hub.quota import (
parse_subscription_quota,
)
from core.handlers.model_hub.async_owner import run_owned_in_thread
+from core.os_errors import local_os_errno
from vibe.model_hub_runtime.client import (
_OFFICIAL_BASE_URLS,
EngineClient,
@@ -1656,10 +1657,10 @@ class CLIProxyEngineAdapter:
return "model_hub_engine_install_failed"
@staticmethod
- def _install_failure(reason: str) -> Exception:
+ def _install_failure(reason: str, *, os_errno: int | None = None) -> Exception:
if reason == INSTALL_PLATFORM_UNSUPPORTED_REASON:
return RuntimePlatformUnsupportedError()
- return EngineUnavailableError("models.engine.install_failed", reason=reason)
+ return EngineUnavailableError("models.engine.install_failed", reason=reason, os_errno=os_errno)
async def ensure_installed(
self,
@@ -1692,7 +1693,7 @@ class CLIProxyEngineAdapter:
)
if not install.get("ok"):
reason = str(install.get("reason") or "engine_install_failed")
- raise self._install_failure(reason)
+ raise self._install_failure(reason, os_errno=install.get("os_errno"))
if install.get("changed"):
await self._transports_idle.wait()
await run_owned_in_thread(self.supervisor.restart_if_running)
@@ -2793,7 +2794,7 @@ class CLIProxyEngineAdapter:
raise OriginNotAllowedError(f"origin {origin!r} is not allowed to use source {source_id!r}")
try:
client = await asyncio.to_thread(self.supervisor.client)
- except EngineUnavailableError:
+ except EngineUnavailableError as exc:
return completed_handle(
RawCallOutcome(
kind=RawOutcomeKind.NETWORK_ERROR,
@@ -2803,6 +2804,7 @@ class CLIProxyEngineAdapter:
stream_started=False,
model_id=model_id,
source_id=source_id,
+ os_errno=local_os_errno(exc),
)
)
release = self._acquire_transport()
diff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.py
index 1e33106ed..8c6fd9699 100644
--- a/vibe/model_hub_runtime/client.py
+++ b/vibe/model_hub_runtime/client.py
@@ -38,6 +38,7 @@ from core.handlers.model_hub.json_wire import (
)
from core.handlers.model_hub.request import FORWARDED_CALLER_HEADERS
from core.message_output import plain_untrusted_text
+from core.os_errors import local_os_errno
from core.handlers.model_hub.stream_wire import (
ErrorEnvelopePath,
ProtocolObservation,
@@ -85,12 +86,14 @@ class EngineClientError(RuntimeError):
error_type: str | None = None,
error_code: str | None = None,
error_candidates: tuple[str, ...] = (),
+ os_errno: int | None = None,
) -> None:
super().__init__(message)
self.status_code = status_code
self.error_type = error_type
self.error_code = error_code
self.error_candidates = error_candidates
+ self.os_errno = os_errno
class _StreamPrelude:
@@ -244,6 +247,7 @@ class EngineHealthFailure:
reason: Literal["timeout", "http_error", "invalid_response", "unavailable"]
elapsed_seconds: float
http_status: int | None = None
+ os_errno: int | None = None
class EngineInvokeHandle:
@@ -329,6 +333,7 @@ class EngineClient:
)
self.health_failure = EngineHealthFailure(
path, reason, time.monotonic() - started_at, exc.status_code,
+ os_errno=local_os_errno(exc),
)
return False
if not valid:
@@ -700,6 +705,7 @@ class EngineClient:
source=source,
model_id=model_id,
error_code="engine_down",
+ os_errno=local_os_errno(exc),
http_status=response.status if response is not None and first_received else None,
message=(
"local response replay failed"
@@ -801,6 +807,7 @@ class EngineClient:
raise EngineClientError(
"engine API is unavailable",
error_type=type(read_error).__name__,
+ os_errno=local_os_errno(read_error),
) from None
raise EngineClientError(
f"engine API returned HTTP {exc.code}",
@@ -816,7 +823,10 @@ class EngineClient:
socket.timeout,
OSError,
) as exc:
- raise EngineClientError("engine API is unavailable", error_type=type(exc).__name__) from None
+ raise EngineClientError(
+ "engine API is unavailable", error_type=type(exc).__name__,
+ os_errno=local_os_errno(exc),
+ ) from None
def _url(self, path: str, *, query: Mapping[str, str] | None = None) -> str:
url = f"{self.connection.base_url.rstrip('/')}{path}"
@@ -1465,7 +1475,7 @@ async def _response_stream(
message="upstream response timed out after streaming started",
stream_started=wire_state.model_output_started,
)
- except aiohttp.ClientError:
+ except (aiohttp.ClientError, OSError) as exc:
outcome = _observed_stream_terminal_outcome(
wire_state,
source,
@@ -1481,6 +1491,7 @@ async def _response_stream(
model_id=model_id,
http_status=response.status,
error_code="engine_down",
+ os_errno=local_os_errno(exc),
message="upstream response failed after streaming started",
stream_started=wire_state.model_output_started,
)
@@ -1665,6 +1676,7 @@ def _outcome(
usage: ProtocolUsageReport | None = None,
recovery_verified: bool = False,
upstream_detail: str | None = None,
+ os_errno: int | None = None,
) -> RawCallOutcome:
return RawCallOutcome(
kind=kind,
@@ -1679,6 +1691,7 @@ def _outcome(
usage=usage,
recovery_verified=recovery_verified,
upstream_detail=upstream_detail,
+ os_errno=os_errno,
)
diff --git a/vibe/model_hub_runtime/installer.py b/vibe/model_hub_runtime/installer.py
index 568f3cd09..c9de249a4 100644
--- a/vibe/model_hub_runtime/installer.py
+++ b/vibe/model_hub_runtime/installer.py
@@ -208,7 +208,7 @@ class EngineRuntimeManager(ManagedRuntimeManager):
install_state = self.install_state()
if install_state and install_state.get("state") == "not_installed":
reason = install_state.get("reason")
- if isinstance(reason, str) and reason:
+ if isinstance(reason, str) and reason and not managed.get("reason"):
managed["status"] = "error"
managed["reason"] = reason
return managed
@@ -620,7 +620,8 @@ class EngineRuntimeManager(ManagedRuntimeManager):
env=engine_subprocess_environment(),
**isolated_subprocess_kwargs(),
)
- except Exception: # noqa: BLE001
+ except Exception as exc: # noqa: BLE001
+ self._set_install_failure(self._reason("binary_not_runnable"), exc)
return None
match = _ENGINE_VERSION_RE.search(f"{result.stdout}\n{result.stderr}")
if match is None:
diff --git a/vibe/model_hub_runtime/supervisor.py b/vibe/model_hub_runtime/supervisor.py
index 54b456d89..462296c3c 100644
--- a/vibe/model_hub_runtime/supervisor.py
+++ b/vibe/model_hub_runtime/supervisor.py
@@ -15,6 +15,7 @@ from typing import Any, Callable, TypeVar
from config import paths
from config.atomic_io import write_atomic
+from core.os_errors import local_os_errno
from core.process_isolation import (
KILL_SIGNAL,
PROCESS_IDENTITY_ENV,
@@ -60,10 +61,13 @@ class _EngineRecord:
class EngineUnavailableError(RuntimeError):
"""The Hub path is unavailable; callers may use explicitly configured Direct mode."""
- def __init__(self, error_key: str, *, reason: str | None = None) -> None:
+ def __init__(
+ self, error_key: str, *, reason: str | None = None, os_errno: int | None = None,
+ ) -> None:
super().__init__(error_key)
self.error_key = error_key
self.reason = reason
+ self.os_errno = os_errno
self.direct_mode_available = True
@@ -90,6 +94,8 @@ class EngineSupervisor:
self._last_check: str | None = None
self._start_attempted = False
self._health_failure_signature: tuple[str, str, int | None] | None = None
+ self._health_os_errno: int | None = None
+ self._record_os_errno: int | None = None
self._config_generation = 0
def ensure_running(self) -> EngineConnection:
@@ -139,7 +145,10 @@ class EngineSupervisor:
def _require_no_untracked_engine_locked(self) -> None:
if not self._reap_recorded_engines_locked():
- raise EngineUnavailableError("models.engine.stop_unconfirmed", reason="previous_engine_alive")
+ raise EngineUnavailableError(
+ "models.engine.stop_unconfirmed", reason="previous_engine_alive",
+ os_errno=self._record_os_errno,
+ )
def reload_config_if_running(self, previous_sources: list[SourceRecord] | None = None) -> None:
"""Hot-apply the current source projection to a live engine.
@@ -199,10 +208,12 @@ class EngineSupervisor:
# PUT, and its watcher reloads the same file.
deadline = time.monotonic() + MODEL_HUB_CONFIG_RELOAD_TIMEOUT_SECONDS
while True:
+ os_errno = None
try:
listed = client.list_model_names(timeout=1.0)
- except EngineClientError:
+ except EngineClientError as exc:
listed = None
+ os_errno = local_os_errno(exc)
if (
listed is not None
and all(listed.get(model) == name for model, name in expected.items())
@@ -210,7 +221,7 @@ class EngineSupervisor:
):
return
if time.monotonic() >= deadline:
- raise EngineUnavailableError("models.engine.health_failed")
+ raise EngineUnavailableError("models.engine.health_failed", os_errno=os_errno)
time.sleep(_STARTUP_POLL_INTERVAL_SECONDS)
def _next_generation_locked(self) -> str:
@@ -232,10 +243,14 @@ class EngineSupervisor:
def _prepare_instance_locked(self):
managed = self.installer.status()
- binary = self.installer.resolve_engine_path()
+ # Status owns one coherent inspection snapshot, including its failure.
+ # A second resolve could fail for a different reason or replace errno.
+ binary = Path(managed["path"]) if managed.get("path") else None
if binary is None:
reason = str(managed.get("reason") or "engine_not_installed")
- raise EngineUnavailableError("models.engine.install_failed", reason=reason)
+ raise EngineUnavailableError(
+ "models.engine.install_failed", reason=reason, os_errno=managed.get("os_errno"),
+ )
install_id = Path(str(managed.get("install_dir") or binary.parent)).name
instance_dir, runtime_secrets = self.state_store.prepare_instance(install_id, rotate=False)
return managed, binary, instance_dir, runtime_secrets
@@ -335,7 +350,10 @@ class EngineSupervisor:
# rotates in place; a second engine beside it is never safe. Each later
# start retries the reap, so this clears once the survivor is confirmed gone.
if not self._reap_recorded_engines_locked():
- raise EngineUnavailableError("models.engine.start_failed", reason="previous_engine_alive")
+ raise EngineUnavailableError(
+ "models.engine.start_failed", reason="previous_engine_alive",
+ os_errno=self._record_os_errno,
+ )
managed, binary, instance_dir, runtime_secrets = self._prepare_instance_locked()
port = self._port_allocator()
config_path = instance_dir / "config.yaml"
@@ -361,7 +379,10 @@ class EngineSupervisor:
if not self._store_engine_records_locked([launch]):
# A launch no record names would become a permanent orphan if this
# service died, so it never runs untracked.
- raise EngineUnavailableError("models.engine.start_failed", reason="engine_untracked")
+ raise EngineUnavailableError(
+ "models.engine.start_failed", reason="engine_untracked",
+ os_errno=self._record_os_errno,
+ )
try:
process = self._process_factory(
[str(binary), "-config", str(config_path)],
@@ -377,15 +398,21 @@ class EngineSupervisor:
# No process was created, so nothing can carry this marker: retire the
# launch record directly instead of scanning for a tree that never was.
if not self._store_engine_records_locked([]):
- raise EngineUnavailableError("models.engine.start_failed", reason="engine_untracked") from exc
+ raise EngineUnavailableError(
+ "models.engine.start_failed", reason="engine_untracked",
+ os_errno=self._record_os_errno,
+ ) from exc
raise EngineUnavailableError("models.engine.start_failed") from exc
self._process = process
self._connection = connection
if not self._record_engine_locked(process, marker):
# The marker-only launch record still names the tree, so the stop below
# confirms every process it forked is gone before the record retires.
+ os_errno = self._record_os_errno
self._stop_locked()
- raise EngineUnavailableError("models.engine.start_failed", reason="engine_untracked")
+ raise EngineUnavailableError(
+ "models.engine.start_failed", reason="engine_untracked", os_errno=os_errno,
+ )
started_at = time.monotonic()
deadline = started_at + self.startup_timeout
exit_code: int | None = None
@@ -412,6 +439,7 @@ class EngineSupervisor:
)
return connection
time.sleep(min(_STARTUP_POLL_INTERVAL_SECONDS, max(0.0, deadline - time.monotonic())))
+ os_errno = self._health_os_errno if exit_code is None else None
self._stop_locked()
logger.warning(
"Model Hub engine startup outcome=%s managed_version=%s exit_code=%s "
@@ -423,7 +451,7 @@ class EngineSupervisor:
time.monotonic() - started_at,
self.startup_timeout,
)
- raise EngineUnavailableError("models.engine.health_failed")
+ raise EngineUnavailableError("models.engine.health_failed", os_errno=os_errno)
def _healthy_locked(self) -> bool:
if not self._is_running_locked() or self._connection is None:
@@ -434,6 +462,7 @@ class EngineSupervisor:
healthy = client.health()
self._last_check = _utc_now()
failure = client.health_failure
+ self._health_os_errno = failure.os_errno if failure is not None else None
if failure is not None:
signature = (failure.path, failure.reason, failure.http_status)
if signature != self._health_failure_signature:
@@ -454,7 +483,10 @@ class EngineSupervisor:
def _require_stopped_locked(self) -> None:
if not self._stop_locked():
- raise EngineUnavailableError("models.engine.stop_unconfirmed", reason="previous_engine_alive")
+ raise EngineUnavailableError(
+ "models.engine.stop_unconfirmed", reason="previous_engine_alive",
+ os_errno=self._record_os_errno,
+ )
def _stop_locked(self) -> bool:
"""Stop the engine; return whether no engine it may have started remains."""
@@ -463,6 +495,7 @@ class EngineSupervisor:
self._process = None
self._connection = None
self._health_failure_signature = None
+ self._health_os_errno = None
if process is not None and process.poll() is None:
signal_process_tree(process, signal.SIGTERM, logger, "Model Hub engine")
try:
@@ -481,6 +514,7 @@ class EngineSupervisor:
def _load_engine_records_locked(self) -> list[_EngineRecord] | None:
"""Return the recorded engines, or ``None`` if the record is unreadable."""
+ self._record_os_errno = None
try:
text: str | None = self._engine_record_path.read_text(encoding="utf-8")
except FileNotFoundError:
@@ -488,7 +522,8 @@ class EngineSupervisor:
except UnicodeDecodeError:
# Corrupt contents, like malformed JSON: nothing in it can be trusted.
text = None
- except OSError:
+ except OSError as exc:
+ self._record_os_errno = local_os_errno(exc)
logger.warning("Model Hub engine process record could not be read", exc_info=True)
return None
try:
@@ -508,6 +543,7 @@ class EngineSupervisor:
def _store_engine_records_locked(self, records: list[_EngineRecord]) -> bool:
path = self._engine_record_path
+ self._record_os_errno = None
try:
if not records:
path.unlink(missing_ok=True)
@@ -523,7 +559,8 @@ class EngineSupervisor:
)
+ "\n",
)
- except OSError:
+ except OSError as exc:
+ self._record_os_errno = local_os_errno(exc)
logger.warning("Model Hub engine process record could not be written", exc_info=True)
return False
return True
@@ -531,8 +568,16 @@ class EngineSupervisor:
def _record_engine_locked(self, process: Any, marker: str) -> bool:
"""Complete the launch record with the engine's pid; return whether it is tracked."""
+ self._record_os_errno = None
pid = getattr(process, "pid", None)
- identity = capture_spawned_process_identity(pid, marker) if isinstance(pid, int) else None
+
+ def capture_error(error: BaseException) -> None:
+ self._record_os_errno = local_os_errno(error)
+
+ identity = (
+ capture_spawned_process_identity(pid, marker, on_error=capture_error)
+ if isinstance(pid, int) else None
+ )
if identity is None:
return False
return self._store_engine_records_locked([_EngineRecord(identity.worker_fingerprint, identity)])
@@ -551,8 +596,15 @@ class EngineSupervisor:
if records is None:
return False
survivors: list[_EngineRecord] = []
+ survivor_os_errno = None
for record in records:
outcomes = []
+ reap_os_errno = None
+
+ def capture_reap_error(error: BaseException) -> None:
+ nonlocal reap_os_errno
+ reap_os_errno = local_os_errno(error)
+
if record.identity is not None:
outcomes.append(
reap_orphaned_process_tree(logger, "Model Hub engine", expected_identity=record.identity)
@@ -562,6 +614,7 @@ class EngineSupervisor:
logger,
"Model Hub engine",
worker_fingerprint=record.worker_fingerprint,
+ on_error=capture_reap_error,
)
)
# The marker sweep is the authority: it sees every process of the tree,
@@ -569,6 +622,7 @@ class EngineSupervisor:
# retires the record even when the narrower pid/group path could not.
if outcomes[-1] == "unconfirmed":
survivors.append(record)
+ survivor_os_errno = survivor_os_errno or reap_os_errno
elif "reaped" in outcomes:
logger.warning("Reaped a Model Hub engine left running by an earlier service")
if survivors:
@@ -576,7 +630,13 @@ class EngineSupervisor:
"Could not confirm %d earlier Model Hub engine(s) exited; keeping them tracked",
len(survivors),
)
- return self._store_engine_records_locked(survivors) and not survivors
+ stored = self._store_engine_records_locked(survivors)
+ # A successful record rewrite must not erase why a tree remains
+ # unconfirmed. The authoritative marker sweep, not a recovered failure
+ # in the narrower pid/group probe, owns that diagnostic.
+ if survivors and self._record_os_errno is None:
+ self._record_os_errno = survivor_os_errno
+ return stored and not survivors
def _serialize_engine_record(record: _EngineRecord) -> dict[str, Any]:
if record.identity is not None:
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index f799a5d47..e57b25fca 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -11688,7 +11688,9 @@ async def sessions_messages_create(session_id: str):
with engine.connect() as conn:
current = message_deliveries.get_delivery(conn, str(message["id"]))
retry_notice = (
- messages_service.get_message(conn, retry_for, session_id=session_id)
+ messages_service.get_message(
+ conn, retry_for, session_id=session_id, include_local_error_detail=True,
+ )
if retry_for else None
)
if current is None:
@@ -11699,7 +11701,15 @@ async def sessions_messages_create(session_id: str):
if retry_notice is not None:
from vibe.sse_broker import broker
- payload["retry_notice"] = retry_notice
+ payload["retry_notice"] = {
+ **retry_notice,
+ "metadata": message_deliveries.public_message_metadata(
+ retry_notice.get("metadata"),
+ include_local_error_detail=_has_runtime_management_access(
+ getattr(g, "authorization_context", None),
+ ),
+ ),
+ }
# An upsert of an existing notice is not new user communication.
broker.publish("message.updated", retry_notice)
if current["state"] == "queued":
@@ -12160,6 +12170,32 @@ def _workbench_event_payload_for_context(context, event_type: str, payload: str)
"""
from vibe.authorization import INSTANCE_SCOPED_REFETCH_EVENTS
+ if event_type in {"message.new", "message.updated"}:
+ from storage.message_deliveries import public_message_metadata
+
+ try:
+ envelope = json.loads(payload)
+ except (TypeError, json.JSONDecodeError):
+ return None
+ if not isinstance(envelope, dict) or not isinstance(envelope.get("data"), dict):
+ return None
+ data = envelope["data"]
+ if "metadata" not in data:
+ return payload
+ return json.dumps(
+ {
+ **envelope,
+ "data": {
+ **data,
+ "metadata": public_message_metadata(
+ data.get("metadata"),
+ include_local_error_detail=_has_runtime_management_access(context),
+ ),
+ },
+ },
+ ensure_ascii=False,
+ separators=(",", ":"),
+ )
if event_type in INSTANCE_SCOPED_REFETCH_EVENTS and not _has_runtime_management_access(context):
# Below runtime management the frame is a bare signal: consumers refetch
# and ignore the body, while publishers attach identifiers (session ids,