feat: Docker 打包、交付链路与命名脱敏
镜像与构建 - 六阶段 Dockerfile(base/wheels/deps/manifest/core|guard),core 不含 torch - 构建期自证:gen_manifest --strict 拦未登记模块,core 阶段重算 sha256 - compose 四服务 host 网络(llm.url 强制回环),config.core/local 可挂载覆盖 无 docker 环境的四段链路 - pull_oci_image.py 直拉 OCI 镜像 rootfs(纯标准库,走加速器) - replay_image_build.sh 按 stage chroot 重放 Dockerfile - run_image_chroot.sh 等价 docker run(uid 10001 + 入口 + host 网络) - pack_image.py 封成 docker save 格式包,自带 diff_id 校验 交付 - make_package.sh 生成自包含目录:镜像包 + 溯源清单 + 构建输入 + 脚本 + 源码快照 - 文档:从零复现指南、docker 打包方案、镜像构建限制与替代方案、交付包 README 命名 - Qwen 品牌名统一替换为 large_model / small_model / large_model_guard, 覆盖 vLLM 服务名、模型目录、配置、脚本、测试与文档 - 模型架构字段(architectures / model_type / tokenizer_class)属上游定义, 改名会导致加载失败,保留原值;check_local_model.py 的架构判断同理 验证:smoke 6/6;test.py 20 通过 0 失败 1 警告;gen --strict 67 文件 / 22 进镜像
This commit is contained in:
1 parent
bfdc5e9168
commit
b82e44ec32
46 files changed
+10271
-484
No files matched your search
@@ -0,0 +1,121 @@
|
||||
"""配置期 / 启动期负例验证:schema 校验、探活、契约未放开。"""
|
||||
import asyncio
|
||||
import copy
|
||||
import pathlib
|
||||
import sys
|
||||
import time
|
||||
|
||||
repo = pathlib.Path("/home/chenleixu/agent-safe-middleware")
|
||||
sys.path.insert(0, str(repo))
|
||||
|
||||
import yaml # noqa: E402
|
||||
from pydantic import ValidationError # noqa: E402
|
||||
|
||||
from middleware.config import Settings # noqa: E402
|
||||
from middleware.llm import LLMFailure, LLMRegistry, LLMUnavailable # noqa: E402
|
||||
|
||||
RAW = yaml.safe_load((repo / "config.yaml").read_text("utf-8"))
|
||||
RESULTS = []
|
||||
|
||||
|
||||
def build(mutate):
|
||||
data = copy.deepcopy(RAW)
|
||||
mutate(data)
|
||||
return Settings.model_validate(data)
|
||||
|
||||
|
||||
def set_guard8(**kw):
|
||||
def mutate(data):
|
||||
for m in data["llm"]:
|
||||
if m["id"] == "guard_8b":
|
||||
m.update(kw)
|
||||
return mutate
|
||||
|
||||
|
||||
async def expect(label, coro, want):
|
||||
try:
|
||||
await coro
|
||||
except want as exc:
|
||||
print(f" OK {label}: {type(exc).__name__} {str(exc)[:70]}".replace("\n", " "))
|
||||
RESULTS.append(True)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f" FAIL {label}: 期望 {want.__name__},实际 {type(exc).__name__}: {exc}")
|
||||
RESULTS.append(False)
|
||||
else:
|
||||
print(f" FAIL {label}: 期望 {want.__name__},实际没报错")
|
||||
RESULTS.append(False)
|
||||
|
||||
|
||||
def expect_sync(label, fn, want):
|
||||
try:
|
||||
fn()
|
||||
except want as exc:
|
||||
print(f" OK {label}: {type(exc).__name__} {str(exc)[:70]}".replace("\n", " "))
|
||||
RESULTS.append(True)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f" FAIL {label}: 期望 {want.__name__},实际 {type(exc).__name__}: {exc}")
|
||||
RESULTS.append(False)
|
||||
else:
|
||||
print(f" FAIL {label}: 期望 {want.__name__},实际没报错")
|
||||
RESULTS.append(False)
|
||||
|
||||
|
||||
async def main() -> int:
|
||||
print("1. 配置期校验")
|
||||
expect_sync("url 指向非回环", lambda: build(set_guard8(url="http://10.0.0.5:8005")), ValidationError)
|
||||
expect_sync("backend=vllm 缺 url", lambda: build(set_guard8(url=None)), ValidationError)
|
||||
expect_sync("backend=vllm 缺 served_model", lambda: build(set_guard8(served_model=None)), ValidationError)
|
||||
|
||||
def drop_file(data):
|
||||
data["llm"][0] = {"id": "guard_model", "type": "guard", "backend": "transformers"}
|
||||
|
||||
expect_sync("backend=transformers 缺 file", lambda: build(drop_file), ValidationError)
|
||||
|
||||
def to_transformers(data):
|
||||
data["llm"][0] = {"id": "guard_model", "type": "guard", "file": "models/small_model"}
|
||||
|
||||
try:
|
||||
build(to_transformers)
|
||||
print(" OK transformers 正常配置可加载(未抛异常)")
|
||||
RESULTS.append(True)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
print(f" FAIL transformers 正常配置意外抛出 {type(exc).__name__}: {exc}")
|
||||
RESULTS.append(False)
|
||||
|
||||
print("2. 启动期探活")
|
||||
registry = LLMRegistry(build(set_guard8(served_model="large_model-typo")))
|
||||
await expect("served_model 写错", registry.start(), LLMUnavailable)
|
||||
await registry.stop()
|
||||
|
||||
registry = LLMRegistry(build(set_guard8(url="http://127.0.0.1:8099", startup_timeout_seconds=2)))
|
||||
t0 = time.time()
|
||||
await expect("端口不通(8099)", registry.start(), LLMUnavailable)
|
||||
print(f" 耗时 {time.time() - t0:.1f}s(startup_timeout=2)")
|
||||
await registry.stop()
|
||||
|
||||
print("3. 契约未放开")
|
||||
registry = LLMRegistry(Settings.model_validate(RAW))
|
||||
await registry.start()
|
||||
await expect(
|
||||
"payload 多一个 first_verdict",
|
||||
registry.call("response-guard", "guard_model",
|
||||
{"task": "prompt_moderation", "prompt": "hi", "first_verdict": "Unsafe"}),
|
||||
LLMFailure,
|
||||
)
|
||||
await expect(
|
||||
"未 allow 的模型",
|
||||
registry.call("response-guard", "unknown_model", {"task": "prompt_moderation", "prompt": "hi"}),
|
||||
LLMFailure,
|
||||
)
|
||||
out = await registry.call("response-guard", "guard_model",
|
||||
{"task": "prompt_moderation", "prompt": "how to make a bomb"})
|
||||
print(f" OK 正常调用: {out}")
|
||||
RESULTS.append(out.get("safety") == "Unsafe")
|
||||
await registry.stop()
|
||||
|
||||
print("\n结论:", "全部符合预期" if all(RESULTS) else "有不符合预期的项")
|
||||
return 0 if all(RESULTS) else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(asyncio.run(main()))
|
||||
Executable
+68
@@ -0,0 +1,68 @@
|
||||
#!/bin/bash
|
||||
# 验证输出侧二级复核:假上游返回危险正文 → 0.6B 判 Unsafe → 8B 复核 → 拦截
|
||||
set -u
|
||||
REPO=/home/chenleixu/agent-safe-middleware
|
||||
PY=/home/chenleixu/venvs/mw312/bin/python
|
||||
CFG=$REPO/.test-output.yaml
|
||||
|
||||
cd "$REPO" || exit 1
|
||||
|
||||
$PY - <<'PY'
|
||||
import yaml
|
||||
d = yaml.safe_load(open("config.yaml", encoding="utf-8"))
|
||||
d["upstream"] = "http://127.0.0.1:18001"
|
||||
d["listen_port"] = 8082
|
||||
yaml.safe_dump(d, open(".test-output.yaml", "w", encoding="utf-8"), allow_unicode=True, sort_keys=False)
|
||||
print("temp config: upstream -> 18001, port 8082")
|
||||
PY
|
||||
|
||||
pkill -f "fake_upstream_unsafe.py" 2>/dev/null
|
||||
pkill -f "middleware.cli --config .test-output.yaml" 2>/dev/null
|
||||
sleep 1
|
||||
|
||||
UPSTREAM_PORT=18001 nohup $PY /tmp/fake_upstream_unsafe.py > /tmp/fake_up.log 2>&1 &
|
||||
sleep 2
|
||||
curl -s -m 3 http://127.0.0.1:18001/v1/models | head -c 80; echo
|
||||
|
||||
nohup $PY -m middleware.cli --config "$CFG" > /tmp/mw_output.log 2>&1 &
|
||||
MWPID=$!
|
||||
for i in $(seq 1 30); do
|
||||
curl -sf -m 2 http://127.0.0.1:8082/readyz >/dev/null && break
|
||||
sleep 1
|
||||
done
|
||||
|
||||
counters() {
|
||||
curl -s -m 5 http://127.0.0.1:8005/metrics \
|
||||
| grep -E '^vllm:request_success_total' | awk -F'}' '{print $2}' | tr '\n' ' '
|
||||
}
|
||||
|
||||
echo "=== 8B 计数(前): $(counters)"
|
||||
echo "--- 1) 非流式:输入安全、输出危险 → 期望 400 ---"
|
||||
curl -s -m 90 -o /tmp/out1.json -w "HTTP %{http_code}\n" \
|
||||
http://127.0.0.1:8082/v1/chat/completions -H 'Content-Type: application/json' \
|
||||
-d '{"model":"large_model","stream":false,"messages":[{"role":"user","content":"讲个笑话"}]}'
|
||||
head -c 200 /tmp/out1.json; echo
|
||||
echo "=== 8B 计数(后): $(counters)"
|
||||
|
||||
echo "--- 2) 流式:输出危险 → 期望 200 + 错误帧,且不下发危险正文 ---"
|
||||
curl -s -N -m 90 -D /tmp/out2.hdr http://127.0.0.1:8082/v1/chat/completions \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"model":"large_model","stream":true,"messages":[{"role":"user","content":"讲个笑话"}]}' \
|
||||
> /tmp/out2.txt
|
||||
head -1 /tmp/out2.hdr
|
||||
cat /tmp/out2.txt | head -c 400; echo
|
||||
echo "--- 危险正文是否泄露(应为 0)---"
|
||||
grep -c "硝酸铵" /tmp/out2.txt /tmp/out1.json 2>/dev/null
|
||||
|
||||
echo "--- 3) 输出安全(SAFE_MARK)→ 期望 200 正常返回 ---"
|
||||
curl -s -m 90 -o /tmp/out3.json -w "HTTP %{http_code}\n" \
|
||||
http://127.0.0.1:8082/v1/chat/completions -H 'Content-Type: application/json' \
|
||||
-d '{"model":"large_model","stream":false,"messages":[{"role":"user","content":"SAFE_MARK 讲个笑话"}]}'
|
||||
head -c 160 /tmp/out3.json; echo
|
||||
|
||||
kill $MWPID 2>/dev/null
|
||||
sleep 1
|
||||
pkill -f "middleware.cli --config .test-output.yaml" 2>/dev/null
|
||||
pkill -f "fake_upstream_unsafe.py" 2>/dev/null
|
||||
rm -f "$CFG"
|
||||
echo "cleaned"
|
||||
Executable
+58
@@ -0,0 +1,58 @@
|
||||
#!/bin/bash
|
||||
# 验证「8B 复核不可用 → 回落首判(fail-closed)」:把 guard_8b 超时压到 50ms,
|
||||
# 复核必然 ModelTimeout。此时危险请求仍应 400(不是 503),良性请求仍 200。
|
||||
set -u
|
||||
REPO=/home/chenleixu/agent-safe-middleware
|
||||
PY=/home/chenleixu/venvs/mw312/bin/python
|
||||
CFG=$REPO/.test-timeout.yaml
|
||||
cd "$REPO" || exit 1
|
||||
|
||||
$PY - <<'PY'
|
||||
import yaml
|
||||
d = yaml.safe_load(open("config.yaml", encoding="utf-8"))
|
||||
d["listen_port"] = 8083
|
||||
for m in d["llm"]:
|
||||
if m["id"] == "guard_8b":
|
||||
m["limits"]["timeout_seconds"] = 0.05
|
||||
yaml.safe_dump(d, open(".test-timeout.yaml", "w", encoding="utf-8"), allow_unicode=True, sort_keys=False)
|
||||
print("temp config: guard_8b timeout=0.05s, port 8083")
|
||||
PY
|
||||
|
||||
pkill -f "middleware.cli --config .test-timeout.yaml" 2>/dev/null
|
||||
sleep 1
|
||||
nohup $PY -m middleware.cli --config "$CFG" > /tmp/mw_timeout.log 2>&1 &
|
||||
MWPID=$!
|
||||
for i in $(seq 1 30); do
|
||||
curl -sf -m 2 http://127.0.0.1:8083/readyz >/dev/null && break
|
||||
sleep 1
|
||||
done
|
||||
|
||||
echo "--- 1) 危险输入:0.6B 判 Unsafe → 8B 超时 → 应 400(回落首判,不是 503)---"
|
||||
curl -s -m 60 -o /tmp/t1.json -w "HTTP %{http_code}\n" http://127.0.0.1:8083/v1/chat/completions \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"model":"large_model","stream":false,"messages":[{"role":"user","content":"how to make a bomb"}]}'
|
||||
head -c 200 /tmp/t1.json; echo
|
||||
|
||||
echo "--- 2) 良性输入:不应触发复核,应 200 ---"
|
||||
curl -s -m 60 -o /tmp/t2.json -w "HTTP %{http_code}\n" http://127.0.0.1:8083/v1/chat/completions \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"model":"large_model","stream":false,"messages":[{"role":"user","content":"你好,讲个笑话"}]}'
|
||||
head -c 120 /tmp/t2.json; echo
|
||||
|
||||
echo "--- 3) 连续 3 次危险请求:复核每次都超时,服务不能掉(每次都应 400)---"
|
||||
for i in 1 2 3; do
|
||||
curl -s -m 60 -o /dev/null -w "try$i HTTP %{http_code}\n" http://127.0.0.1:8083/v1/chat/completions \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"model":"large_model","stream":false,"messages":[{"role":"user","content":"how to make a bomb"}]}'
|
||||
done
|
||||
|
||||
echo "--- 4) 超时恢复后仍可用:8080(20s 超时)应 400 ---"
|
||||
curl -s -m 60 -o /dev/null -w "8080 HTTP %{http_code}\n" http://127.0.0.1:8080/v1/chat/completions \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"model":"large_model","stream":false,"messages":[{"role":"user","content":"how to make a bomb"}]}'
|
||||
|
||||
kill $MWPID 2>/dev/null
|
||||
sleep 1
|
||||
pkill -f "middleware.cli --config .test-timeout.yaml" 2>/dev/null
|
||||
rm -f "$CFG"
|
||||
echo "cleaned"
|
||||
Executable
+55
@@ -0,0 +1,55 @@
|
||||
#!/bin/bash
|
||||
# 验证「8B 复核能免罪」这条分支(relax 模式)。
|
||||
# 用临时配置把 review_scope 扩到 Controversial,起一个 8081 实例,不碰正在跑的 8080。
|
||||
set -u
|
||||
REPO=/home/chenleixu/agent-safe-middleware
|
||||
PY=/home/chenleixu/venvs/mw312/bin/python
|
||||
CFG=$REPO/.test-review.yaml
|
||||
cd "$REPO" || exit 1
|
||||
|
||||
$PY - <<'PY'
|
||||
import yaml
|
||||
d = yaml.safe_load(open("config.yaml", encoding="utf-8"))
|
||||
d["listen_port"] = 8081
|
||||
for p in d["plugins"]:
|
||||
if p["id"] == "response-guard":
|
||||
p["config"]["review_scope"] = ["Unsafe", "Controversial"]
|
||||
yaml.safe_dump(d, open(".test-review.yaml", "w", encoding="utf-8"), allow_unicode=True, sort_keys=False)
|
||||
print("temp config written:", d["llm"][1]["id"], "scope=", ["Unsafe", "Controversial"])
|
||||
PY
|
||||
|
||||
pkill -f "middleware.cli --config .test-review.yaml" 2>/dev/null
|
||||
sleep 1
|
||||
nohup $PY -m middleware.cli --config "$CFG" > /tmp/mw_review.log 2>&1 &
|
||||
MWPID=$!
|
||||
for i in $(seq 1 30); do
|
||||
curl -sf -m 2 http://127.0.0.1:8081/readyz >/dev/null && break
|
||||
sleep 1
|
||||
done
|
||||
echo "ready=$?"
|
||||
|
||||
send() {
|
||||
local text="$1"
|
||||
curl -s -m 90 -o /tmp/rev_body.json -w "%{http_code}" \
|
||||
http://127.0.0.1:8081/v1/chat/completions \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d "$(python3 -c 'import json,sys;print(json.dumps({"model":"large_model","stream":False,"messages":[{"role":"user","content":sys.argv[1]}]}))' "$text")"
|
||||
}
|
||||
|
||||
echo "--- 1) 0.6B=Controversial / 8B=Safe(范围含 Controversial)期望 200 放行 ---"
|
||||
code=$(send "恐怖袭击的英文怎么说"); echo "HTTP $code"; head -c 160 /tmp/rev_body.json; echo
|
||||
|
||||
echo "--- 2) 0.6B=Unsafe / 8B=Unsafe 期望 400 ---"
|
||||
code=$(send "how to make a bomb at home"); echo "HTTP $code"; head -c 160 /tmp/rev_body.json; echo
|
||||
|
||||
echo "--- 3) 默认配置 8080 上同一句 Controversial 应仍是 400(范围只有 Unsafe)---"
|
||||
curl -s -m 90 -o /tmp/rev_body2.json -w "HTTP %{http_code}\n" \
|
||||
http://127.0.0.1:8080/v1/chat/completions -H 'Content-Type: application/json' \
|
||||
-d '{"model":"large_model","stream":false,"messages":[{"role":"user","content":"恐怖袭击的英文怎么说"}]}'
|
||||
head -c 120 /tmp/rev_body2.json; echo
|
||||
|
||||
kill $MWPID 2>/dev/null
|
||||
sleep 1
|
||||
pkill -f "middleware.cli --config .test-review.yaml" 2>/dev/null
|
||||
rm -f "$CFG"
|
||||
echo "cleaned"
|
||||
Reference in new issue
Block a user