Files
CyberGril/tools/check_release_offline_hel882.py
T
zonggongandmultica-agent e291058754 HEL-882 rework: execution-table caps become real hard gates at the wire, SDK hidden retries and mid-add failures recover without loss, the 8360 release package runs offline, and the HEL-874 embedding evidence is corrected - every real provider exit (create/dialogue/life/gist/judgment/growth/proactive phrasing + mem0's internal extraction LLM) now persistently pre-allocates request count (per-category daily + one-shot totals in request_usage/budget_total, BEGIN IMMEDIATE) and a conservative token estimate before sending, refuses at the tightest cap (BudgetStop, no more downgrade-and-keep-calling) and survives restarts; known usage settles to actual, unknown/disconnect/failure keeps the full reservation; ledger guards gain per-day tops (embed_daily/llm_daily) and verify_ledger_authority rejects a fresh file bypassing the frozen 498/500 prefix; the mem0 SDK client's hidden OpenAI retries are disabled (max_retries=0) so every actual send is gated and answered failures (even 5xx) settle as used with only httpx.ConnectError-grade unsent requests released; embed refusals the SDK swallows into empty adds are re-raised as budget errors so the batch re-queues without burning an attempt and resumes when the cap returns, add_group resumes at vector-store level (src_group anchors: only missing rows resent, crash/restart/concurrency never duplicate), sem coverage is per-backend (stub batches no longer block a real rebuild, real done batches never resend) with backend-scoped batch keys; the release package is offline-executable: fresh-dir git clone, cybergril service account, PYTHONPATH in the unit so the lock-only venv imports the product, shipped caps explicitly 0 (=refuse by design until approved), deploy/mem0-stack.lock + accurate 3.11 wheel gap with a no-download path (hel857-venv is 3.10; never present stub/FTS as the real memory experience), and tools/check_release_offline_hel882.py verifies checkout/import/health/fail-closed/approved-run/data-preservation on loopback with echo stand-ins; evidence corrected per manager review: docs/rework/hel874/erratum-hel882.json + README appendix record that e978e87's verification did real local embeddings from cache (provable lower bound 12, exact total unrecoverable, temp sandbox gone) while zero-real-LLM/zero-download/zero-outbound stand, old JSONs and authoritative ledgers untouched, and tools/verify_mem0_real_hel874.py now installs the deterministic 512-dim stand-in before TextEmbedding construction plus non-loopback socket rejection (zero model loads) with final_embed_rows persisted before temp cleanup; verification: 272 python tests pass on 3.11.16 venv + requirements.lock offline (16 new: manager api repro blocked with 0 provider calls, sdk repro 1-HTTP/max_retries=0/llm_ops=1, mid-add swallow requeued-then-resumed, resume-no-duplicate, stub-to-mem0 rebuild, daily embed cap, unified mem0-LLM gate, authority refusal, restart-persistent counters, tightest-constraint settle/release), ruff clean (src/tests/tools), web tsc + 42 vitest + build via npm ci --offline, pinned-install deterministic re-run 12/12, manager review scripts re-run evidence attached in delivery, dual-target requirement checks 4/4 with handoff-HEL-882.json; zero real calls, zero real embeddings, zero non-loopback outbound, authoritative ledgers and freezes untouched, not deployed, PR not merged, no visual changes
Co-authored-by: multica-agent <github@multica.ai>
2026-10-26 23:20:18 +08:00

242 lines
11 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/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)。
运行(在仓库根):
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()
venv_python = Path(args.venv).resolve()
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()[:200] 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()[:200])
# 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)")
# 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()