Files
CyberGril/spike/hel857/ledger_fake_test.py
T
zonggongandmultica-agent e31ae2d946 HEL-857: approved Mem0 isolation spike - zero-model gates all pass, A/B synthetic scenarios within 26/60 real-call budget
- Fixed mem0 source commit 2c81af3 (2.2.1) in isolated venv, qdrant embedded + fastembed local zh embeddings (95.3MB, within 500MB cap)
- Gate0 transport-level persistent debit ledger: 61st call blocked pre-send, failures count, cross-process persistence, retries disabled+counted (fake transport, zero network)
- Gate1 qdrant embedded checks: keyword_search functional (Chinese segmentation gap recorded honestly), restart subprocess, clean-copy restore, no telemetry collections
- Gate2 privacy with stub LLM: P1-P5 zero leak, first-share timing F1-F6 (failed/cancel/unconfirmed no migration, ack+judged migrates told content with anchors, duplicate receipt idempotent), full backup incl. unshared internal memories restores clean
- A/B same-material same-criteria: Mem0 paraphrase recall strictly better than current lexical path (S3, model answers in Chinese), S1-S9 all pass, no regression
- Headline findings: Chinese input extracted as English memories (default upstream prompt), BM25 lexical channel inert for Chinese, ADD-only infer confirmed with our update orchestration, custom metadata needs direct payload read
- 26/60 real outbound via persistent ledger (incl. one parse-failure retry), usage/latency per row; embeddings 28/500; HEL-835 quota untouched
- Experiment branch only: no merge to main/product, no deploy, no real-profile access; handoff JSON + dual-base requirement checks pass

Co-authored-by: multica-agent <github@multica.ai>
2026-10-25 23:19:26 +08:00

157 lines
5.9 KiB
Python

#!/usr/bin/env python3
"""门禁 0:传输层持久扣账,零网络。
用假传输证明(对照批准范围第4条):
T1 第 61 次在发送前被拦(前 60 次含失败也算数,blocked 不产生网络出站);
T2 失败请求照样扣账(fake 5xx 不回滚额度);
T3 账本跨进程/中断保留:子进程消耗额度后本进程账本可见且继承;
T4 输入超 6000 中文字符发送前拒绝(记 blocked_input,不算出站);
T5 openai client 自动重试显式关闭(max_retries=0),传输层仍逐尝试计数。
"""
from __future__ import annotations
import json
import subprocess
import sys
from pathlib import Path
import httpx
from .common import INPUT_CJK_CAP, LLM_CALL_CAP, write_result
from .ledger import AccountingTransport, BudgetBlocked, FakeTransport, Ledger
def _fresh_ledger(path: Path) -> Ledger:
if path.exists():
path.unlink()
for suffix in ("-wal", "-shm"):
p = Path(str(path) + suffix)
if p.exists():
p.unlink()
return Ledger(path)
def run(tmp: Path) -> dict:
results = {}
led_path = tmp / "ledger_t.sqlite3"
# T1+T2: 60 次上限,其中前 3 次 fake 5xx(失败也计数),第 61 次发送前被拦
led = _fresh_ledger(led_path)
fake = FakeTransport(status=200, fail_first=3)
tr = AccountingTransport(fake, led)
client = httpx.Client(transport=tr, base_url="http://fake.invalid")
blocked_at = None
t1e = None
sent = failed = 0
for i in range(1, 70):
try:
client.post("/v1/chat/completions", json={"messages": [{"role": "user", "content": f"测试{i}"}]})
sent += 1
except BudgetBlocked as e:
blocked_at = i
t1e = str(e)
break
failed_rows = led.rows()
failed = sum(1 for r in failed_rows if r["status"] == "failed")
sent_rows = sum(1 for r in failed_rows if r["status"] == "sent")
results["T1_61st_blocked_before_send"] = {
"attempt_blocked_at": blocked_at,
"message": t1e,
"sent": sent_rows,
"failed(fake5xx)": failed,
"fake_transport_attempts": fake.attempts,
"expect": f"第 {LLM_CALL_CAP + 1} 次发送前被拦;假传输仅收到 {LLM_CALL_CAP} 次尝试",
"pass": blocked_at == LLM_CALL_CAP + 1 and fake.attempts == LLM_CALL_CAP
and sent_rows + failed == LLM_CALL_CAP,
}
results["T2_failures_count"] = {
"failed_debited": failed,
"expect": "fake 5xx 的 3 次失败照样扣账,不回滚额度",
"pass": failed == 3,
}
led_summary_before = led.summary()
# T3: 跨进程。子进程再试 1 次 → 应被拦(60 已用完);账本继承自本进程写入。
child = subprocess.run(
[sys.executable, "-m", "spike.hel857.ledger_child", str(led_path)],
capture_output=True, text=True, cwd=str(Path(__file__).resolve().parents[2]),
)
child_out = {}
try:
child_out = json.loads(child.stdout)
except Exception:
child_out = {"stdout": child.stdout, "stderr": child.stderr, "returncode": child.returncode}
led2 = Ledger(led_path)
results["T3_cross_process"] = {
"child": child_out,
"parent_used_before_child": led_summary_before["debited"],
"ledger_after_child_used": led2.used(),
"expect": "子进程读取同一账本:60 已耗尽 → 其请求在发送前被拦,无新增出站",
"pass": bool(child_out.get("blocked")) and led2.used() == LLM_CALL_CAP
and child_out.get("fake_attempts") == 0,
}
# T4: 输入超限发送前拒绝
led_path4 = tmp / "ledger_t4.sqlite3"
led4 = _fresh_ledger(led_path4)
fake4 = FakeTransport()
tr4 = AccountingTransport(fake4, led4)
client4 = httpx.Client(transport=tr4, base_url="http://fake.invalid")
big = "字" * (INPUT_CJK_CAP + 1)
blocked_input = False
try:
client4.post("/v1/chat/completions", json={"messages": [{"role": "user", "content": big}]})
except BudgetBlocked:
blocked_input = True
rows4 = led4.rows()
results["T4_input_cap"] = {
"blocked_before_send": blocked_input,
"fake_attempts": fake4.attempts,
"rows": [(r["status"], r["cjk_chars"]) for r in rows4],
"expect": f"输入 {INPUT_CJK_CAP + 1} 中文字符 → 发送前拒绝;不计出站、不占真实额度",
"pass": blocked_input and fake4.attempts == 0
and any(r["status"] == "blocked_input" for r in rows4),
}
# T5: openai client 自动重试显式关闭
from openai import OpenAI
led_path5 = tmp / "ledger_t5.sqlite3"
led5 = _fresh_ledger(led_path5)
fake5 = FakeTransport(status=500)
tr5 = AccountingTransport(fake5, led5)
oc = OpenAI(api_key="x", base_url="http://fake.invalid/v1", max_retries=0,
http_client=httpx.Client(transport=tr5))
api_err = None
try:
oc.chat.completions.create(model="m", messages=[{"role": "user", "content": "重试测试"}])
except Exception as e:
api_err = type(e).__name__
results["T5_retry_disabled"] = {
"client_max_retries": oc.max_retries,
"error": api_err,
"transport_attempts": fake5.attempts,
"ledger_debited": led5.used(),
"expect": "max_retries=0:一次调用=一次出站尝试=一次扣账,无隐藏重试",
"pass": oc.max_retries == 0 and fake5.attempts == 1 and led5.used() == 1,
}
ok = all(v.get("pass") for v in results.values())
return {
"ok": ok,
"network_outbound": 0,
"results": results,
"ledger_summary_t1": {k: v for k, v in led_summary_before.items() if k != "rows"},
}
def main(argv: list[str]) -> dict:
import tempfile
with tempfile.TemporaryDirectory() as td:
out = run(Path(td))
write_result("gate0_ledger.json", out)
return out
if __name__ == "__main__":
raise SystemExit(0 if main([])["ok"] else 1)