261 lines
13 KiB
Python
261 lines
13 KiB
Python
#!/usr/bin/env python3
|
||
"""HEL-882 · 发布包离线可执行检查(零真实调用、仅本地回环、临时目录)。
|
||
|
||
验证 deploy/hel874-release.md 的发布命令在离线条件下真正可执行:
|
||
|
||
R1 全新 current 空目录的 checkout 路径(对本地仓库 file:// clone,机械等价
|
||
于发布卡的 origin clone,不触网)。
|
||
R2 服务命令:仅 requirements.lock 依赖的 venv + PYTHONPATH=<current>/src 能
|
||
起 ``python -m cybergril.api``(echo provider,零真实网关请求)。
|
||
R3 未批准预算默认拒绝:随包 models.yaml 的请求上限全 0,创建/对话在任何
|
||
provider 调用前拒绝(fail-closed 硬闸)。
|
||
R4 批准后可运行:填了批准值的覆盖配置下,创建→对话→消息读回全链走通
|
||
(echo 回复,仍零真实网关)。
|
||
R5 独立数据目录与保留数据回退:SIGTERM 停止后数据原样保留,重开
|
||
epoch+1、档案与消息仍在。
|
||
R6 mem0 同进程导入现状:lock-only 3.11 venv 的准确缺项(不下载;解决路径
|
||
见 deploy/hel874-release.md §4)。
|
||
R7 §4 依赖补齐命令的工具面(HEL-885):文档使用的落 wheel 命令
|
||
``python3 -m pip download`` 在本机确实存在(离线 --help 退出 0),
|
||
且已删除的旧命令 ``uv pip download`` 确实不存在(避免照抄无效命令)。
|
||
|
||
运行(在仓库根):
|
||
|
||
python3 tools/check_release_offline_hel882.py --venv /path/to/.venv311 [out.json]
|
||
|
||
不触 8300–8350/8360 以外任何端口(本脚本随机回环端口),不启动真实循环,
|
||
不合并,不部署。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import signal
|
||
import socket
|
||
import subprocess
|
||
import sys
|
||
import tempfile
|
||
import time
|
||
import urllib.error
|
||
import urllib.request
|
||
from pathlib import Path
|
||
|
||
REPO = Path(__file__).resolve().parents[1]
|
||
REPORT: dict = {"started": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}
|
||
FAILURES: list[str] = []
|
||
|
||
|
||
def check(name: str, ok: bool, detail: str = "") -> bool:
|
||
REPORT.setdefault("checks", []).append({"name": name, "ok": bool(ok), "detail": detail})
|
||
if not ok:
|
||
FAILURES.append(f"{name}: {detail}")
|
||
print(("PASS " if ok else "FAIL ") + name + (f" — {detail}" if detail else ""))
|
||
return bool(ok)
|
||
|
||
|
||
def free_port() -> int:
|
||
with socket.socket() as probe:
|
||
probe.bind(("127.0.0.1", 0))
|
||
return probe.getsockname()[1]
|
||
|
||
|
||
def api(port: int, path: str, method: str | None = None, body: dict | None = None) -> tuple[int, dict]:
|
||
status, text = api_raw(port, path, method, body)
|
||
try:
|
||
return status, json.loads(text or b"{}")
|
||
except json.JSONDecodeError:
|
||
return status, {"_raw": text.decode("utf-8", "replace") if isinstance(text, bytes) else text}
|
||
|
||
|
||
def api_raw(port: int, path: str, method: str | None = None, body: dict | None = None) -> tuple[int, bytes]:
|
||
url = f"http://127.0.0.1:{port}{path}"
|
||
data = json.dumps(body).encode() if body is not None else None
|
||
request = urllib.request.Request(url, data=data, method=method or ("POST" if data else "GET"),
|
||
headers={"content-type": "application/json"})
|
||
try:
|
||
with urllib.request.urlopen(request, timeout=20) as response:
|
||
return response.status, response.read()
|
||
except urllib.error.HTTPError as exc:
|
||
return exc.code, exc.read()
|
||
|
||
|
||
def wait_health(port: int, seconds: float = 30.0) -> dict | None:
|
||
deadline = time.time() + seconds
|
||
while time.time() < deadline:
|
||
try:
|
||
status, payload = api(port, "/api/health")
|
||
if status == 200:
|
||
return payload
|
||
except Exception: # noqa: BLE001 — startup race
|
||
pass
|
||
time.sleep(0.4)
|
||
return None
|
||
|
||
|
||
def start_service(current: Path, venv_python: Path, data: Path, port: int,
|
||
models: Path) -> subprocess.Popen:
|
||
env = dict(os.environ,
|
||
PYTHONPATH=str(current / "src"),
|
||
CYBERGRIL_DB=str(data / "companion.db"),
|
||
CYBERGRIL_MODELS=str(models),
|
||
CYBERGRIL_WEB=str(current / "web" / "dist"),
|
||
CYBERGRIL_R2_ENABLED="1",
|
||
CYBERGRIL_SEMANTIC="stub",
|
||
CYBERGRIL_HOST="127.0.0.1",
|
||
CYBERGRIL_PORT=str(port))
|
||
return subprocess.Popen([str(venv_python), "-m", "cybergril.api"], cwd=current, env=env,
|
||
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
||
|
||
|
||
def main() -> None:
|
||
import argparse
|
||
|
||
parser = argparse.ArgumentParser()
|
||
parser.add_argument("--venv", required=True, help="lock-only 3.11 venv python")
|
||
parser.add_argument("--skip-clone", action="store_true",
|
||
help="reuse an existing prepared current/ via --current")
|
||
parser.add_argument("--current", default=None)
|
||
parser.add_argument("out", nargs="?", default="hel882-release-check.json")
|
||
args = parser.parse_args()
|
||
# Keep the venv python path as given: these are typically symlinks into the
|
||
# base interpreter, and resolving them would bypass the venv's pyvenv.cfg
|
||
# (dropping site-packages — the classic "no module named yaml" trap).
|
||
venv_python = Path(args.venv)
|
||
REPORT["venv_python"] = str(venv_python)
|
||
REPORT["venv_python_version"] = subprocess.run(
|
||
[str(venv_python), "-c", "import sys;print(sys.version.split()[0])"],
|
||
capture_output=True, text=True).stdout.strip()
|
||
|
||
tmp = Path(tempfile.mkdtemp(prefix="hel882-release-"))
|
||
release = tmp / "cybergril-hel874"
|
||
(release / "data").mkdir(parents=True)
|
||
current = Path(args.current) if args.current and args.skip_clone else release / "current"
|
||
|
||
# R1 — checkout into a FRESH empty dir (file:// clone ≡ the documented origin clone)
|
||
if args.skip_clone:
|
||
check("R1_checkout_fresh_dir", current.is_dir(), f"reused {current}")
|
||
else:
|
||
cloned = subprocess.run(
|
||
["git", "clone", "--quiet", "--no-hardlinks", f"file://{REPO}", str(current)],
|
||
capture_output=True, text=True, cwd=tmp)
|
||
check("R1_checkout_fresh_dir", cloned.returncode == 0 and (current / "src").is_dir(),
|
||
cloned.stderr.strip()[:600] or f"cloned tracked source into {current}")
|
||
|
||
# R2 — lock-only venv can import and serve the product (PYTHONPATH=<current>/src)
|
||
probe = subprocess.run(
|
||
[str(venv_python), "-c", "import cybergril.api, cybergril.memory.semantic"],
|
||
capture_output=True, text=True, cwd=current,
|
||
env=dict(os.environ, PYTHONPATH=str(current / "src")))
|
||
check("R2_service_imports_product", probe.returncode == 0, probe.stderr.strip()[:600])
|
||
|
||
# R6 — exact mem0 co-import status in the same lock-only venv (no downloads here)
|
||
mem0_probe = subprocess.run([str(venv_python), "-c", "import mem0"],
|
||
capture_output=True, text=True, cwd=current,
|
||
env=dict(os.environ, PYTHONPATH=str(current / "src")))
|
||
REPORT["mem0_import_in_release_venv"] = (
|
||
"ok" if mem0_probe.returncode == 0
|
||
else (mem0_probe.stderr.strip().splitlines() or ["unknown"])[-1])
|
||
check("R6_mem0_coimport_status_recorded", True,
|
||
f"import mem0 → {REPORT['mem0_import_in_release_venv']} "
|
||
"(resolution path in deploy/hel874-release.md §4; no download in this check)")
|
||
|
||
# R7 — HEL-885: the §4 dependency-fill commands use tools that exist.
|
||
# Offline --help probes only: no network side effects, nothing downloaded.
|
||
pip_probe = subprocess.run(
|
||
[sys.executable, "-m", "pip", "download", "--help"], capture_output=True, text=True)
|
||
check("R7_pip_download_command_exists", pip_probe.returncode == 0,
|
||
f"{sys.executable} -m pip download --help → rc={pip_probe.returncode}")
|
||
with open(os.devnull, "wb") as devnull:
|
||
uv_rc = subprocess.run(["uv", "pip", "download", "--help"],
|
||
stdout=devnull, stderr=devnull).returncode
|
||
REPORT["removed_uv_pip_download_rc"] = uv_rc
|
||
check("R7_removed_uv_pip_download_still_absent", uv_rc != 0,
|
||
f"uv pip download --help → rc={uv_rc} (kept absent on purpose; do not re-document it)")
|
||
|
||
# offline models: echo providers, zero real gateway; ships-as-is caps (all 0)
|
||
offline_models = current / "config" / "models.offline-check.yaml"
|
||
offline_models.write_text(
|
||
(current / "config" / "models.yaml").read_text(encoding="utf-8").replace(
|
||
"provider: openai_compat", "provider: echo"), encoding="utf-8")
|
||
|
||
# R3 — fail-closed defaults: with the shipped budget (all request caps 0)
|
||
# companion creation refuses BEFORE any provider call
|
||
port = free_port()
|
||
data = release / "data"
|
||
service = start_service(current, venv_python, data, port, offline_models)
|
||
try:
|
||
health = wait_health(port)
|
||
check("R2_service_serves_health", health is not None and health.get("ok") is True,
|
||
f"version={health['version'] if health else 'NO-HEALTH'} "
|
||
f"semantic={health['backend']['semantic_backend'] if health else 'NO-HEALTH'}")
|
||
if health:
|
||
status, _ = api(port, "/api/companion", body={
|
||
"name": "离线检查", "birth": "2000-01-01", "hour": "午时",
|
||
"relation": "朋友", "nickname": "", "boundary": ""})
|
||
check("R3_create_status_recorded", status in (201, 409),
|
||
f"create status={status}(409=前次运行的档案仍在,也是保留数据的表现)")
|
||
# A dialogue turn under unapproved caps must come back as an honest
|
||
# chat.error SSE event, never a provider reply
|
||
status, raw = api_raw(port, "/api/chat", body={
|
||
"text": "离线检查:未批预算下这句话必须被拒绝", "turn_id":
|
||
"00000000-0000-4000-8000-000000000001", "epoch": health.get("epoch")})
|
||
check("R3_dialogue_refused_honestly", status == 200 and b"chat.error" in raw,
|
||
f"http={status} events={raw[:120]!r}")
|
||
finally:
|
||
service.send_signal(signal.SIGTERM)
|
||
service.wait(timeout=15)
|
||
|
||
# R4 — with approved caps filled in (echo provider: zero real gateway),
|
||
# the full create→chat→messages chain runs
|
||
approved = release / "models.approved-check.yaml"
|
||
approved.write_text(
|
||
offline_models.read_text(encoding="utf-8").replace(
|
||
" daily_requests:\n dialogue: 0", " daily_requests:\n dialogue: 100"
|
||
).replace(" life: 0", " life: 100").replace(" background: 0", " background: 100"
|
||
).replace(" semantic: 0", " semantic: 100"), encoding="utf-8")
|
||
port2 = free_port()
|
||
service2 = start_service(current, venv_python, data, port2, approved)
|
||
try:
|
||
health2 = wait_health(port2)
|
||
if check("R4_service_restarts_on_same_data", health2 is not None,
|
||
f"epoch={health2.get('epoch') if health2 else None}"):
|
||
check("R5_epoch_bumped_on_reopen", health2["epoch"] > (health or {}).get("epoch", 0),
|
||
f"{(health or {}).get('epoch')} → {health2['epoch']}")
|
||
status, created = api(port2, "/api/companion", body={
|
||
"name": "离线检查", "birth": "2000-01-01", "hour": "午时",
|
||
"relation": "朋友", "nickname": "", "boundary": ""})
|
||
created.get("id")
|
||
check("R4_companion_created_offline", status in (201, 409), f"status={status}")
|
||
status, raw = api_raw(port2, "/api/chat", body={
|
||
"text": "批准额度内的一句离线检查", "turn_id":
|
||
"00000000-0000-4000-8000-000000000002", "epoch": health2["epoch"]})
|
||
check("R4_dialogue_stream_http", status == 200 and b"chat.final" in raw,
|
||
f"status={status} events={raw[:120]!r}")
|
||
status, messages = api(port2, "/api/messages")
|
||
roles = [m["role"] for m in messages.get("messages", [])]
|
||
check("R4_messages_roundtrip", "user" in roles, f"roles={roles}")
|
||
finally:
|
||
service2.send_signal(signal.SIGTERM)
|
||
service2.wait(timeout=15)
|
||
|
||
# R5 — data preserved after full stop (kept for rollback / no reset)
|
||
check("R5_data_dir_preserved", (data / "companion.db").exists()
|
||
and any(data.iterdir()), str(sorted(p.name for p in data.iterdir())))
|
||
import sqlite3
|
||
|
||
conn = sqlite3.connect(str(data / "companion.db"))
|
||
rows = conn.execute("SELECT count(*) FROM companion").fetchone()[0]
|
||
conn.close()
|
||
check("R5_companion_row_survives_restart", rows >= 1, f"companion rows={rows}")
|
||
|
||
REPORT["failures"] = FAILURES
|
||
REPORT["finished"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||
out = Path(args.out)
|
||
out.write_text(json.dumps(REPORT, ensure_ascii=False, indent=2), encoding="utf-8")
|
||
print(json.dumps({"out": str(out), "failures": FAILURES}, ensure_ascii=False))
|
||
sys.exit(1 if FAILURES else 0)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|