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>
This commit is contained in:
zonggong
2026-10-26 23:20:18 +08:00
co-authored by multica-agent
parent e978e878df
commit e291058754
28 changed files with 2024 additions and 161 deletions
+241
View File
@@ -0,0 +1,241 @@
#!/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()
+71 -14
View File
@@ -1,10 +1,15 @@
#!/usr/bin/env python3
"""HEL-874 · 实际固定 Mem0 SDK 合同隔离验证(零真实出站、零权威账写入)。
"""HEL-874/882 · 实际固定 Mem0 SDK 合同隔离验证(零真实出站、零真实嵌入、零权威账写入)。
在已安装的固定 mem0ai 2.2.1(2c81af3,HEL-857 hel857-venv)上,用真实
Qdrant 嵌入式向量库、真实 fastembed 本地嵌入(已有模型缓存)和 127.0.0.1
确定性假 OpenAI 网关,验证产品适配层 ``cybergril.memory.semantic.Mem0Backend``
的真实 SDK 合同:
Qdrant 嵌入式向量库、真实 OpenAI 客户端与 127.0.0.1 确定性假网关验证产品
适配层 ``cybergril.memory.semantic.Mem0Backend`` 的真实 SDK 合同。
HEL-882 边界修正(总管独立复现口径):**在 TextEmbedding 构造前**替换为
确定性 512 维向量替身(不加载任何模型、零真实嵌入推理),socket 层拒绝
一切非回环连接。本脚本历史版本(e978e87 及之前)只替换了 LLM 网关、未替换
fastembed 边界,读取缓存做过真实本地嵌入推理——勘正见
docs/rework/hel874/erratum-hel882.json;本版本起零真实模型、零真实嵌入。
C1 构造:真实 from_config + 嵌入式 qdrant 挂载(修复后不再开第二个同路径 client)。
C2 add:携带 user_id 作用域与锚点 metadata;payload 直读可回锚点。
@@ -42,15 +47,11 @@ from pathlib import Path
REPO = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO / "src"))
# 零出站:清代理、禁遥测;嵌入模型走已有本地缓存。
# 零出站:清代理、禁遥测。
for key in ("http_proxy", "https_proxy", "all_proxy", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"):
os.environ.pop(key, None)
os.environ["NO_PROXY"] = "127.0.0.1,localhost"
os.environ["MEM0_TELEMETRY"] = "False"
CACHE = Path("/home/xiaomo/multica_workspaces/hello-af23464d222e/hel-857-2cf6dc7dfc87/workdir"
"/hel857-data/fastembed-cache")
if CACHE.exists():
os.environ["FASTEMBED_CACHE_PATH"] = str(CACHE)
REPORT: dict = {"started": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}
FAILURES: list[str] = []
@@ -63,6 +64,50 @@ def check(name: str, ok: bool, detail: str = "") -> bool:
return bool(ok)
# ------------------------------------------------- HEL-882 确定性边界(先于一切构造)
def install_deterministic_boundary() -> None:
"""总管附件模式:确定性 512 维向量替身 + socket 禁非回环。
必须发生在任何 ``TextEmbedding(...)`` 构造之前——fastembed 的嵌入器在
``FastEmbedEmbedding.__init__`` 里就加载模型;事后替换只挡得住后续实例,
挡不住已发生的真实推理(e978e878 版本的真实嵌入即由此而来)。
"""
real_connect = socket.socket.connect
def connect(sock, address):
host = address[0] if isinstance(address, tuple) else str(address)
if host not in ("127.0.0.1", "::1", "localhost"):
raise AssertionError(f"verify boundary forbids non-loopback connection: {host}")
return real_connect(sock, address)
socket.socket.connect = connect
import mem0.embeddings.fastembed as embedding_module
import numpy as np
class DeterministicEmbedding:
"""sha256(text) 展开成 512 维:确定、零模型加载、逐条计数可见。"""
embedding_size = 512
calls = 0
def __init__(self, *args, **kwargs):
pass
def embed(self, texts, *args, **kwargs):
for text in ([texts] if isinstance(texts, str) else texts):
type(self).calls += 1
digest = hashlib.sha256(text.encode()).digest()
yield np.array([digest[i % 32] / 255.0 for i in range(512)], dtype=np.float32)
embedding_module.TextEmbedding = DeterministicEmbedding
REPORT["embedding_boundary"] = (
"deterministic 512-dimensional vectors installed before TextEmbedding "
"construction; no model loaded; zero real embeddings"
)
REPORT["external_network"] = "socket.connect rejects all non-loopback hosts"
# ---------------------------------------------------------------- 假 OpenAI 网关
class _Server(ThreadingHTTPServer):
daemon_threads = True
@@ -70,7 +115,7 @@ class _Server(ThreadingHTTPServer):
class FakeGateway(BaseHTTPRequestHandler):
requests: list[dict] = []
counter = {"n": 0}
counter: dict = {"n": 0}
lock = threading.Lock()
def log_message(self, *args): # silence
@@ -230,7 +275,7 @@ async def main_async() -> None:
except Exception as exc:
check("C1_construct", False, f"{type(exc).__name__}: {exc}")
REPORT["trace"] = traceback.format_exc()
finish(server)
finish(server, tmp)
return
store = Store(tmp / "product.db")
@@ -263,7 +308,8 @@ async def main_async() -> None:
except Exception as exc:
check("C2_add_anchor_payload", False, f"{type(exc).__name__}: {exc}")
# per-add real spend (verified live): phase-1 query embed + phase-3 batch
# per-add counted spend (identical under the deterministic boundary):
# phase-1 query embed + phase-3 batch
# embed of extracted texts + phase-7 entity-upsert embeds (0..N), 1 LLM call
embed_after_add = embed_used(ledger)
llm_after_add = len(FakeGateway.requests) - llm_before
@@ -386,14 +432,24 @@ async def main_async() -> None:
check("C5_llm_zero_refuses", False, f"{type(exc).__name__}: {exc}")
store.close()
finish(server)
# HEL-882: keep the accounting recoverable even though the temp dir is
# removed — the full ledger rows land in the evidence JSON.
REPORT["final_embed_rows"] = embed_rows(ledger)
REPORT["final_llm_used"] = llm_used(ledger)
finish(server, tmp)
def finish(server: _Server) -> None:
def finish(server: _Server, tmp: Path | None = None) -> None:
server.shutdown()
REPORT["finished"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
REPORT["gateway_requests_total"] = len(FakeGateway.requests)
REPORT["failures"] = FAILURES
import shutil
if tmp is not None:
REPORT["temp_dir"] = str(tmp) # recorded before cleanup for traceability
with contextlib.suppress(Exception):
shutil.rmtree(tmp, ignore_errors=True)
out = Path(sys.argv[1] if len(sys.argv) > 1 else "hel874-real-sdk-report.json")
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(REPORT, ensure_ascii=False, indent=2), encoding="utf-8")
@@ -404,6 +460,7 @@ def finish(server: _Server) -> None:
def main() -> None:
install_deterministic_boundary() # must precede every TextEmbedding construction
install_facts()
import asyncio