Files
CyberGril/tools/audit_sdk_offline_hel896.py
T
zonggongandmultica-agent 01ff919859 HEL-879 release closure: the four HEL-896 audit findings become enforced behavior - (1) archive consistency: tools/release_snapshot_hel896.py v2 checks the wal_checkpoint(TRUNCATE) return (busy!=0 = hard failure, no deliverable tar, half-built dir removed - 'stopped service first' is a precondition, never a reason to ignore an actual failed result), aborts packaging on any source-vs-snapshot table-count mismatch instead of recording rows_match=False and shipping anyway, and verify_archive now rejects legacy packages that recorded rows_match=False while mapping a real rollback drill (unpack to an isolated dir, open every DB, check rows AND hashes against both recorded source and snapshot counts, emit a source-path rollback_plan - no more tar-internal self-attestation); selftest 9/9 reproduces every old failure shape first (naive WAL copy loses companion, held-reader checkpoint=(1,9,8) leaves the copied image malformed/missing the events row, the manager's rows_match=False legacy package verifying ok) then proves each fix (busy fails with zero artifacts, stale-snapshot mismatch fails with zero artifacts, online mode refuses --file dirs containing SQLite by magic-header scan, stop mode recursively takes embedded SQLite like history_root/mem0_public_history.db through checkpoint+per-table verification, verify maps source paths and passes); (2) early-finish seal: PersistentBudget gains sealed()/seal() writing sealed/sealed_requests/sealed_tokens/sealed_at atomically into budget_total beside the real usage (never faking 55, never zeroing), acquire checks the seal FIRST so every category and every remaining allowance rejects budget_sealed:51/55, the marker survives restart and backup-API archive/restore, reseal is idempotent, and there is deliberately no unseal path (re-test = new approval + new instance per budget-package 6.2.4); tools/seal_budget_hel879.py makes the closure an explicit auditable operator command with a post-seal rejection self-check; verify_budget_split_hel896.py gains S6 (51/55 experience chain completes -> seal keeps usage 51 -> 52nd and cross-category rejected with dialogue daily still 19/60 proving it is the seal not the caps, mistaken restart rejected, archive restore rejected, marker requests=51 intact) now 10/10, HEAD made dynamic instead of hardcoded 04eff61; budget-package-hel895.md 6.2 rewritten to the executable seal order (stop -> seal -> consistency snapshot); (3) single install entry: deploy/hel895-release-candidate.md 2 is now the only copy-paste install (uv --offline, npm --offline, cache-miss = stop and record, network only inside an authorized release window with per-item sha256) and 4 is the only fixed-SDK entry as a five-step chain (verify tarball sha256 9dcef930...dda23 against mem0-stack.lock -> build the wheel from the fixed source with hatchling honestly listed as the missing build backend -> cp311 dependency prep with greenlet/pillow/truststore confirmed cache-reusable on re-run -> local-wheels-only --no-index install where mem0ai must come from the fixed-source wheel, the lock line is version-only -> same-process co-import plus the 92MB fastembed cache placement); deploy/hel874-release.md 2/4 carry superseded banners pointing here, mem0-stack.lock no longer routes installs through the index mem0ai==2.2.1 wheel; (4) exact-commit honesty: audit_sdk_offline_hel896.py derives head from git rev-parse and accepts an output dir, fresh evidence written to docs/rework/hel879/sdk-audit/ (hel896 evidence left untouched) recording closure 55 / missing 41 (28 pure + 13 native) / cache-reusable [greenlet, pillow, truststore] / tarball-matches-lock at c121c42; regression on this head: pytest 299/299, ruff clean (src/tests/tools), release-snapshot selftest 9/9, budget-split 10/10 including the new S6 negatives; zero provider calls, zero downloads, authoritative ledgers/freezes/HEL-835 gate untouched, not deployed, PR#11 untouched
Co-authored-by: multica-agent <github@multica.ai>
2026-10-27 03:26:30 +08:00

269 lines
15 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-896 · 固定 SDK 离线余缺只读审计(零下载、零安装、零推理)。
总管独立复审(HEL-896 附件 §3)核定的事实:三个顶层包的 WHEEL 标签均为
py3-none-any(不是必须另找 cp311 专用轮子);已装 mem0ai 的来源是本地固定源码
hel857-src(direct_url),不是索引包;按 3.11 Linux markers + extras 从 3.10 安装
元数据计算的闭包,产品 3.11 venv 缺 41 个分发(含 grpcio/numpy/onnxruntime/
tokenizers 等原生扩展)——那是「已有安装元数据的依赖闭包」,不是已完成的 cp311
解析结果。本工具把这份闭包逐项核清为可执行清单:
- 每个缺项:版本、3.10 安装的 WHEEL 标签、纯 Python / 原生分类、目标平台
(x86_64 Linux)应取的 wheel 形态、本机缓存可复用条目(uv wheels-v*/pypi 与
pip wheels 缓存,记录路径)、来源与哈希(凡有权威值处);
- mem0ai 固定源码身份:hel857-src direct_url + hel857-data/mem0-2c81af3.tar.gz
实测 SHA256 对照 deploy/mem0-stack.lock 注释;pip-install.log 记录的曾构建
wheel 哈希及其「临时缓存、未持久」事实;
- fastembed 模型缓存实测(hel857-data/fastembed-cache,真实模型目录与大小),
发布机落位路径口径;
- seq48–51 pip 26.2.2 事件的缓存取证:uv 缓存中该 wheel 条目创建于
2026-10-27 02:10:04(HEL-895 运行窗口内),来源 files.pythonhosted.org——
该步「零下载」表述不成立(勘误);requirements.lock 装机全部命中既有缓存
(同期无其他新缓存条目)。
只读:不安装、不下载、不 pip/uv 命令、不 site-packages 复制、不写任何产品或
固定栈目录;唯一输出写 docs/rework/hel896/sdk-audit/。缺项不阻塞其余发布工作;
真正下载只在发布卡按 deploy/hel874-release.md §4 获授权执行。
用法:.venv311/bin/python tools/audit_sdk_offline_hel896.py
"""
from __future__ import annotations
import hashlib
import importlib.metadata as md
import json
import re
import sys
from datetime import datetime
from pathlib import Path
from packaging.markers import default_environment
from packaging.requirements import Requirement
REPO = Path(__file__).resolve().parents[1]
HELM = Path("/home/xiaomo/multica_workspaces/hello-af23464d222e/hel-857-2cf6dc7dfc87/workdir")
SDK = HELM / "hel857-venv/lib/python3.10/site-packages"
PROD = Path("/home/xiaomo/multica_workspaces/hello-af23464d222e/hel-895-0261e950b9c2/workdir/CyberGril/.venv311/lib/python3.11/site-packages")
SRC = HELM / "hel857-src"
DATA = HELM / "hel857-data"
UV_CACHE = Path.home() / ".cache/uv"
PIP_WHEELS = Path.home() / ".cache/pip/wheels"
LOCK_TARBALL_SHA256 = "9dcef9303ebcec116eec6739f01b8b35bd24459de6a569686b4d19b9412dda23"
PINNED_WHEEL_SHA256 = "698284b6083ab8b7761454d65876a6d1bb983d278ad21a7bee38d760cb20e9db"
def key(n):
return n.lower().replace("_", "-").replace(".", "-")
def sha256_file(p: Path) -> str:
h = hashlib.sha256()
with open(p, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()
def wheel_tags(dist: md.Distribution) -> list[str]:
raw = dist.read_text("WHEEL") or ""
return re.findall(r"^Tag:\s*(\S+)$", raw, re.M)
def cache_hits(name: str, version: str) -> list[dict]:
hits: list[dict] = []
for gen in ("wheels-v7", "wheels-v6"):
base = UV_CACHE / gen / "pypi" / name
if base.is_dir():
for entry in sorted(base.iterdir()):
if entry.is_dir() and entry.name.startswith(version):
hits.append({"kind": f"uv:{gen}", "path": str(entry),
"name": entry.name, "sha256": None})
if PIP_WHEELS.is_dir():
for whl in sorted(PIP_WHEELS.rglob(f"{name.replace('-', '_')}-{version}-*.whl")):
hits.append({"kind": "pip:wheels", "path": str(whl), "name": whl.name,
"sha256": sha256_file(whl)})
return hits
def main() -> int:
import subprocess as _sp
try:
head = _sp.run(["git", "rev-parse", "HEAD"], cwd=REPO, capture_output=True,
text=True, check=True).stdout.strip()
except Exception:
head = "unknown"
# HEL-879:head 动态取当前提交,不再硬编码旧父提交冒充最新 head;
# 可选参数改写证据目录(默认保持 HEL-896 历史目录不动,本卡证据写 hel879/)。
out_dir = Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else REPO / "docs/rework/hel896/sdk-audit"
out_dir.mkdir(parents=True, exist_ok=True)
installed = {key(d.metadata["Name"]): d for d in md.distributions(path=[str(SDK)])}
base = {key(d.metadata["Name"]): d for d in md.distributions(path=[str(PROD)])}
env = default_environment()
env.update(python_version="3.11", python_full_version="3.11.16", extra="")
queue = [("mem0ai", frozenset()), ("qdrant-client", frozenset()), ("fastembed", frozenset())]
seen: set = set()
rows: dict[str, dict] = {}
while queue:
name, extras = queue.pop(0)
if (name, extras) in seen:
continue
seen.add((name, extras))
d = installed.get(name)
if d is None:
rows.setdefault(name, {"name": name, "installed_sdk": False})
continue
if name not in rows:
tags = wheel_tags(d)
native = tags and not any(t.endswith("py3-none-any") or "py2.py3-none-any" in t for t in tags)
rows[name] = {
"name": name, "version": d.version, "wheel_tags": tags,
"native_extension": native,
"installed_sdk": True, "present_product_311": name in base,
"product_version": base[name].version if name in base else None,
"direct_url": d.read_text("direct_url.json"),
}
for raw in d.requires or []:
req = Requirement(raw)
if req.marker and not any(req.marker.evaluate(dict(env, extra=x)) for x in set(extras) | {""}):
continue
queue.append((key(req.name), frozenset(req.extras)))
missing = []
for name, r in sorted(rows.items()):
if not r.get("installed_sdk") or r.get("present_product_311"):
continue
hits = cache_hits(name, r["version"])
if r["native_extension"]:
resolution = ("3.11 目标需 cp311-cp311(或 cp39+ abi3)manylinux x86_64 原生 wheel;"
"3.10 安装标签不可复制,禁混 site-packages")
else:
resolution = "纯 Python py3-none-any:同版本 wheel 可跨 3.10/3.11 使用"
# 缓存「可复用」必须同版本且标签兼容 3.11:纯 py3-none-any,或 cp311 / cp3x-abi3 标签。
def usable(h: dict) -> bool:
tag = h["name"]
if tag.endswith("py3-none-any"):
return True
if "cp311-" in tag:
return True
return bool(re.search(r"cp3\d+-abi3", tag))
reusable = [h for h in hits if usable(h)]
cls = "cache-reusable" if reusable else ("fixed-source" if name == "mem0ai" else "missing-download-at-release")
r.update(cache_hits=hits, cache_hits_usable_for_311=[h["name"] for h in reusable],
resolution=resolution, classification=cls)
missing.append(r)
# mem0ai 固定源码身份核验
tarball = DATA / "mem0-2c81af3.tar.gz"
tar_sha = sha256_file(tarball) if tarball.is_file() else None
mem0 = installed.get("mem0ai")
direct = (mem0.read_text("direct_url.json") if mem0 else "") or ""
install_log = DATA / "pip-install.log"
built_wheel_note = None
if install_log.is_file():
text = install_log.read_text(errors="replace")
m = re.search(r"Created wheel for mem0ai: filename=(\S+) size=(\d+) sha256=([0-9a-f]{64})", text)
if m:
built_wheel_note = {"filename": m.group(1), "size": int(m.group(2)), "sha256": m.group(3),
"ephemeral_wheel_cache": "/tmp/multica-task-1816511421 (不再存在)",
"persisted_anywhere": False}
hatchling = bool(cache_hits("hatchling", "") or cache_hits("hatchling", "1.32.4")) or (PROD.parent / "hatchling").exists()
identity = {
"direct_url_of_installed": direct.strip(),
"fixed_source_dir": str(SRC),
"fixed_source_dir_exists": SRC.is_dir(),
"pinned_tarball": str(tarball),
"pinned_tarball_sha256_measured": tar_sha,
"pinned_tarball_sha256_lock": LOCK_TARBALL_SHA256,
"tarball_matches_lock": tar_sha == LOCK_TARBALL_SHA256,
"index_wheel_2_2_1_proves_same_code": False,
"note": "索引下载的 mem0ai==2.2.1 wheel 不自动等于固定源码;发布必须用本 tarball/源码目录离线构建安装",
"built_wheel_from_hel857_install": built_wheel_note,
"offline_build_backend": {"hatchling_cached_or_local": bool(hatchling),
"note": "离线构建 mem0 wheel 需要 hatchling 及其依赖可离线获得;未命中则发布卡需一并拉取"},
}
# fastembed 模型缓存实测
fe_cache = DATA / "fastembed-cache"
models = {}
if fe_cache.is_dir():
for d in sorted(fe_cache.glob("models--*")):
files = [p for p in d.rglob("*") if p.is_file()]
models[d.name] = {"files": len(files), "bytes": sum(p.stat().st_size for p in files)}
default_cache = Path.home() / ".cache/fastembed"
fastembed_models = {
"cache_dir": str(fe_cache), "exists": fe_cache.is_dir(),
"models": models,
"default_cache_dir": str(default_cache), "default_cache_exists": default_cache.is_dir(),
"release_note": "真实 mem0 模式把 fastembed cache_dir 指向发布实例数据目录内的该缓存拷贝;本次零下载、不推理",
}
# seq48–51 pip 26.2.2 事件缓存取证
pip_entry = UV_CACHE / "wheels-v7/pypi/pip/26.2.2-py3-none-any"
pip_http = UV_CACHE / "wheels-v7/pypi/pip/26.2.2-py3-none-any.http"
archive = UV_CACHE / "archive-v0"
new_archives = [p for p in archive.iterdir() if p.stat().st_mtime >= datetime(2026, 10, 27, 1, 50).timestamp()] if archive.is_dir() else []
http_meta = pip_http.read_bytes()[:400] if pip_http.is_file() else b""
url_m = re.search(rb"https://files\.pythonhosted\.org/\S*pip-26\.2\.2\S*\.whl", http_meta)
sha_m = re.search(rb"sha256=([0-9a-f]{64})|Sha256.{0,4}([0-9a-f]{64})", http_meta)
venv_pip_di = PROD / "pip-26.2.2.dist-info"
pip_event = {
"claim_under_review": "HEL-895 seq48–51:uv pip install --offline pip 失败后去掉 --offline 安装 pip 26.2.2 成功;前卡日志仅存尾两行",
"installed_into": str(venv_pip_di),
"installer": (venv_pip_di / "INSTALLER").read_text().strip() if (venv_pip_di / "INSTALLER").is_file() else None,
"uv_cache_entry_created": datetime.fromtimestamp(pip_entry.stat().st_mtime).isoformat() if pip_entry.is_dir() else None,
"uv_http_cache_created": datetime.fromtimestamp(pip_http.stat().st_mtime).isoformat() if pip_http.is_file() else None,
"recorded_source_url": url_m.group(0).decode() if url_m else None,
"recorded_sha256": (sha_m.group(1) or sha_m.group(2)).decode() if sha_m else None,
"other_new_cache_entries_in_window": [p.name for p in new_archives if p.name != "_hW09NO2UJIjczHf"],
"verdict": ("勘误成立:uv 缓存中 pip-26.2.2 wheel 条目创建于 2026-10-27 02:10:04 +0800(HEL-895 运行窗口内),"
"来源 files.pythonhosted.org,且是该窗口唯一新增缓存条目——该步发生了网络获取,"
"前卡『零下载』对此步不成立;requirements.lock 装机同期未产生任何新缓存条目(全部命中既有缓存)。"
"字节级『完整下载 vs 条件请求』无法由缓存取证区分,按保守口径记为下载。"),
}
top = {n: rows.get(n) for n in ("mem0ai", "qdrant-client", "fastembed")}
result = {
"head": head,
"scope": ("只读审计:3.10 固定栈安装元数据按 3.11 Linux markers+extras 求闭包,对照产品 3.11 venv 与本机 uv/pip 缓存;"
"这是依赖闭包清单,不是已完成的 cp311 解析或下载结果"),
"read_only": True, "zero_downloads_this_card": True,
"closure_total": len(rows), "missing_count": len(missing),
"missing_pure_python": sorted(r["name"] for r in missing if not r["native_extension"]),
"missing_native": sorted(r["name"] for r in missing if r["native_extension"]),
"cache_reusable_now": sorted(r["name"] for r in missing if r["classification"] == "cache-reusable"),
"top_level": top,
"missing_detail": missing,
"mem0_identity": identity,
"fastembed_models": fastembed_models,
"pip_2622_event": pip_event,
}
(out_dir / "sdk-audit.json").write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
summary = [
"# HEL-896 · 固定 SDK 离线余缺审计摘要(只读)\n",
f"- 闭包 {len(rows)} 项,产品 3.11 venv 缺 {len(missing)} 项:纯 Python "
f"{len([r for r in missing if not r['native_extension']])} 项、原生扩展 "
f"{len([r for r in missing if r['native_extension']])} 项(" + ", ".join(result["missing_native"]) + ")。",
"- 三个顶层包 WHEEL 均 py3-none-any(纯 Python,可跨 3.10/3.11)。",
f"- mem0ai 固定源码身份:tarball SHA256 {'一致' if identity['tarball_matches_lock'] else '不一致!'}"
f"({identity['pinned_tarball_sha256_measured']});索引同名 wheel 不作数;"
f"hel857 构建过的 wheel({PINNED_WHEEL_SHA256[:12]}…)在临时缓存、未持久。",
f"- 当前缓存可直接复用的缺项 wheel:{result['cache_reusable_now'] or '(mem0 栈闭包内无)'}。",
"- 其余缺项(纯 Python wheel 与 cp311 原生 wheel)由发布卡按 deploy/hel874-release.md §4 "
"获授权后下载并 sha256 留证;缺项不阻塞其余发布工作。",
f"- fastembed 模型缓存实测:{json.dumps(fastembed_models['models'], ensure_ascii=False)}"
"(hel857-data/fastembed-cache,随发布实例落位,零下载)。",
f"- pip 26.2.2 事件:{pip_event['verdict']}",
]
(out_dir / "summary.md").write_text("\n".join(summary) + "\n", encoding="utf-8")
print(json.dumps({"closure_total": len(rows), "missing": len(missing),
"pure": len(result["missing_pure_python"]), "native": len(result["missing_native"]),
"cache_reusable": result["cache_reusable_now"],
"mem0_tarball_matches_lock": identity["tarball_matches_lock"]}, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())