296 lines
16 KiB
Python
296 lines
16 KiB
Python
#!/usr/bin/env python3
|
||
"""HEL-869 补证:原话滚动窗口独立重现 + 报告勘误事实核对。
|
||
|
||
依据 HEL-869 任务卡(总管对 81d50f2 的《HEL-868-独立复核》确认后的只读补证):
|
||
1. 用固定 Mem0 storage 源码在独立内存 SQLite 重现"每次写入后仅保留最近 10 条"
|
||
的滚动窗口(零 LLM、零嵌入、全新合成消息,不依赖夹具);
|
||
2. 只读核对本轮真实数据:Mem0 messages 表 10 条、缺 t3 双角色/t4 双角色/t5 用户
|
||
共 5 条,恢复库同 10 条;现状主档案 baseline.sqlite3 chat_message 15 条逐字
|
||
逐角色完整;原始 calls 输入仍含全部 15 条——SDK 滚动窗口 ≠ 永久原话档案,
|
||
不声称真实用户资料丢失;
|
||
3. 勘误事实核对:本轮 13 次用量 46004(44735+1269)/累计 39 次 163041;原始
|
||
QA6–13 顺序对应方案 QA1–8;calls headline"答出蓝色"为旧说明、本轮答不知道;
|
||
进程内 llm_calls_real=0/嵌入 39 不能替代持久账 13 真实/40 嵌入;S9 本轮只
|
||
重新验证公开实例,完整私密恢复证据复用 gate2。
|
||
|
||
边界:零网络(socket 硬拒绝+HF 离线)、零模型请求、零本地嵌入;原账/续账/嵌入账
|
||
与全部既有结果文件只读(mode=ro / git blob 比对),新证据独立命名,不覆盖历史。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import importlib.util
|
||
import json
|
||
import os
|
||
import socket
|
||
import sqlite3
|
||
import subprocess
|
||
import sys
|
||
from datetime import datetime, timezone
|
||
from pathlib import Path
|
||
|
||
REPO = Path(__file__).resolve().parents[2]
|
||
RESULTS = REPO / "spike/hel857/results"
|
||
FAMILY = Path(os.environ.get("HEL869_FAMILY", REPO.parents[2]))
|
||
OUT = RESULTS / "recheck_HEL-869_rawretention.json"
|
||
|
||
os.environ.setdefault("HF_HUB_OFFLINE", "1")
|
||
os.environ.setdefault("TRANSFORMERS_OFFLINE", "1")
|
||
os.environ.setdefault("MEM0_TELEMETRY", "False")
|
||
|
||
|
||
def deny(*args, **kwargs):
|
||
raise RuntimeError("HEL-869 recheck forbids all network")
|
||
|
||
|
||
socket.socket.connect = deny
|
||
socket.socket.connect_ex = deny
|
||
sys.path.insert(0, str(REPO))
|
||
from spike.hel857 import fixtures as FX # noqa: E402
|
||
|
||
|
||
def now_iso() -> str:
|
||
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||
|
||
|
||
def read_json(p):
|
||
return json.loads(Path(p).read_text(encoding="utf-8"))
|
||
|
||
|
||
def digest(rows) -> str:
|
||
return hashlib.sha256(json.dumps(rows, ensure_ascii=False).encode()).hexdigest()
|
||
|
||
|
||
def table_rows(p, table, order="id"):
|
||
with sqlite3.connect(f"file:{p}?mode=ro", uri=True) as c:
|
||
return c.execute(f"SELECT * FROM {table} ORDER BY {order}").fetchall()
|
||
|
||
|
||
def git(*args) -> str:
|
||
return subprocess.check_output(["git", *args], cwd=str(REPO), text=True).strip()
|
||
|
||
|
||
checks: dict[str, bool] = {}
|
||
|
||
|
||
def check(key: str, value) -> None:
|
||
checks[key] = bool(value)
|
||
|
||
|
||
def main() -> int:
|
||
calls = read_json(RESULTS / "retest_HEL-868_calls.json")
|
||
data = Path(calls["env"]["HEL857_DATA"]) / "ab"
|
||
original_path = FAMILY / "hel-857-2cf6dc7dfc87/workdir/hel857-data/ledger.sqlite3"
|
||
continued_path = Path(calls["env"]["HEL857_LEDGER"])
|
||
embed_path = Path(calls["env"]["HEL857_EMBED_LEDGER"])
|
||
storage_source = FAMILY / "hel-857-2cf6dc7dfc87/workdir/hel857-src/mem0/memory/storage.py"
|
||
|
||
before = {
|
||
"original": digest(table_rows(original_path, "outbound")),
|
||
"continued": digest(table_rows(continued_path, "outbound")),
|
||
"embed": digest(table_rows(embed_path, "embed_ops")),
|
||
}
|
||
check("ledger_digests_match_review",
|
||
before == {"original": "03f92557972ccfaa51d5a1ba8d0e6a97a5a1cc36e637c0cd01fd545bb0af8f47",
|
||
"continued": "c987127765729f1f9c24f67d416f61ea5a8d333c0de7f25336d5267279dffadd",
|
||
"embed": "9716c722688da1cc04b655e31e6b6be49efca1906d608f69f73534392c4d30b9"})
|
||
|
||
# ---- 1a. 上游滚动窗口独立重现(全新合成消息,单批 15 条) ----
|
||
src_text = storage_source.read_text(encoding="utf-8")
|
||
spec = importlib.util.spec_from_file_location("recheck869_mem0_storage", storage_source)
|
||
storage = importlib.util.module_from_spec(spec)
|
||
spec.loader.exec_module(storage)
|
||
check("storage_source_limit10", "LIMIT 10" in src_text)
|
||
one_batch = [f"HEL-869独立合成原话-{i}" for i in range(15)]
|
||
stub = storage.SQLiteManager(":memory:")
|
||
stub.save_messages([{"role": "user", "content": t} for t in one_batch], "recheck-one")
|
||
kept_one = [r[0] for r in stub.connection.execute(
|
||
"SELECT content FROM messages").fetchall()]
|
||
# 单批 15 条同时间戳:同批内并列键的取舍顺序属 SQLite 实现细节,此处只断言
|
||
# "一次写入即被截到 10 条、丢失 5 条且全部来自本批";结构方向由下方按真实
|
||
# add 批次(9,1,1,2,2)的复现断言(保留批1前4条、缺批1后5条)与本轮真实
|
||
# messages 表缺失清单交叉印证。
|
||
check("one_batch_15_keeps_10",
|
||
len(kept_one) == 10 and set(one_batch).issuperset(kept_one)
|
||
and (set(one_batch) - set(kept_one)) and len(set(one_batch) - set(kept_one)) == 5)
|
||
# ---- 1b. 按本轮真实 add 批次结构(9,1,1,2,2)重现:保留批1前4条+后6条,缺批1后5条 ----
|
||
stub2 = storage.SQLiteManager(":memory:")
|
||
pattern = [9, 1, 1, 2, 2]
|
||
seq = 0
|
||
for n in pattern:
|
||
batch = [f"HEL-869独立合成批次消息-{seq + i}" for i in range(n)]
|
||
seq += n
|
||
stub2.save_messages([{"role": "user", "content": t} for t in batch], "recheck-real")
|
||
kept_two = {r[0] for r in stub2.connection.execute(
|
||
"SELECT content FROM messages").fetchall()}
|
||
synth = [f"HEL-869独立合成批次消息-{i}" for i in range(15)]
|
||
expect_kept = set(synth[:4]) | set(synth[9:]) # 批1前4条 + 批2–5全部
|
||
expect_dropped = set(synth[4:9]) # 批1后5条(同时间戳并列按行序保留前4)
|
||
check("real_pattern_keeps_10_first4_plus_later",
|
||
len(kept_two) == 10 and kept_two == expect_kept and expect_dropped.isdisjoint(kept_two))
|
||
stub.connection.close()
|
||
stub2.connection.close()
|
||
|
||
# ---- 2. 本轮真实数据只读核对 ----
|
||
fixture_rows = FX.PUBLIC_CORPUS + FX.CORRECTION_PAIR + FX.FACT_FEELING_PAIR + FX.PROMISE_PAIR
|
||
with sqlite3.connect(f'file:{data / "mem0/mem0_public_history.db"}?mode=ro', uri=True) as c:
|
||
stored = [r[0] for r in c.execute("SELECT content FROM messages").fetchall()]
|
||
missing = [{"turn": t, "role": r, "raw": text}
|
||
for t, r, text in fixture_rows if text not in stored]
|
||
missing_target = {(m["turn"], m["role"]) for m in missing}
|
||
check("mem0_messages_10_missing_5",
|
||
len(stored) == 10 and missing_target == {("t3", "user"), ("t3", "companion"),
|
||
("t4", "user"), ("t4", "companion"),
|
||
("t5", "user")})
|
||
with sqlite3.connect(f'file:{data / "restore_public/mem0_public_history.db"}?mode=ro', uri=True) as c:
|
||
restored = [r[0] for r in c.execute("SELECT content FROM messages").fetchall()]
|
||
check("restore_public_same_10", sorted(restored) == sorted(stored))
|
||
with sqlite3.connect(f'file:{data / "baseline.sqlite3"}?mode=ro', uri=True) as c:
|
||
baseline = set(c.execute("SELECT turn_id,role,text FROM chat_message").fetchall())
|
||
check("baseline_chat_message_all_15", baseline == set(fixture_rows))
|
||
add_inputs = [m["content"] for r in calls["raw_calls"] if r["kind"] == "add"
|
||
for m in r["messages"]]
|
||
check("calls_add_inputs_have_all_15",
|
||
all(text in add_inputs for _, _, text in fixture_rows))
|
||
|
||
# ---- 3. 勘误事实核对 ----
|
||
# 3a. 用量口径:本轮 13 次 46004(44735+1269);累计 39 次 163041
|
||
with sqlite3.connect(f"file:{continued_path}?mode=ro", uri=True) as c:
|
||
c.row_factory = sqlite3.Row
|
||
new_rows = [dict(r) for r in c.execute(
|
||
"SELECT * FROM outbound WHERE id>26 ORDER BY id").fetchall()]
|
||
usage = {k: sum(json.loads(r["usage_json"])[k] for r in new_rows)
|
||
for k in ("prompt_tokens", "completion_tokens", "total_tokens")}
|
||
after_totals = calls["after"]["real_ledger"]["usage_totals"]
|
||
check("usage_this_round_46004", usage == {"prompt_tokens": 44735,
|
||
"completion_tokens": 1269,
|
||
"total_tokens": 46004})
|
||
check("usage_cumulative_163041",
|
||
after_totals == {"prompt_tokens": 158918, "completion_tokens": 4123,
|
||
"total_tokens": 163041}
|
||
and all(after_totals[k] - calls["before"]["real_ledger"]["usage_totals"][k]
|
||
== usage[k] for k in usage))
|
||
# 3b. QA 编号映射:原始 QA6–13 顺序对应方案 QA1–8
|
||
asks = [r for r in calls["raw_calls"] if r["kind"] == "ask"]
|
||
plan = read_json(RESULTS / "rework860_offline.json")["_retest_plan"]
|
||
plan_qa = plan["estimated_real_calls"]["model_use_qa"]
|
||
check("qa_labels_6_to_13",
|
||
[r["call"] for r in asks] == [f"QA{n}" for n in range(6, 14)])
|
||
check("qa_map_plan_1_to_8",
|
||
[q["no"] for q in plan_qa] == [f"QA{n}" for n in range(1, 9)]
|
||
and plan["estimated_real_calls"]["total"] == 13
|
||
and [q["scenario"] for q in plan_qa]
|
||
== ["S2", "S2", "S2", "S3", "S3", "S4", "S6", "S6"])
|
||
# 3c. headline"答出蓝色"为旧说明:本轮 S3 Mem0 实答"不知道。"
|
||
headline = calls["outcome"]["headline_findings"]["extraction_language"]
|
||
s3_mem0_answer = [r for r in calls["raw_calls"]
|
||
if r["kind"] == "ask_result"][4]["answer"]
|
||
check("headline_stale_s3_answered_unknown",
|
||
("蓝色" in headline and "答出" in headline)
|
||
and s3_mem0_answer == "不知道。"
|
||
and "蓝色" not in s3_mem0_answer
|
||
and "蓝色" not in asks[4]["sent_context"])
|
||
# 3d. 进程内计数 ≠ 持久账:llm_calls_real=0/嵌入39 vs 账本 13 真实/40 嵌入
|
||
counters = calls["counters"]
|
||
embeds = table_rows(embed_path, "embed_ops")
|
||
dense_new = sum(r[4] for r in embeds[181:] if r[3] in ("dense", "entity"))
|
||
check("counters_not_authoritative_vs_ledger",
|
||
counters["llm_calls_real"] == 0
|
||
and len(new_rows) == 13
|
||
and all(r["status"] == "sent" and r["http_status"] == 200 for r in new_rows)
|
||
and counters["embed_items_dense"] == 39 and dense_new == 40)
|
||
# 3e. S9 本轮只重新验证公开实例;完整私密恢复证据复用 gate2
|
||
s9 = read_json(RESULTS / "retest_HEL-868_S9.json")
|
||
restore_dir = sorted(p.name for p in (data / "restore_public").iterdir())
|
||
gate2 = read_json(RESULTS / "gate2_privacy.json")
|
||
p5 = gate2["results"]["P5_full_backup_restore"]
|
||
check("s9_public_only_full_private_reuse_gate2",
|
||
list(s9["results"].keys()) == ["S9_backup_restore"]
|
||
and restore_dir == ["mem0_public_history.db", "vec_public"]
|
||
and p5["pass"] and "mem0_private_history.db" in p5["backup_files"]
|
||
and "vec_private" in p5["backup_files"])
|
||
# 3f. S1 原冻结判据只抽查 Mem0 t1(代码与输出双重核对,判据未改动)
|
||
ab_src = (REPO / "spike/hel857/ab_scenarios.py").read_text(encoding="utf-8")
|
||
s1 = read_json(RESULTS / "retest_HEL-868_S1.json")["results"]["S1_verbatim_retention"]
|
||
check("s1_criterion_sampled_mem0_t1_only",
|
||
"raw_t1 = FX.PUBLIC_CORPUS[0][2]" in ab_src
|
||
and "any(raw_t1 in m for m in hist_msgs)" in ab_src
|
||
and not git("diff", "e06dcaf", "HEAD", "--", "spike/hel857/ab_scenarios.py")
|
||
and set(s1.keys()) <= {"fixture_integrity_pass", "baseline_raw_in_chat_message",
|
||
"mem0_raw_in_history_db", "expect", "pass"})
|
||
|
||
# ---- 4. 既有证据与账本零改动收尾核对 ----
|
||
old_files = git("ls-tree", "-r", "--name-only", "e06dcaf", "spike/hel857/results").splitlines()
|
||
check("old_result_blobs_unchanged",
|
||
all(git("rev-parse", f"e06dcaf:{p}") == git("rev-parse", f"HEAD:{p}")
|
||
for p in old_files))
|
||
after = {
|
||
"original": digest(table_rows(original_path, "outbound")),
|
||
"continued": digest(table_rows(continued_path, "outbound")),
|
||
"embed": digest(table_rows(embed_path, "embed_ops")),
|
||
}
|
||
check("ledgers_unchanged_during_recheck", before == after)
|
||
|
||
report = {
|
||
"card": "HEL-869",
|
||
"commit": git("rev-parse", "HEAD"),
|
||
"baseline_version": "1.11",
|
||
"generated_at": now_iso(),
|
||
"real_requests_added": 0,
|
||
"local_embeddings_added": 0,
|
||
"isolation": "socket connect denied; HF_HUB_OFFLINE=1; no gateway, no fastembed import",
|
||
"checks": checks,
|
||
"all_checks_pass": all(checks.values()),
|
||
"upstream_eviction_reproduction": {
|
||
"storage_source": str(storage_source),
|
||
"storage_sha256": hashlib.sha256(src_text.encode()).hexdigest(),
|
||
"one_batch_15": {"saved": 15, "retained": len(kept_one)},
|
||
"real_add_pattern": {"batches": pattern, "retained": len(kept_two),
|
||
"structure": "batch1 first 4 + all later batches; "
|
||
"batch1 last 5 evicted"},
|
||
"note": "save_messages() deletes beyond most recent 10 per scope "
|
||
"(storage.py 'LIMIT 10'); ties on identical created_at keep "
|
||
"insertion order, so a 9-row first batch loses its last 5 rows"},
|
||
"round_raw_retention": {
|
||
"fixtures_total": len(fixture_rows),
|
||
"mem0_messages_actual": len(stored),
|
||
"missing": missing,
|
||
"restore_public_same_10": sorted(restored) == sorted(stored),
|
||
"baseline_chat_message_rows": len(baseline),
|
||
"calls_add_inputs_have_all_15": all(text in add_inputs
|
||
for _, _, text in fixture_rows),
|
||
"assessment": "Mem0 SDK messages 表是每次写入后仅保留最近 10 条的滚动窗口,"
|
||
"不是永久原话档案;现状主档案(baseline.sqlite3 chat_message,"
|
||
"15 条逐字逐角色)与原始 calls 输入仍完整保留全部原话——"
|
||
"缺口在 SDK 派生副本的覆盖范围,不声称真实用户资料丢失。"
|
||
"永久原话职责由我方主档案承担;后续方案须让真实 Mem0 链从"
|
||
"持久化主档案读取原话,不以 SDK 滚动窗口或固定 fixtures 清单"
|
||
"充当长期原文库。"},
|
||
"erratum_facts": {
|
||
"usage_this_round": usage,
|
||
"usage_cumulative": after_totals,
|
||
"raw_qa_labels": [r["call"] for r in asks],
|
||
"plan_qa_labels": [q["no"] for q in plan_qa],
|
||
"s3_mem0_answer": s3_mem0_answer,
|
||
"counters": counters,
|
||
"ledger_new_rows": len(new_rows),
|
||
"embed_dense_new": dense_new,
|
||
"s9_restore_dir": restore_dir,
|
||
"gate2_p5_pass": p5["pass"],
|
||
},
|
||
"ledger_digests_before": before,
|
||
"ledger_digests_after": after,
|
||
"conclusion": "滚动 10 条窗口独立重现并只读核实本轮缺口(10/15,缺 5 条);"
|
||
"主档案与原始输入完整。六项报告口径勘误逐条核实。零真实请求、"
|
||
"零嵌入、零网络;三账与既有结果文件本轮前后未变。不改变原判据、"
|
||
"原结果与本轮 5 过 4 败的如实记录。",
|
||
}
|
||
OUT.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
||
print(json.dumps({"checks": checks, "all_checks_pass": all(checks.values())},
|
||
ensure_ascii=False))
|
||
return 0 if all(checks.values()) else 1
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|