497 lines
21 KiB
Python
497 lines
21 KiB
Python
#!/usr/bin/env python3
|
||
"""HEL-874/882 · 实际固定 Mem0 SDK 合同隔离验证(零真实出站、零真实嵌入、零权威账写入)。
|
||
|
||
在已安装的固定 mem0ai 2.2.1(2c81af3,HEL-857 hel857-venv)上,用真实
|
||
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 直读可回锚点。
|
||
C3 默认提取的输入集:第二批 add 的提取提示包含第一批的提取记忆(旧记忆)
|
||
与滚动 history——全部只来自此前过门批次;未分享 canary 永不出现。
|
||
C4 search:必须带 user_id 过滤(2.2.1 对无过滤 search 直接 ValueError);
|
||
每次恰好 1 条嵌入记账(旧实现外层+包装双记)。
|
||
C5 预算闸:embed_cap=0 / llm_cap=0 在任何真实工作前拒绝(LLM 服务器零请求)。
|
||
C6 并发:并行 search 预占不越过 cap。
|
||
C7 关闭恢复:aclose 后同一目录重建,数据与锚点仍在。
|
||
|
||
证据 JSON 写入 argv[1]。运行(在仓库根,用固定 venv):
|
||
|
||
/path/to/hel857-venv/bin/python tools/verify_mem0_real_hel874.py out.json
|
||
|
||
本脚本对修复前(31970c4)与修复后代码均可运行:修复前行为按异常如实记录,
|
||
供前后对照。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import contextlib
|
||
import hashlib
|
||
import json
|
||
import os
|
||
import socket
|
||
import sqlite3
|
||
import sys
|
||
import tempfile
|
||
import threading
|
||
import time
|
||
import traceback
|
||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||
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"
|
||
|
||
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}")
|
||
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
|
||
|
||
|
||
class FakeGateway(BaseHTTPRequestHandler):
|
||
requests: list[dict] = []
|
||
counter: dict = {"n": 0}
|
||
lock = threading.Lock()
|
||
|
||
def log_message(self, *args): # silence
|
||
pass
|
||
|
||
def do_POST(self): # noqa: N802 — http.server contract
|
||
length = int(self.headers.get("content-length") or 0)
|
||
body = self.rfile.read(length).decode("utf-8", "replace")
|
||
with FakeGateway.lock:
|
||
FakeGateway.counter["n"] += 1
|
||
FakeGateway.requests.append({
|
||
"n": FakeGateway.counter["n"], "path": self.path, "body": body,
|
||
})
|
||
memory_text = f"合成提取记忆HEL874-{FakeGateway.counter['n']}"
|
||
completion = {
|
||
"id": f"chatcmpl-hel874-{FakeGateway.counter['n']}",
|
||
"object": "chat.completion",
|
||
"created": int(time.time()),
|
||
"model": "hel874-deterministic",
|
||
"choices": [{
|
||
"index": 0,
|
||
"message": {"role": "assistant",
|
||
"content": json.dumps({"memory": [{"text": memory_text, "event": "ADD"}]},
|
||
ensure_ascii=False)},
|
||
"finish_reason": "stop",
|
||
}],
|
||
"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
|
||
}
|
||
payload = json.dumps(completion).encode()
|
||
self.send_response(200)
|
||
self.send_header("content-type", "application/json")
|
||
self.send_header("content-length", str(len(payload)))
|
||
self.end_headers()
|
||
self.wfile.write(payload)
|
||
|
||
|
||
def start_gateway() -> _Server:
|
||
with socket.socket() as probe:
|
||
probe.bind(("127.0.0.1", 0))
|
||
port = probe.getsockname()[1]
|
||
server = _Server(("127.0.0.1", port), FakeGateway)
|
||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||
return server
|
||
|
||
|
||
def last_prompt() -> str:
|
||
req = FakeGateway.requests[-1]
|
||
try:
|
||
return json.loads(req["body"])["messages"][-1]["content"]
|
||
except Exception:
|
||
return req["body"]
|
||
|
||
|
||
def install_facts() -> None:
|
||
import importlib.metadata as md
|
||
|
||
facts = {"python": sys.version.split()[0]}
|
||
for pkg in ("mem0ai", "qdrant-client", "fastembed"):
|
||
try:
|
||
facts[pkg] = md.version(pkg)
|
||
except Exception as exc: # pragma: no cover
|
||
facts[pkg] = f"ERR {exc}"
|
||
import mem0
|
||
|
||
facts["mem0_path"] = str(Path(mem0.__file__).parent)
|
||
digests = {}
|
||
for rel in ("memory/main.py", "memory/storage.py", "embeddings/fastembed.py",
|
||
"llms/openai.py", "vector_stores/qdrant.py"):
|
||
path = Path(mem0.__file__).parent / rel
|
||
if path.exists():
|
||
digests[rel] = hashlib.sha256(path.read_bytes()).hexdigest()
|
||
facts["module_sha256"] = digests
|
||
tarball = Path("/home/xiaomo/multica_workspaces/hello-af23464d222e/hel-857-2cf6dc7dfc87"
|
||
"/workdir/hel857-data/mem0-2c81af3.tar.gz")
|
||
if tarball.exists():
|
||
facts["source_tarball_sha256"] = hashlib.sha256(tarball.read_bytes()).hexdigest()
|
||
REPORT["install"] = facts
|
||
|
||
|
||
def make_ledger(path: Path, cap: int, llm_cap: int) -> None:
|
||
"""Temp ledger + SYNTHETIC authority prefix row (HEL-885).
|
||
|
||
The seeded row is an uncounted kind with 0 items (guard ``used()`` stays
|
||
0); it exists because the product now REFUSES any positive cap without an
|
||
explicit authority block — test/verify harnesses hand it a synthetic one
|
||
over this prefix, never relaxing the production default.
|
||
"""
|
||
conn = sqlite3.connect(str(path))
|
||
with conn:
|
||
conn.execute("CREATE TABLE IF NOT EXISTS embed_ops (id INTEGER PRIMARY KEY AUTOINCREMENT,"
|
||
" ts TEXT, pid INTEGER, kind TEXT, items INTEGER, note TEXT)")
|
||
conn.execute("CREATE TABLE IF NOT EXISTS llm_ops (id INTEGER PRIMARY KEY AUTOINCREMENT,"
|
||
" ts TEXT, pid INTEGER, kind TEXT, items INTEGER, note TEXT)")
|
||
if conn.execute("SELECT count(*) FROM embed_ops").fetchone()[0] == 0:
|
||
conn.execute(
|
||
"INSERT INTO embed_ops(ts,pid,kind,items,note) VALUES"
|
||
"('2026-01-01T00:00:00Z',1,'authority_prefix',0,'authority:synthetic-verify-prefix')")
|
||
conn.close()
|
||
path.with_name(path.name + ".meta").write_text(
|
||
json.dumps({"embed_cap": cap, "llm_cap": llm_cap}), encoding="utf-8")
|
||
|
||
|
||
def synthetic_authority(ledger: Path, *, prefix_rows: int = 1, min_used: int = 0) -> dict:
|
||
rows = sqlite3.connect(str(ledger)).execute(
|
||
"SELECT ts,pid,kind,items,note FROM embed_ops ORDER BY id LIMIT ?",
|
||
(prefix_rows,)).fetchall()
|
||
digest = hashlib.sha256(
|
||
"\n".join("|".join(str(c) for c in row) for row in rows).encode()).hexdigest()
|
||
return {"prefix_rows": prefix_rows, "prefix_sha256": digest, "min_used": min_used}
|
||
|
||
|
||
def embed_used(path: Path) -> int:
|
||
conn = sqlite3.connect(str(path))
|
||
try:
|
||
row = conn.execute("SELECT coalesce(sum(items),0) FROM embed_ops").fetchone()
|
||
return int(row[0] or 0)
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def embed_rows(path: Path) -> list[dict]:
|
||
conn = sqlite3.connect(str(path))
|
||
try:
|
||
return [{"kind": r[0], "items": r[1], "note": r[2]}
|
||
for r in conn.execute("SELECT kind,items,note FROM embed_ops ORDER BY id")]
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def llm_used(path: Path) -> int:
|
||
conn = sqlite3.connect(str(path))
|
||
try:
|
||
row = conn.execute("SELECT coalesce(sum(items),0) FROM llm_ops").fetchone()
|
||
return int(row[0] or 0)
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def config_for(tmp: Path, ledger: Path, *, port: int, cap: int, llm_cap: int) -> dict:
|
||
config = {
|
||
"gateway_base_url": f"http://127.0.0.1:{port}/v1",
|
||
"gateway_model": "hel874-deterministic",
|
||
"gateway_key": "hel874-local-test",
|
||
"vector_root": str(tmp / "vec"),
|
||
"history_root": str(tmp / "hist"),
|
||
"collection": "cg_hel874",
|
||
"ledger_path": str(ledger),
|
||
"embed_cap": cap,
|
||
"llm_cap": llm_cap,
|
||
}
|
||
if cap > 0 or llm_cap > 0:
|
||
# HEL-885: positive caps require the explicit (synthetic) authority —
|
||
# the production default refuses without one.
|
||
config["authority"] = synthetic_authority(ledger)
|
||
return config
|
||
|
||
|
||
async def main_async() -> None:
|
||
from cybergril.memory.semantic import Mem0Backend, SemanticMemory
|
||
from cybergril.memory.store import Store
|
||
|
||
tmp = Path(tempfile.mkdtemp(prefix="hel874-real-sdk-"))
|
||
ledger = tmp / "ledger.sqlite3"
|
||
make_ledger(ledger, cap=64, llm_cap=32)
|
||
server = start_gateway()
|
||
port = server.server_address[1]
|
||
|
||
import cybergril.memory.semantic as sem_mod
|
||
|
||
REPORT["adapter_has_llm_guard"] = hasattr(sem_mod, "LlmLedgerGuard")
|
||
|
||
# ---- C1 construct --------------------------------------------------
|
||
backend = None
|
||
try:
|
||
backend = Mem0Backend(config_for(tmp, ledger, port=port, cap=64, llm_cap=32))
|
||
if hasattr(backend, "_memory") and hasattr(backend._memory, "vector_store") \
|
||
and getattr(backend, "_client", None) is backend._memory.vector_store.client:
|
||
single_client = "sdk-vector-store-client"
|
||
else:
|
||
single_client = "second-standalone-client"
|
||
check("C1_construct", True, f"client_path={single_client}")
|
||
except Exception as exc:
|
||
check("C1_construct", False, f"{type(exc).__name__}: {exc}")
|
||
REPORT["trace"] = traceback.format_exc()
|
||
finish(server, tmp)
|
||
return
|
||
|
||
store = Store(tmp / "product.db")
|
||
|
||
def public_turn(turn_id: str, user_text: str, ts: int) -> list[dict]:
|
||
with store.conn:
|
||
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES"
|
||
"(?,'user',?,?,'sent')", (ts, user_text, turn_id))
|
||
row = store.query_one("SELECT id FROM chat_message WHERE turn_id=?", (turn_id,))
|
||
return [{"message_id": row["id"], "turn_id": turn_id, "role": "user", "text": user_text}]
|
||
|
||
anchor_for = sem_mod.anchor_fingerprint
|
||
|
||
# ---- C2 add with anchors + scope ------------------------------------
|
||
rows1 = public_turn("t1", "家里的备用钥匙藏在阳台第三个花盆下面", 1_763_000_000_000)
|
||
anchor1 = {"turn_ids": ["t1"], "turn_roles": [["t1", "user", rows1[0]["message_id"]]],
|
||
"input_sha256": anchor_for(rows1)}
|
||
llm_before = len(FakeGateway.requests)
|
||
try:
|
||
created1 = await backend.add_group(rows1, anchor1, "chat_public:t1:a1")
|
||
ok = bool(created1) and created1[0]["id"]
|
||
payload = backend.payload(created1[0]["id"]) or {}
|
||
ok = ok and payload.get("turn_roles") == anchor1["turn_roles"] \
|
||
and payload.get("input_sha256") == anchor1["input_sha256"] \
|
||
and payload.get("src_group") == "chat_public:t1:a1"
|
||
scoped = "user_id" in payload or "cybergril" in json.dumps(payload)
|
||
check("C2_add_anchor_payload", ok, f"created={bool(created1)} payload_keys={sorted(payload)[:8]}")
|
||
check("C2_add_user_scope", scoped, "user_id present in stored payload" if scoped
|
||
else "no user scope in payload (pre-fix behavior)")
|
||
except Exception as exc:
|
||
check("C2_add_anchor_payload", False, f"{type(exc).__name__}: {exc}")
|
||
|
||
# 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
|
||
REPORT["embed_rows_after_first_add"] = embed_rows(ledger)
|
||
check("C2_add_ledger_shape", 2 <= embed_after_add <= 4 and llm_after_add == 1,
|
||
f"embed_items={embed_after_add} llm_calls={llm_after_add}")
|
||
|
||
# ---- C3 default extraction input set --------------------------------
|
||
rows2 = public_turn("t2", "周末想一起去旧书店逛一圈", 1_763_000_100_000)
|
||
anchor2 = {"turn_ids": ["t2"], "turn_roles": [["t2", "user", rows2[0]["message_id"]]],
|
||
"input_sha256": anchor_for(rows2)}
|
||
try:
|
||
await backend.add_group(rows2, anchor2, "chat_public:t2:a2")
|
||
prompt = last_prompt()
|
||
old_memory_seen = "合成提取记忆HEL874-1" in prompt
|
||
new_row_seen = "旧书店" in prompt
|
||
history_seen = "花盆" in prompt # rolling history carries batch 1's raw message
|
||
check("C3_extraction_input_set", old_memory_seen and new_row_seen,
|
||
f"old_memory={old_memory_seen} new_row={new_row_seen} history_carry={history_seen}")
|
||
except Exception as exc:
|
||
check("C3_extraction_input_set", False, f"{type(exc).__name__}: {exc}")
|
||
|
||
# ---- C3b unshared canary never leaves --------------------------------
|
||
canary = "她私藏的紫铜风铃HEL874绝不外传"
|
||
with store.conn:
|
||
store.execute("INSERT INTO chat_message(ts,role,text,turn_id,status) VALUES"
|
||
"(?,'companion',?,?,'sent')", (1_763_000_200_000, canary, "t3"))
|
||
semantic = SemanticMemory(store, backend)
|
||
queued = semantic.enqueue_uncovered() # only public rows batch
|
||
gate_calls = len(FakeGateway.requests)
|
||
await semantic.tick()
|
||
prompts_since = [r["body"] for r in FakeGateway.requests[gate_calls:]]
|
||
leaked = any(canary in body for body in prompts_since)
|
||
batch = store.query_one("SELECT * FROM sem_batch WHERE batch_key LIKE '%t3%'")
|
||
companion_in_anchor = False
|
||
if batch:
|
||
companion_in_anchor = canary in batch["anchor_json"]
|
||
check("C3b_unshared_canary_never_outbound", (not leaked) and (not companion_in_anchor),
|
||
f"queued_public_batches={queued} leaked={leaked} anchor_taint={companion_in_anchor}")
|
||
|
||
# ---- C4 search: filters + single accounting --------------------------
|
||
embed_before_search = embed_used(ledger)
|
||
try:
|
||
hits = await backend.search("合成提取记忆", limit=4)
|
||
delta = embed_used(ledger) - embed_before_search
|
||
check("C4_search_filters", bool(hits), f"hits={len(hits)}")
|
||
check("C4_search_single_debit", delta == 1, f"embed_delta={delta} (pre-fix=2)")
|
||
except Exception as exc:
|
||
check("C4_search_filters", False, f"{type(exc).__name__}: {exc}")
|
||
check("C4_search_single_debit", False, "search raised")
|
||
|
||
# ---- C6 concurrency cannot overshoot ---------------------------------
|
||
# own vector roots: a second Memory on the SAME local path is rejected by
|
||
# qdrant's file lock (that is the C1 before-evidence, not this check)
|
||
cap_tmp = tmp / "conc-ledger.sqlite3"
|
||
make_ledger(cap_tmp, cap=3, llm_cap=3)
|
||
conc_cfg = config_for(tmp, cap_tmp, port=port, cap=3, llm_cap=3)
|
||
conc_cfg["vector_root"] = str(tmp / "vec-conc")
|
||
conc_cfg["history_root"] = str(tmp / "hist-conc")
|
||
conc_backend = Mem0Backend(conc_cfg)
|
||
import asyncio
|
||
|
||
async def one(i: int):
|
||
try:
|
||
await conc_backend.search(f"查询{i}")
|
||
return "ok"
|
||
except RuntimeError:
|
||
return "refused"
|
||
except Exception as exc: # pre-fix ValueError path
|
||
return f"err:{type(exc).__name__}"
|
||
|
||
outcomes = await asyncio.gather(*(one(i) for i in range(8)))
|
||
used_after = embed_used(cap_tmp)
|
||
check("C6_concurrency_cap", used_after <= 3,
|
||
f"outcomes={sorted(set(outcomes))} used={used_after} cap=3")
|
||
with contextlib.suppress(Exception):
|
||
await conc_backend.aclose()
|
||
|
||
# ---- C7 shutdown / reopen --------------------------------------------
|
||
await backend.aclose()
|
||
try:
|
||
reopened = Mem0Backend(config_for(tmp, ledger, port=port, cap=64, llm_cap=32))
|
||
hits2 = await reopened.search("合成提取记忆", limit=4)
|
||
check("C7_reopen_after_close", bool(hits2), f"hits_after_reopen={len(hits2)}")
|
||
await reopened.aclose()
|
||
except Exception as exc:
|
||
check("C7_reopen_after_close", False, f"{type(exc).__name__}: {exc}")
|
||
|
||
# ---- C5 zero budgets refuse BEFORE any real work ----------------------
|
||
cap0 = tmp / "cap0-ledger.sqlite3"
|
||
make_ledger(cap0, cap=0, llm_cap=0)
|
||
try:
|
||
zero = Mem0Backend(config_for(tmp, cap0, port=port, cap=0, llm_cap=0))
|
||
requests_before = len(FakeGateway.requests)
|
||
try:
|
||
await zero.add_group(rows1, anchor1, "cap0")
|
||
check("C5_embed_zero_refuses", False, "add succeeded with embed_cap=0")
|
||
except RuntimeError as exc:
|
||
llm_sent = len(FakeGateway.requests) - requests_before
|
||
check("C5_embed_zero_refuses", "embed" in str(exc) and llm_sent == 0,
|
||
f"err={exc} llm_sent={llm_sent}")
|
||
await zero.aclose()
|
||
except Exception as exc:
|
||
check("C5_embed_zero_refuses", False, f"{type(exc).__name__}: {exc}")
|
||
|
||
llm0 = tmp / "llm0-ledger.sqlite3"
|
||
make_ledger(llm0, cap=64, llm_cap=0)
|
||
try:
|
||
zero_llm = Mem0Backend(config_for(tmp, llm0, port=port, cap=64, llm_cap=0))
|
||
requests_before = len(FakeGateway.requests)
|
||
try:
|
||
await zero_llm.add_group(rows1, anchor1, "llm0")
|
||
check("C5_llm_zero_refuses", False, "add succeeded with llm_cap=0")
|
||
except RuntimeError as exc:
|
||
llm_sent = len(FakeGateway.requests) - requests_before
|
||
check("C5_llm_zero_refuses", "llm" in str(exc) and llm_sent == 0,
|
||
f"err={exc} llm_sent={llm_sent}")
|
||
await zero_llm.aclose()
|
||
except Exception as exc:
|
||
check("C5_llm_zero_refuses", False, f"{type(exc).__name__}: {exc}")
|
||
|
||
store.close()
|
||
# 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, 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")
|
||
print(json.dumps({"out": str(out), "failures": FAILURES,
|
||
"checks": {c["name"]: c["ok"] for c in REPORT.get("checks", [])}},
|
||
ensure_ascii=False, indent=2))
|
||
sys.exit(1 if FAILURES else 0)
|
||
|
||
|
||
def main() -> None:
|
||
install_deterministic_boundary() # must precede every TextEmbedding construction
|
||
install_facts()
|
||
import asyncio
|
||
|
||
asyncio.run(main_async())
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|