fix(模型): 显示加载失败阶段和依赖诊断
模型子进程返回固定的加载阶段、异常类型和已知依赖名称,主进程在启动日志及异常中展示诊断信息,不输出原始异常文本。保留加载失败时阻止就绪与子进程清理行为。 新增六个加载阶段、异常信息过滤与进程清理测试;相关测试共 28 项通过,Ruff 检查通过。
This commit is contained in:
1 parent
5d71803b02
commit
eab1af6c5f
4 files changed
+150
-5
No files matched your search
@@ -127,3 +127,5 @@ local result = host.llm("Qwen3Guard-Gen-0.6B", {
|
|||||||
```
|
```
|
||||||
|
|
||||||
`host.llm.call(id, request)` is equivalent to the callable form. Calls are synchronous from Lua, serialized per model, and executed in a separate Python process. The worker is started before `/readyz` becomes ready. Model failures are returned as capability failures; plugins should fail closed (the example `response_guard.lua` blocks on a failed moderation call). The model worker is local-only and does not download weights at request time.
|
`host.llm.call(id, request)` is equivalent to the callable form. Calls are synchronous from Lua, serialized per model, and executed in a separate Python process. The worker is started before `/readyz` becomes ready. Model failures are returned as capability failures; plugins should fail closed (the example `response_guard.lua` blocks on a failed moderation call). The model worker is local-only and does not download weights at request time.
|
||||||
|
|
||||||
|
模型启动失败时,服务日志输出 `model_load_failed model=... stage=... exception=... dependency=...`。`stage` 区分 `import_torch`、`import_transformers`、`load_tokenizer`、`load_model`、`move_to_device` 和 `eval_model`;`exception` 是允许记录的异常类型,`dependency` 标记已知的缺失依赖,其余值为 `unknown`。诊断不输出原始异常文本或模型文件内容,模型加载失败仍会阻止服务就绪。例如 `stage=import_torch exception=ModuleNotFoundError dependency=torch` 表示缺少 PyTorch,需要在构建实际运行的镜像时安装 `.[guard]`。
|
||||||
+28
-2
@@ -14,6 +14,30 @@ from .config import LLMConfig, Settings
|
|||||||
|
|
||||||
logger = logging.getLogger("middleware.audit")
|
logger = logging.getLogger("middleware.audit")
|
||||||
|
|
||||||
|
# Only fixed diagnostic labels may cross the startup IPC boundary or enter logs.
|
||||||
|
MODEL_LOAD_STAGES = {
|
||||||
|
"import_torch", "import_transformers", "load_tokenizer", "load_model",
|
||||||
|
"move_to_device", "eval_model",
|
||||||
|
}
|
||||||
|
MODEL_LOAD_ERRORS = {
|
||||||
|
"ModuleNotFoundError", "ImportError", "FileNotFoundError", "PermissionError",
|
||||||
|
"OSError", "ValueError", "TypeError", "RuntimeError", "MemoryError",
|
||||||
|
"SafetensorError", "OutOfMemoryError",
|
||||||
|
}
|
||||||
|
MODEL_DEPENDENCIES = {"torch", "transformers", "tokenizers", "safetensors", "numpy", "accelerate"}
|
||||||
|
|
||||||
|
|
||||||
|
def model_load_diagnostic(result: dict[str, Any]) -> str:
|
||||||
|
labels = []
|
||||||
|
for key, allowed in (
|
||||||
|
("stage", MODEL_LOAD_STAGES),
|
||||||
|
("exception", MODEL_LOAD_ERRORS),
|
||||||
|
("dependency", MODEL_DEPENDENCIES),
|
||||||
|
):
|
||||||
|
value = result.get(key)
|
||||||
|
labels.append(f"{key}={value if isinstance(value, str) and value in allowed else 'unknown'}")
|
||||||
|
return " ".join(labels)
|
||||||
|
|
||||||
|
|
||||||
class LLMFailure(Exception):
|
class LLMFailure(Exception):
|
||||||
"""A deliberately non-sensitive LLM capability failure."""
|
"""A deliberately non-sensitive LLM capability failure."""
|
||||||
@@ -149,7 +173,7 @@ class GuardAdapter:
|
|||||||
from .llm_worker import guard_worker_main
|
from .llm_worker import guard_worker_main
|
||||||
|
|
||||||
if not self.spec.file.is_dir():
|
if not self.spec.file.is_dir():
|
||||||
raise LLMUnavailable()
|
raise LLMUnavailable("ModelDirectoryMissing")
|
||||||
parent, child = self.context.Pipe(duplex=True)
|
parent, child = self.context.Pipe(duplex=True)
|
||||||
process = self.context.Process(
|
process = self.context.Process(
|
||||||
target=guard_worker_main,
|
target=guard_worker_main,
|
||||||
@@ -177,7 +201,9 @@ class GuardAdapter:
|
|||||||
)
|
)
|
||||||
result = json.loads(response)
|
result = json.loads(response)
|
||||||
if not result.get("ok"):
|
if not result.get("ok"):
|
||||||
raise LLMUnavailable()
|
diagnostic = model_load_diagnostic(result)
|
||||||
|
logger.error("model_load_failed model=%s %s", self.spec.id, diagnostic)
|
||||||
|
raise LLMUnavailable(f"ModelLoadFailed {diagnostic}")
|
||||||
except BaseException as exc:
|
except BaseException as exc:
|
||||||
await self.stop()
|
await self.stop()
|
||||||
if isinstance(exc, (LLMFailure, asyncio.CancelledError)):
|
if isinstance(exc, (LLMFailure, asyncio.CancelledError)):
|
||||||
|
|||||||
@@ -3,24 +3,29 @@
|
|||||||
import json
|
import json
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from .llm import _send, guard_messages, parse_guard_output
|
from .llm import MODEL_DEPENDENCIES, MODEL_LOAD_ERRORS, _send, guard_messages, parse_guard_output
|
||||||
|
|
||||||
|
|
||||||
def guard_worker_main(
|
def guard_worker_main(
|
||||||
connection, model_path: str, load: dict[str, Any], limits: dict[str, Any]
|
connection, model_path: str, load: dict[str, Any], limits: dict[str, Any]
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Load one model and serve serialized requests until stopped."""
|
"""Load one model and serve serialized requests until stopped."""
|
||||||
|
stage = "import_torch"
|
||||||
try:
|
try:
|
||||||
import torch
|
import torch
|
||||||
|
|
||||||
|
stage = "import_transformers"
|
||||||
from transformers import AutoModelForCausalLM, AutoTokenizer
|
from transformers import AutoModelForCausalLM, AutoTokenizer
|
||||||
|
|
||||||
hub_options = {"local_files_only": True, "trust_remote_code": False}
|
hub_options = {"local_files_only": True, "trust_remote_code": False}
|
||||||
if load.get("revision") is not None:
|
if load.get("revision") is not None:
|
||||||
hub_options["revision"] = load["revision"]
|
hub_options["revision"] = load["revision"]
|
||||||
|
stage = "load_tokenizer"
|
||||||
tokenizer = AutoTokenizer.from_pretrained(
|
tokenizer = AutoTokenizer.from_pretrained(
|
||||||
model_path,
|
model_path,
|
||||||
**hub_options,
|
**hub_options,
|
||||||
)
|
)
|
||||||
|
stage = "load_model"
|
||||||
dtype_name = load.get("dtype", "auto")
|
dtype_name = load.get("dtype", "auto")
|
||||||
torch_dtype = "auto" if dtype_name == "auto" else getattr(torch, dtype_name)
|
torch_dtype = "auto" if dtype_name == "auto" else getattr(torch, dtype_name)
|
||||||
device = load.get("device", "cpu")
|
device = load.get("device", "cpu")
|
||||||
@@ -29,12 +34,23 @@ def guard_worker_main(
|
|||||||
torch_dtype=torch_dtype,
|
torch_dtype=torch_dtype,
|
||||||
**hub_options,
|
**hub_options,
|
||||||
)
|
)
|
||||||
|
stage = "move_to_device"
|
||||||
model.to(device)
|
model.to(device)
|
||||||
|
stage = "eval_model"
|
||||||
model.eval()
|
model.eval()
|
||||||
_send(connection, {"ok": True})
|
_send(connection, {"ok": True})
|
||||||
except Exception:
|
except Exception as exc:
|
||||||
|
exception = type(exc).__name__
|
||||||
|
dependency = exc.name if isinstance(exc, ImportError) else None
|
||||||
|
failure = {
|
||||||
|
"ok": False,
|
||||||
|
"error": "ModelLoadFailed",
|
||||||
|
"stage": stage,
|
||||||
|
"exception": exception if exception in MODEL_LOAD_ERRORS else "unknown",
|
||||||
|
"dependency": dependency if dependency in MODEL_DEPENDENCIES else "unknown",
|
||||||
|
}
|
||||||
try:
|
try:
|
||||||
_send(connection, {"ok": False, "error": "ModelLoadFailed"})
|
_send(connection, failure)
|
||||||
finally:
|
finally:
|
||||||
connection.close()
|
connection.close()
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import builtins
|
||||||
|
import json
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from unittest.mock import Mock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from middleware.config import LLMConfig
|
||||||
|
from middleware.llm import GuardAdapter, LLMUnavailable
|
||||||
|
from middleware.llm_worker import guard_worker_main
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("stage", "error", "dependency"),
|
||||||
|
[
|
||||||
|
("import_torch", ModuleNotFoundError("private-message", name="torch"), "torch"),
|
||||||
|
("import_transformers", ImportError("private-message"), "unknown"),
|
||||||
|
("load_tokenizer", PermissionError("private-message"), "unknown"),
|
||||||
|
("load_model", OSError("private-message"), "unknown"),
|
||||||
|
("move_to_device", RuntimeError("private-message"), "unknown"),
|
||||||
|
("eval_model", ValueError("private-message"), "unknown"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_worker_reports_load_stage_without_raw_exception(monkeypatch, stage, error, dependency):
|
||||||
|
def step(name, value=None):
|
||||||
|
if name == stage:
|
||||||
|
raise error
|
||||||
|
return value
|
||||||
|
|
||||||
|
model = SimpleNamespace(
|
||||||
|
to=lambda device: step("move_to_device"),
|
||||||
|
eval=lambda: step("eval_model"),
|
||||||
|
)
|
||||||
|
transformers = SimpleNamespace(
|
||||||
|
AutoTokenizer=SimpleNamespace(
|
||||||
|
from_pretrained=lambda *a, **kw: step("load_tokenizer", object())
|
||||||
|
),
|
||||||
|
AutoModelForCausalLM=SimpleNamespace(
|
||||||
|
from_pretrained=lambda *a, **kw: step("load_model", model)
|
||||||
|
),
|
||||||
|
)
|
||||||
|
original_import = builtins.__import__
|
||||||
|
|
||||||
|
def import_module(name, *args, **kwargs):
|
||||||
|
if name == "torch":
|
||||||
|
return step("import_torch", SimpleNamespace())
|
||||||
|
if name == "transformers":
|
||||||
|
return step("import_transformers", transformers)
|
||||||
|
return original_import(name, *args, **kwargs)
|
||||||
|
|
||||||
|
monkeypatch.setattr(builtins, "__import__", import_module)
|
||||||
|
connection = Mock()
|
||||||
|
guard_worker_main(connection, "/private-model-path", {}, {})
|
||||||
|
|
||||||
|
payload = connection.send_bytes.call_args.args[0]
|
||||||
|
result = json.loads(payload)
|
||||||
|
assert result == {
|
||||||
|
"ok": False,
|
||||||
|
"error": "ModelLoadFailed",
|
||||||
|
"stage": stage,
|
||||||
|
"exception": type(error).__name__,
|
||||||
|
"dependency": dependency,
|
||||||
|
}
|
||||||
|
assert b"private" not in payload
|
||||||
|
connection.close.assert_called_once()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("malformed", [False, True])
|
||||||
|
async def test_adapter_logs_failure_and_cleans_up(tmp_path, caplog, malformed):
|
||||||
|
result = {
|
||||||
|
"ok": False,
|
||||||
|
"error": "ModelLoadFailed",
|
||||||
|
"stage": "import_torch",
|
||||||
|
"exception": "ModuleNotFoundError",
|
||||||
|
"dependency": "torch",
|
||||||
|
"message": "private-message",
|
||||||
|
}
|
||||||
|
if malformed:
|
||||||
|
result.update(stage=["private"], exception="private-error", dependency={"private": True})
|
||||||
|
parent = Mock()
|
||||||
|
parent.recv_bytes.return_value = json.dumps(result).encode()
|
||||||
|
child = Mock()
|
||||||
|
process = Mock()
|
||||||
|
process.is_alive.side_effect = [True, False]
|
||||||
|
adapter = GuardAdapter(LLMConfig(id="guard", type="guard", file=tmp_path))
|
||||||
|
adapter.context = Mock()
|
||||||
|
adapter.context.Pipe.return_value = (parent, child)
|
||||||
|
adapter.context.Process.return_value = process
|
||||||
|
|
||||||
|
with pytest.raises(LLMUnavailable, match="ModelLoadFailed") as failure:
|
||||||
|
await adapter.start()
|
||||||
|
|
||||||
|
expected = "stage=unknown" if malformed else "stage=import_torch"
|
||||||
|
assert expected in caplog.text
|
||||||
|
assert expected in str(failure.value)
|
||||||
|
assert "private" not in caplog.text + str(failure.value)
|
||||||
|
assert adapter.process is None
|
||||||
|
assert adapter.connection is None
|
||||||
|
process.terminate.assert_called_once()
|
||||||
|
parent.close.assert_called_once()
|
||||||
|
child.close.assert_called_once()
|
||||||
Reference in new issue
Block a user