Files
CyberGril/tools/verify_mem0_real_hel874.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

497 lines
21 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-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()