mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-17 10:32:01 +00:00
eddeded2a4
- 第一批(安全加固与生命周期止血):隔离测试宿主机密钥与 .env 泄漏;修复 SQLite 取消查询挂死、:memory: 连接池报错与 EngineCache 世代竞态;补齐运行与评测删除时的 Checkpointer 线程、Artifact 磁盘文件与无主附件回收;加固三套沙箱路径越界、进程组清理与 Seatbelt 数据目录隔离,封堵 SSRF IPv4-mapped IPv6 元数据绕过与响应体 OOM;修复推理模型多轮 reasoning_content、结构化输出 Token 漏计与缓存折扣计费 - 第二批(数据库/集群/问数提速与首屏分包):补齐核心表索引与 SQLite WAL 调优,列表接口按需 defer 大列,收敛启动扫描并打通跨进程 slot 槽位唤醒;优化跨源全局选表、哈希桶数字绑定、流式 CSV 导入及多方言分析算子;剥离首屏静态引入的 @xyflow/react 与全局样式(首屏主包降至 461.59 kB),补充流式 rAF 攒批、Store 精细订阅与表单无障碍绑定 - 第三批(架构演进与工程自动化闭环):记录库超挂接阈值历史版本自动增量归档至单库多表(解除 SQLite 10 库 ATTACH 硬上限);重构知识库为词面 BM25 与全集合归一化向量矩阵真·双路独立召回并支持游标分批重建;升级多方言感知 SQL 模板词法分析(E'...' / $$...$$ / q'[...]' / # / 嵌套注释)与 Decimal / bool / NaN 参数校验,消除 ledger 层对 api 路由层的反向依赖;拆分 3101 行 CaliberDrafts 页面为 7 个领域子模块,消除检查脚本本机路径硬编码并新增 GitHub Actions CI 门禁与三批回归测试套件
201 lines
8.6 KiB
Python
201 lines
8.6 KiB
Python
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from app.core import atomic
|
|
from app.core.config import settings
|
|
|
|
# --------------------------------------------------------------------------
|
|
# 内容寻址的工件库
|
|
#
|
|
# 事件流里的输出是给画布看的截断预览;这里存的是完整证据。
|
|
# 工件按内容 sha256 寻址:同一份内容只存一份,且任何篡改都会改变地址本身,
|
|
# 这比"相信数据库没被改过"强得多。出具溯源、周对比 diff、基线回归、
|
|
# 轨迹提模板,全部踩在这一层上。
|
|
# --------------------------------------------------------------------------
|
|
|
|
|
|
def canonical_json(obj: Any) -> str:
|
|
"""规范化 JSON:键排序、紧凑分隔符。同一数据永远得到同一字节串,哈希才稳定。"""
|
|
return json.dumps(obj, ensure_ascii=False, sort_keys=True, separators=(",", ":"), default=str)
|
|
|
|
|
|
def content_hash(data: bytes | str) -> str:
|
|
if isinstance(data, str):
|
|
data = data.encode()
|
|
return hashlib.sha256(data).hexdigest()
|
|
|
|
|
|
def graph_hash(graph: dict[str, Any]) -> str:
|
|
"""图定义的指纹。formal run 钉住的就是这个值。
|
|
|
|
viewport 是纯视觉状态,挪一下画布不该改变图的身份,剔除后再哈希。
|
|
"""
|
|
slim = {k: v for k, v in graph.items() if k != "viewport"}
|
|
return content_hash(canonical_json(slim))
|
|
|
|
|
|
def execution_content(graph: dict[str, Any]) -> dict[str, Any]:
|
|
"""执行定义的规范形式。历史 graph_hash 保持原算法,以便复验已封存证据。"""
|
|
from app.engine.schema import GraphSpec
|
|
|
|
spec = GraphSpec.model_validate(graph)
|
|
return {
|
|
"schema_version": 1,
|
|
"defaults": spec.defaults,
|
|
"nodes": sorted([{"id": n.id, "type": n.type.value, "data": n.data.model_dump()}
|
|
for n in spec.nodes], key=lambda n: n["id"]),
|
|
"edges": sorted([{"source": e.source, "target": e.target, "sourceHandle": e.sourceHandle,
|
|
"targetHandle": e.targetHandle} for e in spec.edges], key=canonical_json),
|
|
}
|
|
|
|
|
|
def execution_hash(graph: dict[str, Any]) -> str:
|
|
"""布局、选中态和边的显示标签不改变执行身份。"""
|
|
return content_hash(canonical_json(execution_content(graph)))
|
|
|
|
|
|
def _path_of(artifact_id: str) -> Path:
|
|
# 按前两位分桶,避免单目录塞几万个文件
|
|
return settings.data_dir / "artifacts" / artifact_id[:2] / f"{artifact_id}.json"
|
|
|
|
|
|
async def put_json(
|
|
obj: Any,
|
|
*,
|
|
kind: str,
|
|
run_id: str | None = None,
|
|
node_id: str | None = None,
|
|
meta: dict[str, Any] | None = None,
|
|
) -> str:
|
|
"""存一个 JSON 工件,返回其内容哈希(即工件 id)。
|
|
|
|
幂等:同内容重复写只落一次盘;同一工件被多个 run 引用时,
|
|
数据库里各记一行引用(溯源需要知道"谁产出的"),文件只有一份。
|
|
"""
|
|
from sqlalchemy.exc import IntegrityError
|
|
|
|
from app.cluster.mutex import lock
|
|
from app.db.base import SessionLocal
|
|
from app.db.models import Artifact
|
|
|
|
text = canonical_json(obj)
|
|
artifact_id = content_hash(text)
|
|
path = _path_of(artifact_id)
|
|
async with lock(f"artifact:{artifact_id[:2]}"):
|
|
if not path.exists():
|
|
# 原子落盘(core/atomic):写一半崩了不会留下半个工件;临时文件名带随机后缀,两个进程同时写同一份内容
|
|
# 各写各的,不会一个把另一个写到一半的截断;且与同分桶的 forget 互斥,不会刚写下就被并发回收删掉
|
|
atomic.write_text(path, text)
|
|
|
|
async with SessionLocal() as session:
|
|
existing = await session.get(Artifact, (artifact_id, run_id or ""))
|
|
if existing is None:
|
|
session.add(
|
|
Artifact(
|
|
id=artifact_id,
|
|
run_id=run_id or "",
|
|
kind=kind,
|
|
node_id=node_id,
|
|
size=len(text.encode()),
|
|
meta=meta or {},
|
|
)
|
|
)
|
|
try:
|
|
await session.commit()
|
|
except IntegrityError:
|
|
await session.rollback()
|
|
return artifact_id
|
|
|
|
|
|
def load(artifact_id: str) -> Any | None:
|
|
"""按 id 取回工件内容。取回时重新校验哈希——工件库的承诺就是内容不可变。"""
|
|
if not artifact_id or not artifact_id.isalnum():
|
|
return None
|
|
path = _path_of(artifact_id)
|
|
if not path.exists():
|
|
return None
|
|
text = path.read_text(encoding="utf-8")
|
|
if content_hash(text) != artifact_id:
|
|
raise ValueError(f"工件 {artifact_id[:12]}… 内容与哈希不符,疑似被篡改")
|
|
return json.loads(text)
|
|
|
|
|
|
def read_bytes(artifact_id: str, *, verify: bool = True) -> bytes | None:
|
|
"""按 id 取回工件文件的原始字节。文件本身就是 put_json 写下的规范 JSON,字节原样,不解析、不重排。
|
|
|
|
可验证报告要把工件按原字节嵌进页面,让拿到文件的人自己重算哈希,所以不能像 load 那样解析了再交出去。
|
|
默认同样复验哈希、对不上就抛 ValueError(和 load 一样的承诺);verify=False 只给要把字节原样交给别人
|
|
去核的调用方——被改过的工件照实交出去,核的那一方就会看到对不上。id 不对或者文件不在了返回 None。
|
|
"""
|
|
if not artifact_id or not artifact_id.isalnum():
|
|
return None
|
|
path = _path_of(artifact_id)
|
|
if not path.exists():
|
|
return None
|
|
data = path.read_bytes()
|
|
if verify and content_hash(data) != artifact_id:
|
|
raise ValueError(f"工件 {artifact_id[:12]}… 内容与哈希不符,疑似被篡改")
|
|
return data
|
|
|
|
|
|
async def forget(ids: Any) -> list[str]:
|
|
"""回收工件文件:这几个 id 里,引用表(artifacts)里**一条引用都不剩**的,删掉文件;还有引用的一个不动。返回删掉了
|
|
哪几个(docs/design/next-round/01-效果度量与回归评测.md 做法 16)。
|
|
|
|
为什么按引用数、不按调用方说的:工件按内容寻址,同样的内容只存一份——评测的一次运行和用户的一次运行查到同一份结果、
|
|
冻结了同一份表结构,文件就是同一个。调用方先删自己那几行引用(删运行时它名下的引用行),再把这些 id 交给这里;别的
|
|
运行、目录快照、对比结果还引用着的文件照留。put_json 每写一个工件都记一行引用,所以「没有引用」就是没人要了。
|
|
|
|
先查引用再删文件,两步之间同一份内容又被写一次(put_json 先写文件、后记引用)的话会删掉一个刚有人要的文件:单进程部署,
|
|
回收在评测清理的后台任务里串行做,和写入撞上的窗口极小;真撞上了,读的一方照实报「工件不在」(load 返回 None),不会
|
|
读到错的内容。"""
|
|
from sqlalchemy import select
|
|
|
|
from app.cluster.mutex import lock
|
|
from app.db.base import SessionLocal
|
|
from app.db.models import Artifact
|
|
|
|
wanted = sorted({i for i in ids or () if isinstance(i, str) and i and i.isalnum()})
|
|
if not wanted:
|
|
return []
|
|
by_bucket: dict[str, list[str]] = {}
|
|
for artifact_id in wanted:
|
|
by_bucket.setdefault(artifact_id[:2], []).append(artifact_id)
|
|
|
|
removed: list[str] = []
|
|
for bucket in sorted(by_bucket):
|
|
bucket_ids = by_bucket[bucket]
|
|
async with lock(f"artifact:{bucket}"):
|
|
async with SessionLocal() as session:
|
|
kept: set[str] = set()
|
|
for start in range(0, len(bucket_ids), 500):
|
|
chunk = bucket_ids[start:start + 500]
|
|
kept |= set((await session.execute(select(Artifact.id).where(Artifact.id.in_(chunk)))).scalars())
|
|
for artifact_id in bucket_ids:
|
|
if artifact_id in kept:
|
|
continue
|
|
path = _path_of(artifact_id)
|
|
try:
|
|
path.unlink()
|
|
except FileNotFoundError:
|
|
continue
|
|
removed.append(artifact_id)
|
|
return removed
|
|
|
|
|
|
def manifest_hash(rows: list[tuple[int, str, str | None, dict[str, Any]]]) -> str:
|
|
"""把一次运行的全部事件压成一个清单哈希。
|
|
|
|
rows: [(seq, type, node_id, data)]。存在 Run 上之后,事后任何对
|
|
事件流的增删改都能被这一个值戳穿。
|
|
"""
|
|
lines = [
|
|
f"{seq}|{etype}|{node_id or ''}|{content_hash(canonical_json(data))}"
|
|
for seq, etype, node_id, data in sorted(rows, key=lambda r: r[0])
|
|
]
|
|
return content_hash("\n".join(lines))
|