Files
CyberGril/tools/check_release_offline_hel882.py
T
zonggongandmultica-agent 78b6267d3a HEL-885 rework: per-row progress matches what was really sent, cross-day and unknown-outcome accounting stay conservative, positive caps require the ledger authority, and the release dependency-fill command actually exists - every Memory.add now carries an anchor for exactly its own row (the HEL-882 whole-batch anchor let the first stored vector mark unsent rows complete; the manager's real-SDK partial reproduction showed the user's original words never leaving the process), a row finishing with a legitimately EMPTY extraction gets a durable sem_row_done record (r4.sql additive table) written inside the worker thread the moment its add completes, resume skips = vector-store anchors ∪ sem_row_done so no row is lost, none falsely complete, and finished work is never re-sent across budget-refusal/crash/restart/lease/concurrency, entry_ids merge across partial attempts, and the swallowed-failure detection is per-row; PersistentBudget.settle/release book on hold.day (the old write to state.day manufactured -80 used on the new day and re-opened headroom the reservation day had already spent; token_usage/request_usage refund the paying day, budget_total stays global) and the empty-budget_total TypeError crash in total_requests_used/total_tokens_used is fixed - the old one-shot-total test passed only because that crash surfaced as chat.error, it now books the total honestly; _atomic_reserve no longer purges aged reserve: rows (a crashed worker's hold is an UNKNOWN outcome - an hour-old timeout is not proof the call never happened; unknown consumption stays billed across restarts, only a provably-unsent release() ever removes a hold, embed_ops and llm_ops share the fix); Mem0Backend refuses construction before importing mem0 when any cap>0 lacks a (non-empty dict) authority block - ledger_authority_required - or when the prefix check fails, closing the fresh-empty-ledger bypass the manager reproduced live, config/semantic.example.yaml ships the authority block as REQUIRED with the explicit cumulative formula (embed_cap=500+approved-increment e.g. 680, embed_reserve=2 frozen untouched, min_used=498; never write 180 as the cumulative cap of a 498-used account) mirrored into docs/budget-plan-hel874.md §2 with the HEL-885 accounting rules; deploy/hel874-release.md §4 replaces the nonexistent uv pip download (rc=2, re-verified) with python3 -m pip download --only-binary :all: --platform manylinux2014_x86_64 --python-version 3.11 --implementation cp --abi cp311 + sha256 manifest + uv pip install --no-index --find-links offline merge + same-process co-import verdict, honest missing-materials list unchanged (no 3.11 wheels cached, zero downloads this card, no version swaps), and tools/check_release_offline_hel882.py gains R7 probing both command surfaces offline; verification: 281 python tests pass on 3.11.16 venv + requirements.lock offline (9 new tests/test_rework_hel885.py cases: partial batch claims only the sent row / empty-extraction row completes and is never resent / process restart sends only the missing row / concurrent ticks never double-send / cross-day settle and release book on the reservation day / aged unknown llm+embed reservations never refunded / missing-empty-malformed-wrong authority all fail closed; test_resume_never_loses_or_duplicates_rows rewritten to drive the REAL product path instead of hand-planting single-row anchors the product never wrote), ruff clean (src/tests/tools), web tsc + 42 vitest + build via npm ci --offline, pinned mem0 2.2.1 install on the deterministic boundary: contract re-run 12/12 (harness now hands a synthetic authority prefix - production defaults not relaxed), new tools/verify_semantic_recovery_hel885.py 7/7 (S0 authority fail-closed, S1 per-row partial with exactly 1 HTTP, S2 restart sends only the missing row proven by HTTP count since mem0 prompts legitimately carry old rows in rolling history, S3 lease recovery + concurrent ticks single-send, S4a/S4b unknown reservations kept), both manager review scripts re-run VERBATIM against this head (partial: completed=[2] only, resume done with 2 entries, HTTP=2, user words actually sent; extra: new-day used=0, over-cap request refused, aged reservation second_allowed=false, uv probe still rc=2), release offline check R1-R7 green, dual-target requirement checks 4/4 with handoff-HEL-885.json; zero real LLM, 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-27 00:01:44 +08:00

261 lines
13 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)。
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()