已开启
feat/build-memory-optimization #14
hid24429644创建于 10月20日
feat/build-memory-optimization #14
已开启
共 24 个文件变更+2218-83
| @@ -17,3 +17,6 @@ dist/ | |||
| 17 | 17 | ||
| 18 | # ZCode agent workspace | 18 | # ZCode agent workspace |
| 19 | .zcode/ | 19 | .zcode/ |
| 20 | + | ||
| 21 | +# Generated performance corpora and reports | ||
| 22 | +benchmarks/results/ | ||
| @@ -789,8 +789,8 @@ scope 各限制为 4096 字符。需要正文时应继续使用带游标的 `get | |||
| 789 | 789 | ||
| 790 | ```bash | 790 | ```bash |
| 791 | # 克隆仓库 | 791 | # 克隆仓库 |
| 792 | -git clone https://gitcode.com/DeepRust/project-brain.git | 792 | +git clone https://gitcode.com/xuanwu/bot-brain.git |
| 793 | -cd project-brain | 793 | +cd bot-brain |
| 794 | 794 | ||
| 795 | # 安装依赖 | 795 | # 安装依赖 |
| 796 | uv sync --extra dev | 796 | uv sync --extra dev |
| @@ -970,8 +970,8 @@ MIT License | |||
| 970 | 970 | ||
| 971 | ## 联系方式 | 971 | ## 联系方式 |
| 972 | 972 | ||
| 973 | -- 项目地址:https://gitcode.com/DeepRust/project-brain | 973 | +- 项目地址:https://gitcode.com/xuanwu/bot-brain |
| 974 | -- 问题反馈:https://gitcode.com/DeepRust/project-brain/issues | 974 | +- 问题反馈:https://gitcode.com/xuanwu/bot-brain/issues |
| 975 | 975 | ||
| 976 | ## 致谢 | 976 | ## 致谢 |
| 977 | 977 | ||
| @@ -0,0 +1,126 @@ | |||
| 1 | +# 分阶段性能基准 | ||
| 2 | + | ||
| 3 | +在仓库根目录、装有项目依赖的 Python 环境中执行: | ||
| 4 | + | ||
| 5 | +```powershell | ||
| 6 | +python -m benchmarks.performance.run --size smoke --runs 1 --warm-runs 2 | ||
| 7 | +python -m benchmarks.performance.run --size medium --runs 3 --backend json | ||
| 8 | +python -m benchmarks.performance.run --size medium --runs 3 --backend sqlite | ||
| 9 | +python -m benchmarks.performance.run --project C:/datasets/my-project --output C:/bench-results --query timeout --query "连接池" | ||
| 10 | +python -m benchmarks.performance.run --project C:/datasets/my-project --output C:/bench-results --runs 1 --sample-resources --max-rss-mib 8192 --max-document-mib 16 --timeout 1800 | ||
| 11 | +``` | ||
| 12 | + | ||
| 13 | +默认 keyword,不下载向量模型。`--strategy hybrid` / `semantic` 可测语义路径, | ||
| 14 | +需要事先准备模型和相关依赖;模型失败、降级或解析失败不会被当作成功基准。 | ||
| 15 | +`--timeout` 是单个 worker 的秒数上限,默认 600。失败返回非零退出码并保留诊断报告。 | ||
| 16 | + | ||
| 17 | +## 数据集 | ||
| 18 | + | ||
| 19 | +固定内容生成,不依赖网络和随机数,包含 Python、Rust、C、TypeScript、Go 源码, | ||
| 20 | +中英文 Markdown 和 TXT 文档。源码包含大量符号,文档包含长正文、分节和代码符号引用。 | ||
| 21 | +查询覆盖英文、中文、符号名、下划线标识符及无命中场景。可重复 `--query` 自定义查询。 | ||
| 22 | + | ||
| 23 | +| 规模 | 源码文件 | 文档文件 | 每文件函数数 / 每文档节数 | | ||
| 24 | +|---|---:|---:|---:| | ||
| 25 | +| smoke | 5 | 4 | 4 | | ||
| 26 | +| small | 50 | 20 | 12 | | ||
| 27 | +| medium | 500 | 200 | 24 | | ||
| 28 | +| large | 2500 | 1000 | 48 | | ||
| 29 | + | ||
| 30 | +`--project` 使用真实项目的副本,可以加入 Java、C++、Office、PDF 等项目支持的格式; | ||
| 31 | +原项目及其已有图谱不会被修改。复制排除 `.git`、旧图谱、虚拟环境及常见大型依赖目录, | ||
| 32 | +因此当前框架不测试真实 Git 历史规模。测试副本统一使用框架配置:full profile、 | ||
| 33 | +index_body=true、保存所有文档全文与分块、关闭 watcher 和 Clang 语义解析,文档总量上限 1 GiB。 | ||
| 34 | +单文档仍保留项目默认的 2 MiB 限制,超限会使基准失败。 | ||
| 35 | +可以通过 `--max-document-mib` 调整单文档上限。 | ||
| 36 | +不复制原项目配置。每轮构建前记录文件数量、扩展名分布、字节数和内容 SHA256, | ||
| 37 | +保证各轮输入一致。真实项目运行时需避免同时修改数据集。 | ||
| 38 | + | ||
| 39 | +## 阶段与测量语义 | ||
| 40 | + | ||
| 41 | +每轮先在独立进程构建并发布图谱,再在另一个新进程加载同一图谱并查询。 | ||
| 42 | +运行时通过可还原的方法包装器插桩,不改变生产代码,也不会启动 watcher。 | ||
| 43 | + | ||
| 44 | +- 构建:源码解析、单文档解析、历史探测、关系、文档代码链接、约定、profile 投影。 | ||
| 45 | +- 扫描:源码、文档、manifest 发现;逐次计时迭代器推进,不包含消费端的解析时间。 | ||
| 46 | +- 索引:BM25 构建、符号和文件索引、关键词索引读写、可选语义索引构建和加载。 | ||
| 47 | +- 存储:JSON 图加载、邻接索引重建、JSON 写入、generation 发布;SQLite 启动加载。 | ||
| 48 | +- 冷启动:依赖导入、服务初始化、schema 检查、查询索引准备、能力计算。 | ||
| 49 | +- 查询:第一轮查询、连续查询、BM25、embedding、向量检索、融合召回、结果序列化。 | ||
| 50 | + | ||
| 51 | +`session.ready` 是创建服务到初始化完成;进程总耗时另含解释器启动、导入、 | ||
| 52 | +查询及清理。冷启动指新进程,**不清空操作系统文件缓存**。 | ||
| 53 | +第一轮的多个查询共用进程,只有其中第一个查询具有首次查询初始化成本。 | ||
| 54 | +查询 worker 如触发重建会失败,防止将构建时间误报为加载时间。 | ||
| 55 | + | ||
| 56 | +报告同时记录 inclusive 时间、self 时间、CPU 时间、阶段前后的 RSS。 | ||
| 57 | +嵌套阶段的 inclusive 时间不能相加。RSS 是边界快照,不是阶段峰值; | ||
| 58 | +Windows/Linux 支持 RSS,其他平台标为 null。为避免干扰默认不启用 tracemalloc。 | ||
| 59 | +计时包含插桩开销,适合在同机器、同 Python/依赖/配置/数据集下比较。 | ||
| 60 | +报告的 p50/p95 是每次方法调用分布;另有每个 worker 内该阶段累计时间的中位数, | ||
| 61 | +适合比较多次调用的文档解析等阶段。少量样本的 p95 只供观察。 | ||
| 62 | +扫描样本包含每个产出文件及最后一次迭代结束检测,累计值表示扫描活动耗时。 | ||
| 63 | + | ||
| 64 | +## 输出和扩展 | ||
| 65 | + | ||
| 66 | +`benchmarks/results/<UTC时间>/` 保存输入副本、每个 worker 的请求、结果、日志, | ||
| 67 | +以及汇总 `report.json` 和 `report.md`。JSON 包含原始样本、查询命中数和环境信息, | ||
| 68 | +方便后续基线比较。生成目录被 Git 忽略,框架不会自动删除历史结果。 | ||
| 69 | +Windows 下请使用较短的输出路径,底层图谱临时文件可能受系统路径长度限制。 | ||
| 70 | + | ||
| 71 | +`--sample-resources` 需要可选的 psutil,默认每 0.5 秒采样 worker 及其子进程, | ||
| 72 | +在各 worker 目录保存 `resources.jsonl`,报告增加 RSS 采样峰值、CPU 采样峰值和观测到的 | ||
| 73 | +累计 CPU 时间。CPU 的 100% 表示一个逻辑核心满载;短于采样间隔的峰值可能漏采, | ||
| 74 | +进程树 RSS 汇总可能重复计算共享内存。`--max-rss-mib` 只在启用采样时可用, | ||
| 75 | +超限会终止本次 worker 进程树,并保留资源采样与日志。 | ||
| 76 | +同时保存 `stages.jsonl` 的阶段开始/结束时间,可以在运行过程中查看当前阶段, | ||
| 77 | +或与资源采样按时间对齐;逐文件扫描事件不写入该日志,避免过多磁盘写入。 | ||
| 78 | +文档转换使用各 worker 目录中的 `tmp` 作为临时目录。 | ||
| 79 | + | ||
| 80 | +新增阶段:在 `worker.py` 的 hooks 列表添加类、方法及稳定阶段名。 | ||
| 81 | +新增合成输入:修改 `dataset.py`,并检查 manifest 是否改变。 | ||
| 82 | +本框架使用真实的构建和 QueryEngine 链路,查询序列化只针对搜索结果列表, | ||
| 83 | +不包括 MCP 网络传输与 freshness 包装。当前不提供并发负载、增量更新或自动回归门禁。 | ||
| 84 | + | ||
| 85 | +## 全量加载与偏移按需加载对比 | ||
| 86 | + | ||
| 87 | +```powershell | ||
| 88 | +python -m benchmarks.performance.compare_search --project C:/datasets/my-project --prepare --runs 3 --warm-runs 5 | ||
| 89 | +``` | ||
| 90 | + | ||
| 91 | +`--prepare` 将已有 JSON generation 复制到新 generation,重新写入 `nodes.json` 并同步生成 | ||
| 92 | +`node_offsets.json`,不重新解析源码;两种查询方式都读取该新版本。不再生成重复的 `nodes.jsonl`。 | ||
| 93 | +交替执行 full/lazy 新进程测试,对比初始化、采样内存和连续查询,并额外各执行一次真实 CLI。 | ||
| 94 | +包含符号、文档、无命中、scope、测试代码过滤等 8 种查询;对比全部结果字段, | ||
| 95 | +仅排除随请求时间变化的 freshness.seconds_since_update。 | ||
| 96 | + | ||
| 97 | +生产 CLI 可通过 `search --search-loading auto|full|lazy` 选择路径,默认 auto。 | ||
| 98 | +仅兼容配置一致、schema 一致且有偏移文件的 JSON keyword 图谱;其他情况 auto 回退原路径。 | ||
| 99 | +lazy 强制使用按需加载,不满足条件时明确报错。 | ||
| 100 | +按需路径仍加载整个关键词索引和偏移索引,但不加载图谱节点/边、不重建非搜索辅助索引。 | ||
| 101 | +节点缓存最多 128 条,缓存记录序列化字节数预算为 8 MiB(不是精确 Python 堆内存限制)。 | ||
| 102 | +新发布的 JSON 图谱自动生成偏移文件;全量与按需路径共用 `nodes.json`,仅额外保存轻量偏移索引。 | ||
| 103 | +偏移格式 v2 明确引用 `nodes.json`;旧版 v1 的 JSONL 图谱仍可读取。偏移与节点文件必须属于同一 generation。 | ||
| 104 | +generation 完整性验证仍会流式校验文件哈希,不会将所有节点反序列化到内存。 | ||
| 105 | + | ||
| 106 | +## 持久化内存 | ||
| 107 | + | ||
| 108 | +节点、边、关键词、语义 ID 映射和 generation 元数据的 JSON 保存均采用 | ||
| 109 | +流式编码。编码使用约 64 Ki 字符的输出批次,单个大字符串 | ||
| 110 | +值可以超过该批次大小。Edge 和反向 token 集按需逐条转换,不预先生成全量副本。 | ||
| 111 | +临时文件与原子发布流程保持不变,FAISS 文件沿用原生写入。 | ||
| 112 | + | ||
| 113 | +测试保存内存时应区分原图/倒排常驻内存与序列化临时内存;加载已有图谱后的保存 | ||
| 114 | +对照不等价于完整源码构建。比较产物可在固定 `PYTHONHASHSEED` 下检查 SHA256, | ||
| 115 | +关键词集合的数组顺序受进程哈希种子影响,跨种子应比较语义及检索结果。 | ||
| 116 | + | ||
| 117 | +## embedding 文本内存 | ||
| 118 | + | ||
| 119 | +语义构建仅保留 normal/test 节点 ID;首遍逐节点检查可索引性,正式推理按批 | ||
| 120 | +重新生成文本,截到 2000 字符后送入模型。预估样本最多 50 条并使用同一推理 | ||
| 121 | +入口,内存异常可跳过预估;正式批次发生分配异常时减半重试。向量成功加入 | ||
| 122 | +FAISS 后才登记新 ID,避免失败批次在重试时被当作完成。 | ||
| 123 | + | ||
| 124 | +这会降低全量拼接文本的驻留,但仍保留图谱、BM25、ONNX 和累计 FAISS 向量; | ||
| 125 | +单个原始节点拼接仍可能产生大字符串。测量时需分别报告这些内存来源,不能 | ||
| 126 | +把合成文本准备测试或 keyword 保存测试当成完整真实语料的 embedding 峰值。 | ||
| @@ -0,0 +1 @@ | |||
| 1 | +"""Reproducible, process-isolated build and search benchmarks.""" | ||
| @@ -0,0 +1,190 @@ | |||
| 1 | +"""Prepare node sidecars without reparsing, then compare full/lazy search.""" | ||
| 2 | +from __future__ import annotations | ||
| 3 | + | ||
| 4 | +import argparse | ||
| 5 | +import hashlib | ||
| 6 | +import json | ||
| 7 | +import os | ||
| 8 | +from pathlib import Path | ||
| 9 | +import shutil | ||
| 10 | +import statistics | ||
| 11 | +import subprocess | ||
| 12 | +import sys | ||
| 13 | +import time | ||
| 14 | +from datetime import datetime, timezone | ||
| 15 | + | ||
| 16 | +from .run import REPO, percentile | ||
| 17 | +from .resources import monitored_run | ||
| 18 | + | ||
| 19 | +# Preparation also runs in the coordinator, which may have another checkout | ||
| 20 | +# installed as an editable package. Workers already receive this PYTHONPATH. | ||
| 21 | +sys.path.insert(0, str(REPO / "src")) | ||
| 22 | + | ||
| 23 | +CASES = [ | ||
| 24 | + {"query": "PyObject"}, {"query": "garbage collection"}, {"query": "asyncio"}, | ||
| 25 | + {"query": "reference counting"}, {"query": "benchmark_missing_token_98371"}, | ||
| 26 | + {"query": "PyObject", "scope": "Objects"}, | ||
| 27 | + {"query": "timeout", "test_filter": "test"}, | ||
| 28 | + {"query": "timeout", "test_filter": "all", "top_k": 5}, | ||
| 29 | +] | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +def prepare(project): | ||
| 33 | + from project_brain.graph.generation import GenerationRepository | ||
| 34 | + from project_brain.graph.offset_store import write_node_offsets | ||
| 35 | + from project_brain.paths import graph_dir | ||
| 36 | + repo = GenerationRepository(graph_dir(project), keep=3) | ||
| 37 | + active = repo.current_path() | ||
| 38 | + manifest = json.loads((active / "manifest.json").read_text(encoding="utf-8")) | ||
| 39 | + if ("node_offsets.json" in manifest["artifacts"] | ||
| 40 | + and json.loads((active / "node_offsets.json").read_text(encoding="utf-8")).get("format_version") == 2): | ||
| 41 | + return active | ||
| 42 | + | ||
| 43 | + def writer(staging): | ||
| 44 | + for name in manifest["artifacts"]: | ||
| 45 | + if name in {"nodes.json", "nodes.jsonl", "node_offsets.json"}: | ||
| 46 | + continue | ||
| 47 | + destination = staging / name | ||
| 48 | + destination.parent.mkdir(parents=True, exist_ok=True) | ||
| 49 | + shutil.copy2(active / name, destination) | ||
| 50 | + with (active / "nodes.json").open(encoding="utf-8") as stream: | ||
| 51 | + nodes = json.load(stream) | ||
| 52 | + write_node_offsets(nodes.values(), staging) | ||
| 53 | + return repo.publish(writer, metadata=manifest["metadata"]) | ||
| 54 | + | ||
| 55 | + | ||
| 56 | +def worker(request): | ||
| 57 | + from project_brain.mcp.server import ProjectBrainServer | ||
| 58 | + from .metrics import rss_bytes | ||
| 59 | + started = time.perf_counter() | ||
| 60 | + server = ProjectBrainServer(request["project"]) | ||
| 61 | + try: | ||
| 62 | + server._ensure_search_initialized(request["loading"]) | ||
| 63 | + ready = time.perf_counter() - started | ||
| 64 | + store = server._store | ||
| 65 | + reads_at_ready = getattr(store, "reads", None) | ||
| 66 | + rss_at_ready = rss_bytes() | ||
| 67 | + rows = [] | ||
| 68 | + first_digest = {} | ||
| 69 | + for iteration in range(request["warm_runs"] + 1): | ||
| 70 | + for case_id, case in enumerate(CASES): | ||
| 71 | + start = time.perf_counter() | ||
| 72 | + raw = server.call_tool_sync("keyword_search", case) | ||
| 73 | + elapsed = time.perf_counter() - start | ||
| 74 | + payload = json.loads(raw) | ||
| 75 | + payload.get("freshness", {}).pop("seconds_since_update", None) | ||
| 76 | + canonical = json.dumps(payload, sort_keys=True, ensure_ascii=False).encode() | ||
| 77 | + digest = hashlib.sha256(canonical).hexdigest() | ||
| 78 | + if iteration == 0: | ||
| 79 | + first_digest[case_id] = digest | ||
| 80 | + elif first_digest[case_id] != digest: | ||
| 81 | + raise AssertionError("Repeated search changed results") | ||
| 82 | + rows.append({"case": case_id, "iteration": iteration, "seconds": elapsed, | ||
| 83 | + "sha256": digest, "hits": payload["total"]}) | ||
| 84 | + return {"loading": request["loading"], "ready_seconds": ready, | ||
| 85 | + "rss_at_ready_bytes": rss_at_ready, "reads_at_ready": reads_at_ready, | ||
| 86 | + "node_reads": getattr(store, "reads", None), | ||
| 87 | + "cache_hits": getattr(store, "cache_hits", None), "queries": rows} | ||
| 88 | + finally: | ||
| 89 | + server.close() | ||
| 90 | + | ||
| 91 | + | ||
| 92 | +def main(): | ||
| 93 | + parser = argparse.ArgumentParser(description=__doc__) | ||
| 94 | + parser.add_argument("--project", type=Path) | ||
| 95 | + parser.add_argument("--output", type=Path, default=REPO / "benchmarks/results/offset-comparison") | ||
| 96 | + parser.add_argument("--runs", type=int, default=3) | ||
| 97 | + parser.add_argument("--warm-runs", type=int, default=5) | ||
| 98 | + parser.add_argument("--prepare", action="store_true") | ||
| 99 | + parser.add_argument("--worker", nargs=2, metavar=("REQUEST", "RESULT")) | ||
| 100 | + args = parser.parse_args() | ||
| 101 | + if args.worker: | ||
| 102 | + request_path, result_path = map(Path, args.worker) | ||
| 103 | + result = worker(json.loads(request_path.read_text(encoding="utf-8"))) | ||
| 104 | + result_path.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8") | ||
| 105 | + return | ||
| 106 | + if args.project is None or args.runs <= 0 or args.warm_runs <= 0: | ||
| 107 | + parser.error("Provide --project and positive --runs / --warm-runs") | ||
| 108 | + project = args.project.resolve() | ||
| 109 | + if args.prepare: | ||
| 110 | + print(f"Prepared: {prepare(project)}", flush=True) | ||
| 111 | + output = args.output.resolve() / datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S_%fZ") | ||
| 112 | + output.mkdir(parents=True) | ||
| 113 | + env = dict(os.environ, PYTHONPATH=os.pathsep.join([str(REPO / "src"), str(REPO)]), | ||
| 114 | + PYTHONHASHSEED="0") | ||
| 115 | + temp = output / "tmp" | ||
| 116 | + temp.mkdir() | ||
| 117 | + for key in ("TMP", "TEMP", "TMPDIR"): | ||
| 118 | + env[key] = str(temp) | ||
| 119 | + results = [] | ||
| 120 | + golden = None | ||
| 121 | + for trial in range(args.runs): | ||
| 122 | + for loading in (("full", "lazy") if trial % 2 == 0 else ("lazy", "full")): | ||
| 123 | + directory = output / f"{trial}-{loading}" | ||
| 124 | + directory.mkdir() | ||
| 125 | + request = directory / "request.json" | ||
| 126 | + target = directory / "result.json" | ||
| 127 | + request.write_text(json.dumps(dict(project=str(project), loading=loading, | ||
| 128 | + warm_runs=args.warm_runs)), encoding="utf-8") | ||
| 129 | + print(f"[{trial + 1}/{args.runs}] {loading}", flush=True) | ||
| 130 | + start = time.perf_counter() | ||
| 131 | + with (directory / "worker.log").open("w", encoding="utf-8") as log: | ||
| 132 | + code, resource = monitored_run( | ||
| 133 | + [sys.executable, "-m", "benchmarks.performance.compare_search", "--worker", str(request), str(target)], | ||
| 134 | + cwd=REPO, env=env, log=log, timeout=180, | ||
| 135 | + samples_file=directory / "resources.jsonl", max_rss_mib=8192) | ||
| 136 | + if code or resource["stop_reason"]: | ||
| 137 | + raise RuntimeError(f"Worker failed; inspect {directory}") | ||
| 138 | + result = json.loads(target.read_text(encoding="utf-8")) | ||
| 139 | + result.update(process_wall_seconds=time.perf_counter() - start, resources=resource) | ||
| 140 | + digests = [row["sha256"] for row in result["queries"]] | ||
| 141 | + if golden is None: | ||
| 142 | + golden = digests | ||
| 143 | + if golden != digests: | ||
| 144 | + raise AssertionError("Full and lazy responses differ (including rankings, scores, previews and freshness)") | ||
| 145 | + results.append(result) | ||
| 146 | + # Also time the real CLI, including argument parsing, formatting and exit. | ||
| 147 | + cli = {} | ||
| 148 | + for loading in ("full", "lazy"): | ||
| 149 | + start = time.perf_counter() | ||
| 150 | + completed = subprocess.run( | ||
| 151 | + [sys.executable, "-m", "project_brain", "--project", str(project), | ||
| 152 | + "search", "garbage collection", "--json", "--search-loading", loading], | ||
| 153 | + cwd=REPO, env=env, capture_output=True, text=True, encoding="utf-8", timeout=180) | ||
| 154 | + if completed.returncode: | ||
| 155 | + raise RuntimeError(completed.stderr) | ||
| 156 | + payload = json.loads(completed.stdout) | ||
| 157 | + payload.get("freshness", {}).pop("seconds_since_update", None) | ||
| 158 | + cli[loading] = {"seconds": time.perf_counter() - start, "payload": payload} | ||
| 159 | + assert cli["full"]["payload"] == cli["lazy"]["payload"] | ||
| 160 | + summary = {} | ||
| 161 | + for loading in ("full", "lazy"): | ||
| 162 | + runs = [row for row in results if row["loading"] == loading] | ||
| 163 | + warm = [q["seconds"] for row in runs for q in row["queries"] if q["iteration"] > 0] | ||
| 164 | + summary[loading] = {"ready_seconds": statistics.median(row["ready_seconds"] for row in runs), | ||
| 165 | + "peak_rss_mib": statistics.median(row["resources"]["peak_tree_rss_bytes"] / 1024 ** 2 for row in runs), | ||
| 166 | + "warm_p50_ms": statistics.median(warm) * 1000, | ||
| 167 | + "warm_p95_ms": percentile(warm, .95) * 1000, | ||
| 168 | + "cli_seconds": cli[loading]["seconds"]} | ||
| 169 | + report = {"project": str(project), "cases": CASES, "runs": results, | ||
| 170 | + "summary": summary, "cli": cli, "responses_identical": True, | ||
| 171 | + "note": "新进程、未清空 OS 缓存,交替顺序;按需方案同时跳过非搜索辅助索引重建。"} | ||
| 172 | + (output / "report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8") | ||
| 173 | + lines = ["# 全量加载与偏移按需加载对比", "", "同一份 CPython 图谱," + str(args.runs) + " 轮新进程测试,8 类查询,每轮连续查询 " + str(args.warm_runs) + " 遍。", "", | ||
| 174 | + "所有结果、顺序、分数、摘要和 freshness 状态完全一致;排除随请求时间变化的 seconds_since_update 字段。", "", | ||
| 175 | + "| 指标 | 全量加载 | 按需加载 |", "|---|---:|---:|"] | ||
| 176 | + for key, label, unit in [("ready_seconds", "初始化耗时中位数", "秒"), | ||
| 177 | + ("cli_seconds", "真实 CLI 单次总耗时", "秒"), | ||
| 178 | + ("peak_rss_mib", "进程 RSS 采样峰值中位数", "MiB"), | ||
| 179 | + ("warm_p50_ms", "连续查询 p50", "毫秒"), | ||
| 180 | + ("warm_p95_ms", "连续查询 p95", "毫秒")]: | ||
| 181 | + lines.append(f"| {label} | {summary['full'][key]:.3f} {unit} | {summary['lazy'][key]:.3f} {unit} |") | ||
| 182 | + lines += ["", report["note"], "", "初始化不包含依赖导入;真实 CLI 总耗时包含导入与退出,各测一次。RSS 每 0.5 秒采样。", | ||
| 183 | + "按需路径仍全量加载关键词倒排索引与轻量节点偏移索引,并保留有容量上限的节点缓存。", | ||
| 184 | + "本次只覆盖 keyword;旧图谱、配置不匹配及语义检索在 auto 模式下使用原路径。", ""] | ||
| 185 | + (output / "report.md").write_text("\n".join(lines), encoding="utf-8") | ||
| 186 | + print(f"Report: {output / 'report.md'}") | ||
| 187 | + | ||
| 188 | + | ||
| 189 | +if __name__ == "__main__": | ||
| 190 | + main() | ||
| @@ -0,0 +1,69 @@ | |||
| 1 | +"""Deterministic mixed corpora. Never modify a supplied source project.""" | ||
| 2 | +from __future__ import annotations | ||
| 3 | + | ||
| 4 | +import hashlib | ||
| 5 | +import shutil | ||
| 6 | +from pathlib import Path | ||
| 7 | + | ||
| 8 | +SIZES = {"smoke": (5, 4, 4), "small": (50, 20, 12), | ||
| 9 | + "medium": (500, 200, 24), "large": (2500, 1000, 48)} | ||
| 10 | +QUERIES = ["retry timeout", "连接池 重试", "RetryPolicy", "connection_pool", | ||
| 11 | + "architecture", "benchmark_missing_token_98371"] | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +def generate(root: Path, size: str) -> None: | ||
| 15 | + files, documents, units = SIZES[size] | ||
| 16 | + (root / "src").mkdir(parents=True) | ||
| 17 | + (root / "docs").mkdir() | ||
| 18 | + for i in range(files): | ||
| 19 | + language = i % 5 | ||
| 20 | + bodies = [] | ||
| 21 | + for j in range(units): | ||
| 22 | + name = f"retry_timeout_{i}_{j}" | ||
| 23 | + bodies.append([ | ||
| 24 | + f'def {name}(connection_pool, timeout=30):\n' | ||
| 25 | + ' """RetryPolicy: retry a connection after timeout."""\n' | ||
| 26 | + ' return connection_pool + timeout\n', | ||
| 27 | + f"pub fn {name}(connection_pool: i32, timeout: i32) -> i32 {{\n" | ||
| 28 | + " connection_pool + timeout\n}\n", | ||
| 29 | + f"int {name}(int connection_pool, int timeout) {{\n" | ||
| 30 | + " return connection_pool + timeout;\n}\n", | ||
| 31 | + f"export function {name}(connection_pool: number, timeout: number): number {{\n" | ||
| 32 | + " return connection_pool + timeout;\n}\n", | ||
| 33 | + f"func RetryTimeout{i}_{j}(connectionPool int, timeout int) int {{\n" | ||
| 34 | + " return connectionPool + timeout\n}\n", | ||
| 35 | + ][language]) | ||
| 36 | + prefix = "package benchmark\n\n" if language == 4 else "" | ||
| 37 | + ext = ["py", "rs", "c", "ts", "go"][language] | ||
| 38 | + (root / "src" / f"module_{i}.{ext}").write_text( | ||
| 39 | + prefix + "\n".join(bodies), encoding="utf-8") | ||
| 40 | + for i in range(documents): | ||
| 41 | + content = f"# Connection architecture {i}\n\n" | ||
| 42 | + for j in range(units): | ||
| 43 | + content += (f"## RetryPolicy {j}\n\n" | ||
| 44 | + f"连接池在超时后重试。连接池 重试 timeout retry connection_pool。\n\n" | ||
| 45 | + f"See `retry_timeout_{i % files}_{j}` for the retry implementation.\n\n" | ||
| 46 | + + "Connection architecture uses bounded timeout and retry budgets.\n" * 12) | ||
| 47 | + ext = "md" if i % 2 == 0 else "txt" | ||
| 48 | + (root / "docs" / f"guide_{i}.{ext}").write_text(content, encoding="utf-8") | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +def copy_project(source: Path, root: Path) -> None: | ||
| 52 | + shutil.copytree(source, root, ignore=shutil.ignore_patterns( | ||
| 53 | + ".git", ".botbrain", ".projectbrain", ".venv", "node_modules", | ||
| 54 | + "__pycache__", "target", ".pytest_cache")) | ||
| 55 | + | ||
| 56 | + | ||
| 57 | +def manifest(root: Path) -> dict: | ||
| 58 | + digest = hashlib.sha256() | ||
| 59 | + extensions: dict[str, int] = {} | ||
| 60 | + total = 0 | ||
| 61 | + for path in sorted(p for p in root.rglob("*") if p.is_file()): | ||
| 62 | + relative = path.relative_to(root).as_posix() | ||
| 63 | + content = path.read_bytes() | ||
| 64 | + digest.update(relative.encode("utf-8") + b"\0") | ||
| 65 | + digest.update(hashlib.sha256(content).digest()) | ||
| 66 | + total += len(content) | ||
| 67 | + extensions[path.suffix] = extensions.get(path.suffix, 0) + 1 | ||
| 68 | + return {"sha256": digest.hexdigest(), "files": sum(extensions.values()), | ||
| 69 | + "bytes": total, "extensions": extensions} | ||
| @@ -0,0 +1,111 @@ | |||
| 1 | +"""Inclusive/exclusive timings and boundary RSS, with no sampling thread.""" | ||
| 2 | +from __future__ import annotations | ||
| 3 | + | ||
| 4 | +from contextlib import contextmanager | ||
| 5 | +from functools import wraps | ||
| 6 | +import json | ||
| 7 | +import os | ||
| 8 | +from pathlib import Path | ||
| 9 | +import sys | ||
| 10 | +import time | ||
| 11 | +from unittest.mock import patch | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +def rss_bytes() -> int | None: | ||
| 15 | + if sys.platform == "win32": | ||
| 16 | + import ctypes | ||
| 17 | + from ctypes import wintypes | ||
| 18 | + | ||
| 19 | + class Counters(ctypes.Structure): | ||
| 20 | + _fields_ = [("cb", wintypes.DWORD), ("PageFaultCount", wintypes.DWORD)] + [ | ||
| 21 | + (name, ctypes.c_size_t) for name in ( | ||
| 22 | + "PeakWorkingSetSize", "WorkingSetSize", "QuotaPeakPagedPoolUsage", | ||
| 23 | + "QuotaPagedPoolUsage", "QuotaPeakNonPagedPoolUsage", | ||
| 24 | + "QuotaNonPagedPoolUsage", "PagefileUsage", "PeakPagefileUsage")] | ||
| 25 | + kernel = ctypes.WinDLL("kernel32", use_last_error=True) | ||
| 26 | + kernel.GetCurrentProcess.restype = wintypes.HANDLE | ||
| 27 | + psapi = ctypes.WinDLL("psapi", use_last_error=True) | ||
| 28 | + psapi.GetProcessMemoryInfo.argtypes = [wintypes.HANDLE, ctypes.POINTER(Counters), wintypes.DWORD] | ||
| 29 | + counters = Counters() | ||
| 30 | + counters.cb = ctypes.sizeof(counters) | ||
| 31 | + if psapi.GetProcessMemoryInfo(kernel.GetCurrentProcess(), ctypes.byref(counters), counters.cb): | ||
| 32 | + return counters.WorkingSetSize | ||
| 33 | + return None | ||
| 34 | + if sys.platform.startswith("linux"): | ||
| 35 | + try: | ||
| 36 | + with open("/proc/self/statm") as stream: | ||
| 37 | + return int(stream.read().split()[1]) * os.sysconf("SC_PAGE_SIZE") | ||
| 38 | + except (OSError, ValueError, IndexError): | ||
| 39 | + return None | ||
| 40 | + return None | ||
| 41 | + | ||
| 42 | + | ||
| 43 | +class Recorder: | ||
| 44 | + def __init__(self, event_path: str | None = None): | ||
| 45 | + self.rows: list[dict] = [] | ||
| 46 | + self.stack: list[dict] = [] | ||
| 47 | + self.scenario = "setup" | ||
| 48 | + self.event_path = Path(event_path) if event_path else None | ||
| 49 | + | ||
| 50 | + def _event(self, event, stage, **extra): | ||
| 51 | + if self.event_path is not None and not stage.startswith("scan."): | ||
| 52 | + with self.event_path.open("a", encoding="utf-8") as stream: | ||
| 53 | + stream.write(json.dumps(dict(event=event, stage=stage, scenario=self.scenario, | ||
| 54 | + unix_seconds=time.time(), **extra)) + "\n") | ||
| 55 | + | ||
| 56 | + @contextmanager | ||
| 57 | + def measure(self, name): | ||
| 58 | + self._event("start", name) | ||
| 59 | + before_rss = rss_bytes() | ||
| 60 | + frame = {"children": 0.0} | ||
| 61 | + self.stack.append(frame) | ||
| 62 | + cpu = time.process_time() | ||
| 63 | + start = time.perf_counter() | ||
| 64 | + status = "ok" | ||
| 65 | + try: | ||
| 66 | + yield | ||
| 67 | + except BaseException: | ||
| 68 | + status = "error" | ||
| 69 | + raise | ||
| 70 | + finally: | ||
| 71 | + elapsed = time.perf_counter() - start | ||
| 72 | + cpu_elapsed = time.process_time() - cpu | ||
| 73 | + self.stack.pop() | ||
| 74 | + after_rss = rss_bytes() | ||
| 75 | + if self.stack: | ||
| 76 | + self.stack[-1]["children"] += elapsed | ||
| 77 | + self.rows.append({"scenario": self.scenario, "stage": name, | ||
| 78 | + "seconds": elapsed, "self_seconds": max(0, elapsed - frame["children"]), | ||
| 79 | + "cpu_seconds": cpu_elapsed, "rss_before_bytes": before_rss, | ||
| 80 | + "rss_after_bytes": after_rss, "status": status}) | ||
| 81 | + self._event("end", name, status=status, seconds=elapsed) | ||
| 82 | + | ||
| 83 | + def hook(self, owner, method, label): | ||
| 84 | + original = getattr(owner, method) | ||
| 85 | + | ||
| 86 | + @wraps(original) | ||
| 87 | + def wrapped(*args, **kwargs): | ||
| 88 | + with self.measure(label): | ||
| 89 | + return original(*args, **kwargs) | ||
| 90 | + return patch.object(owner, method, wrapped) | ||
| 91 | + | ||
| 92 | + def hook_iterator(self, owner, method, label): | ||
| 93 | + """Time iterator advancement, excluding work done by its consumer.""" | ||
| 94 | + original = getattr(owner, method) | ||
| 95 | + | ||
| 96 | + @wraps(original) | ||
| 97 | + def wrapped(*args, **kwargs): | ||
| 98 | + iterator = iter(original(*args, **kwargs)) | ||
| 99 | + sentinel = object() | ||
| 100 | + try: | ||
| 101 | + while True: | ||
| 102 | + with self.measure(label): | ||
| 103 | + value = next(iterator, sentinel) | ||
| 104 | + if value is sentinel: | ||
| 105 | + return | ||
| 106 | + yield value | ||
| 107 | + finally: | ||
| 108 | + close = getattr(iterator, "close", None) | ||
| 109 | + if close: | ||
| 110 | + close() | ||
| 111 | + return patch.object(owner, method, wrapped) | ||
| @@ -0,0 +1,81 @@ | |||
| 1 | +"""Optional process-tree sampling for large-project stress runs.""" | ||
| 2 | +from __future__ import annotations | ||
| 3 | + | ||
| 4 | +import json | ||
| 5 | +from pathlib import Path | ||
| 6 | +import subprocess | ||
| 7 | +import time | ||
| 8 | + | ||
| 9 | + | ||
| 10 | +def monitored_run(command, *, cwd, env, log, timeout, samples_file: Path, max_rss_mib=None): | ||
| 11 | + import psutil | ||
| 12 | + | ||
| 13 | + start = time.monotonic() | ||
| 14 | + cpu_seen = {} | ||
| 15 | + peak_rss = 0 | ||
| 16 | + peak_cpu = 0.0 | ||
| 17 | + previous_cpu = 0.0 | ||
| 18 | + previous_time = start | ||
| 19 | + count = 0 | ||
| 20 | + reason = None | ||
| 21 | + process = subprocess.Popen(command, cwd=cwd, env=env, stdout=log, stderr=subprocess.STDOUT) | ||
| 22 | + root = psutil.Process(process.pid) | ||
| 23 | + known = {process.pid: root} | ||
| 24 | + try: | ||
| 25 | + with samples_file.open("w", encoding="utf-8") as samples: | ||
| 26 | + while True: | ||
| 27 | + now = time.monotonic() | ||
| 28 | + try: | ||
| 29 | + for child in root.children(recursive=True): | ||
| 30 | + known[child.pid] = child | ||
| 31 | + except psutil.NoSuchProcess: | ||
| 32 | + pass | ||
| 33 | + rss = 0 | ||
| 34 | + live = 0 | ||
| 35 | + for pid, observed in list(known.items()): | ||
| 36 | + try: | ||
| 37 | + memory = observed.memory_info() | ||
| 38 | + cpu = observed.cpu_times() | ||
| 39 | + key = (pid, observed.create_time()) | ||
| 40 | + cpu_seen[key] = max(cpu_seen.get(key, 0), cpu.user + cpu.system) | ||
| 41 | + rss += memory.rss | ||
| 42 | + live += 1 | ||
| 43 | + except psutil.NoSuchProcess: | ||
| 44 | + known.pop(pid, None) | ||
| 45 | + total_cpu = sum(cpu_seen.values()) | ||
| 46 | + usage = max(0.0, total_cpu - previous_cpu) / max(now - previous_time, .001) * 100 | ||
| 47 | + row = {"unix_seconds": time.time(), "elapsed_seconds": now - start, "rss_bytes": rss, | ||
| 48 | + "cpu_seconds": total_cpu, "cpu_percent": usage, "processes": live} | ||
| 49 | + samples.write(json.dumps(row) + "\n") | ||
| 50 | + samples.flush() | ||
| 51 | + count += 1 | ||
| 52 | + peak_rss = max(peak_rss, rss) | ||
| 53 | + peak_cpu = max(peak_cpu, usage) | ||
| 54 | + previous_cpu, previous_time = total_cpu, now | ||
| 55 | + if process.poll() is not None: | ||
| 56 | + break | ||
| 57 | + if max_rss_mib and rss > max_rss_mib * 1024 ** 2: | ||
| 58 | + reason = f"进程树 RSS 超过 {max_rss_mib} MiB 上限" | ||
| 59 | + break | ||
| 60 | + if now - start > timeout: | ||
| 61 | + reason = f"测试进程超过 {timeout} 秒时限" | ||
| 62 | + break | ||
| 63 | + time.sleep(.5) | ||
| 64 | + finally: | ||
| 65 | + # Stop only descendants created for this worker; preserve other apps. | ||
| 66 | + if process.poll() is None: | ||
| 67 | + try: | ||
| 68 | + descendants = root.children(recursive=True) | ||
| 69 | + except psutil.NoSuchProcess: | ||
| 70 | + descendants = [] | ||
| 71 | + for child in reversed(descendants): | ||
| 72 | + try: | ||
| 73 | + child.kill() | ||
| 74 | + except psutil.NoSuchProcess: | ||
| 75 | + pass | ||
| 76 | + process.kill() | ||
| 77 | + process.wait() | ||
| 78 | + return process.returncode, {"interval_seconds": .5, "samples": count, | ||
| 79 | + "peak_tree_rss_bytes": peak_rss, "peak_tree_cpu_percent": peak_cpu, | ||
| 80 | + "observed_tree_cpu_seconds": sum(cpu_seen.values()), | ||
| 81 | + "stop_reason": reason} | ||
| @@ -0,0 +1,283 @@ | |||
| 1 | +"""CLI coordinator; reports survive worker errors and timeouts.""" | ||
| 2 | +from __future__ import annotations | ||
| 3 | + | ||
| 4 | +import argparse | ||
| 5 | +import hashlib | ||
| 6 | +from importlib.metadata import PackageNotFoundError, version | ||
| 7 | +from collections import defaultdict | ||
| 8 | +from datetime import datetime, timezone | ||
| 9 | +import json | ||
| 10 | +import math | ||
| 11 | +import os | ||
| 12 | +from pathlib import Path | ||
| 13 | +import platform | ||
| 14 | +import statistics | ||
| 15 | +import subprocess | ||
| 16 | +import sys | ||
| 17 | +import time | ||
| 18 | + | ||
| 19 | +from .dataset import QUERIES, SIZES, copy_project, generate, manifest | ||
| 20 | + | ||
| 21 | +REPO = Path(__file__).resolve().parents[2] | ||
| 22 | + | ||
| 23 | +STAGE_LABELS = { | ||
| 24 | + "runtime.imports": "运行依赖导入", | ||
| 25 | + "session.ready": "服务创建至初始化完成", | ||
| 26 | + "startup.initialize": "服务初始化", | ||
| 27 | + "startup.query_indexes": "查询索引准备", | ||
| 28 | + "startup.schema_check": "图谱结构兼容性检查", | ||
| 29 | + "startup.capabilities": "查询能力计算", | ||
| 30 | + "build.total": "图谱构建总计", | ||
| 31 | + "build.code_parse": "源码解析", | ||
| 32 | + "build.document_parse": "文档解析", | ||
| 33 | + "build.document_convert": "文档格式转换", | ||
| 34 | + "build.document_chunks": "文档分块", | ||
| 35 | + "build.history": "Git 历史解析", | ||
| 36 | + "build.relations": "代码关系构建", | ||
| 37 | + "build.links": "文档与代码链接构建", | ||
| 38 | + "build.conventions": "项目约定提取", | ||
| 39 | + "build.projection": "图谱配置裁剪", | ||
| 40 | + "build.validation": "图谱一致性校验", | ||
| 41 | + "index.bm25_build": "BM25 索引构建", | ||
| 42 | + "index.symbol_file_build": "符号及文件索引构建", | ||
| 43 | + "index.semantic_build": "语义索引构建", | ||
| 44 | + "index.keyword_load": "关键词索引加载", | ||
| 45 | + "index.keyword_save": "关键词索引保存", | ||
| 46 | + "index.semantic_load": "语义索引加载", | ||
| 47 | + "storage.json_load": "JSON 图谱加载", | ||
| 48 | + "storage.json_save": "JSON 图谱保存", | ||
| 49 | + "storage.adjacency_build": "边邻接索引重建", | ||
| 50 | + "storage.sqlite_load": "SQLite 图谱加载", | ||
| 51 | + "storage.sqlite_publish": "SQLite 图谱及索引发布", | ||
| 52 | + "storage.publish": "图谱版本发布", | ||
| 53 | + "semantic.model_ready": "向量模型准备", | ||
| 54 | + "search.embedding": "查询向量生成", | ||
| 55 | + "search.vector": "向量检索", | ||
| 56 | + "search.bm25": "BM25 关键词检索", | ||
| 57 | + "search.retrieve": "候选结果召回", | ||
| 58 | + "search.total": "搜索引擎处理总计", | ||
| 59 | + "query.end_to_end": "查询及结果序列化总计", | ||
| 60 | + "query.serialize": "查询结果序列化", | ||
| 61 | + "scan.code": "源码文件扫描", | ||
| 62 | + "scan.doc": "文档文件扫描", | ||
| 63 | + "scan.manifest": "项目清单文件扫描", | ||
| 64 | +} | ||
| 65 | +MODE_LABELS = {"build": "构建", "query": "查询"} | ||
| 66 | +SCENARIO_LABELS = {"setup": "依赖准备", "build": "首次构建", "query": "冷启动加载", | ||
| 67 | + "first_pass": "首轮查询", "warm": "连续查询"} | ||
| 68 | + | ||
| 69 | + | ||
| 70 | +def percentile(values: list[float], fraction: float) -> float: | ||
| 71 | + ordered = sorted(values) | ||
| 72 | + return ordered[max(0, math.ceil(len(ordered) * fraction) - 1)] | ||
| 73 | + | ||
| 74 | + | ||
| 75 | +def summarize(workers: list[dict]) -> list[dict]: | ||
| 76 | + groups = defaultdict(list) | ||
| 77 | + totals = defaultdict(list) | ||
| 78 | + for worker in workers: | ||
| 79 | + per_worker = defaultdict(float) | ||
| 80 | + for row in worker.get("metrics", []): | ||
| 81 | + key = (worker["mode"], row["scenario"], row["stage"]) | ||
| 82 | + groups[key].append(row) | ||
| 83 | + per_worker[key] += row["seconds"] | ||
| 84 | + for key, total in per_worker.items(): | ||
| 85 | + totals[key].append(total) | ||
| 86 | + rows = [] | ||
| 87 | + for (mode, scenario, stage), samples in sorted(groups.items()): | ||
| 88 | + seconds = [r["seconds"] for r in samples] | ||
| 89 | + rss = [r["rss_after_bytes"] for r in samples if r["rss_after_bytes"] is not None] | ||
| 90 | + rows.append({"mode": mode, "scenario": scenario, "stage": stage, | ||
| 91 | + "calls": len(samples), "workers": len(totals[(mode, scenario, stage)]), | ||
| 92 | + "p50_ms": statistics.median(seconds) * 1000, | ||
| 93 | + "p95_ms": percentile(seconds, .95) * 1000, | ||
| 94 | + "median_worker_total_ms": statistics.median(totals[(mode, scenario, stage)]) * 1000, | ||
| 95 | + "self_total_ms": sum(r["self_seconds"] for r in samples) * 1000, | ||
| 96 | + "max_boundary_rss_bytes": max(rss) if rss else None}) | ||
| 97 | + return rows | ||
| 98 | + | ||
| 99 | + | ||
| 100 | +def launch(request: dict, directory: Path, timeout: float) -> dict: | ||
| 101 | + directory.mkdir() | ||
| 102 | + request = dict(request) | ||
| 103 | + if request.get("sample_resources"): | ||
| 104 | + request["events_file"] = str((directory / "stages.jsonl").resolve()) | ||
| 105 | + request_file, result_file = directory / "request.json", directory / "result.json" | ||
| 106 | + request_file.write_text(json.dumps(request), encoding="utf-8") | ||
| 107 | + env = dict(os.environ) | ||
| 108 | + # Always benchmark this checkout, even if another bot-brain is installed. | ||
| 109 | + env["PYTHONPATH"] = os.pathsep.join([str(REPO / "src"), str(REPO)]) | ||
| 110 | + env["PYTHONHASHSEED"] = "0" | ||
| 111 | + env["GIT_CEILING_DIRECTORIES"] = str(Path(request["project"]).parent) | ||
| 112 | + # Document converters stage snapshots via tempfile; keep them in the | ||
| 113 | + # writable benchmark directory rather than an inherited sandbox temp path. | ||
| 114 | + temp_directory = directory / "tmp" | ||
| 115 | + temp_directory.mkdir() | ||
| 116 | + for variable in ("TMP", "TEMP", "TMPDIR"): | ||
| 117 | + env[variable] = str(temp_directory.resolve()) | ||
| 118 | + start = time.perf_counter() | ||
| 119 | + try: | ||
| 120 | + with (directory / "worker.log").open("w", encoding="utf-8") as log: | ||
| 121 | + command = [sys.executable, "-m", "benchmarks.performance.worker", str(request_file), str(result_file)] | ||
| 122 | + resources = None | ||
| 123 | + if request.get("sample_resources"): | ||
| 124 | + from .resources import monitored_run | ||
| 125 | + exit_code, resources = monitored_run( | ||
| 126 | + command, cwd=REPO, env=env, log=log, timeout=timeout, | ||
| 127 | + samples_file=directory / "resources.jsonl", max_rss_mib=request.get("max_rss_mib")) | ||
| 128 | + else: | ||
| 129 | + completed = subprocess.run(command, cwd=REPO, env=env, stdout=log, | ||
| 130 | + stderr=subprocess.STDOUT, timeout=timeout, encoding="utf-8") | ||
| 131 | + exit_code = completed.returncode | ||
| 132 | + result = json.loads(result_file.read_text(encoding="utf-8")) if result_file.exists() else { | ||
| 133 | + "status": "error", "error": "Worker produced no result; inspect worker.log", "metrics": []} | ||
| 134 | + result["exit_code"] = exit_code | ||
| 135 | + if resources is not None: | ||
| 136 | + result["resources"] = resources | ||
| 137 | + if resources["stop_reason"]: | ||
| 138 | + result["status"] = "error" | ||
| 139 | + result["error"] = resources["stop_reason"] | ||
| 140 | + if exit_code: | ||
| 141 | + result["status"] = "error" | ||
| 142 | + except subprocess.TimeoutExpired: | ||
| 143 | + result = {"status": "error", "error": f"Worker timed out after {timeout}s", "metrics": []} | ||
| 144 | + result.update(mode=request["mode"], process_wall_seconds=time.perf_counter() - start) | ||
| 145 | + return result | ||
| 146 | + | ||
| 147 | + | ||
| 148 | +def markdown(report: dict) -> str: | ||
| 149 | + status = {"ok": "成功", "error": "失败"}.get(report["status"], report["status"]) | ||
| 150 | + strategy = {"keyword": "关键词检索", "hybrid": "混合检索", "semantic": "语义检索"}.get( | ||
| 151 | + report["settings"]["strategy"], report["settings"]["strategy"]) | ||
| 152 | + lines = ["# bot-brain 性能测试报告", "", f"运行状态:**{status}**", "", | ||
| 153 | + f"数据集指纹:`{report['dataset']['sha256']}`", "", | ||
| 154 | + f"数据集规模:{report['dataset']['files']} 个文件,{report['dataset']['bytes']} 字节。", "", | ||
| 155 | + f"存储后端:{report['settings']['backend']};检索策略:{strategy};" | ||
| 156 | + f"重复轮数:{report['settings']['runs']};每轮连续查询遍数:{report['settings']['warm_runs']}。", "", | ||
| 157 | + "冷启动指启动新的 Python 进程,不清空操作系统文件缓存。" | ||
| 158 | + "首轮中的多个查询共用进程,只有第一个查询包含首次查询初始化开销。" | ||
| 159 | + "计时包含性能插桩开销;父阶段耗时包含子阶段,嵌套阶段的耗时不能直接相加。", "", | ||
| 160 | + "RSS 为阶段边界的进程常驻内存快照,不是阶段内存峰值;不支持的平台显示“不可用”。" | ||
| 161 | + "原始数据中的自身耗时已扣除被插桩子阶段的耗时,仍包含未单独插桩的操作。", "", | ||
| 162 | + "p50 为单次调用耗时的中位数,p95 为第 95 百分位耗时。" | ||
| 163 | + "进程内累计耗时中位数先汇总每个测试进程内该阶段的全部调用,再对各进程取中位数。", "", | ||
| 164 | + "| 模式 / 场景 | 测试阶段 | 调用次数 | 单次 p50(毫秒) | 单次 p95(毫秒) | 进程内累计耗时中位数(毫秒) | 边界 RSS 最大值(MiB) |", | ||
| 165 | + "|---|---|---:|---:|---:|---:|---:|"] | ||
| 166 | + for row in report["summary"]: | ||
| 167 | + rss = row["max_boundary_rss_bytes"] | ||
| 168 | + memory = f"{rss / 1024 ** 2:.1f}" if rss is not None else "不可用" | ||
| 169 | + mode = MODE_LABELS.get(row["mode"], row["mode"]) | ||
| 170 | + scenario = SCENARIO_LABELS.get(row["scenario"], row["scenario"]) | ||
| 171 | + stage = STAGE_LABELS.get(row["stage"], row["stage"]) | ||
| 172 | + lines.append(f"| {mode} / {scenario} | {stage} | {row['calls']} | " | ||
| 173 | + f"{row['p50_ms']:.3f} | {row['p95_ms']:.3f} | {row['median_worker_total_ms']:.3f} | {memory} |") | ||
| 174 | + lines += ["", "## 进程实际总耗时", "", | ||
| 175 | + "包含解释器启动、依赖导入、该进程执行的全部操作及退出清理。", ""] | ||
| 176 | + for mode in ("build", "query"): | ||
| 177 | + values = [w["process_wall_seconds"] for w in report["workers"] if w["mode"] == mode] | ||
| 178 | + if values: | ||
| 179 | + lines.append(f"- {MODE_LABELS[mode]}:中位数 {statistics.median(values):.3f} 秒," | ||
| 180 | + f"p95 {percentile(values, .95):.3f} 秒。") | ||
| 181 | + for worker in report["workers"]: | ||
| 182 | + if worker.get("resources"): | ||
| 183 | + resource = worker["resources"] | ||
| 184 | + lines += ["", f"### {MODE_LABELS[worker['mode']]}进程树资源采样", "", | ||
| 185 | + f"- RSS 采样峰值:{resource['peak_tree_rss_bytes'] / 1024 ** 2:.1f} MiB。", | ||
| 186 | + f"- CPU 采样峰值:{resource['peak_tree_cpu_percent']:.1f}%(单个逻辑核心满载为 100%)。", | ||
| 187 | + f"- 观测到的累计 CPU 时间:{resource['observed_tree_cpu_seconds']:.3f} 秒。", | ||
| 188 | + "- 采样间隔 0.5 秒,短暂峰值可能漏采;进程树 RSS 汇总可能重复计算共享内存。"] | ||
| 189 | + if worker["status"] != "ok": | ||
| 190 | + lines += ["", "### 测试进程错误详情", "", | ||
| 191 | + "以下保留原始错误信息,便于排查。", "", "```text", | ||
| 192 | + worker.get("error", "测试进程执行失败"), "```"] | ||
| 193 | + return "\n".join(lines) + "\n" | ||
| 194 | + | ||
| 195 | + | ||
| 196 | +def positive_int(value: str) -> int: | ||
| 197 | + number = int(value) | ||
| 198 | + if number <= 0: | ||
| 199 | + raise argparse.ArgumentTypeError("must be positive") | ||
| 200 | + return number | ||
| 201 | + | ||
| 202 | + | ||
| 203 | +def main(argv=None) -> int: | ||
| 204 | + parser = argparse.ArgumentParser(description=__doc__) | ||
| 205 | + parser.add_argument("--size", choices=SIZES, default="small") | ||
| 206 | + parser.add_argument("--project", type=Path, help="Copy a real source/doc corpus; original is never built") | ||
| 207 | + parser.add_argument("--output", type=Path, default=REPO / "benchmarks" / "results") | ||
| 208 | + parser.add_argument("--backend", choices=["json", "sqlite"], default="json") | ||
| 209 | + parser.add_argument("--strategy", choices=["keyword", "hybrid", "semantic"], default="keyword") | ||
| 210 | + parser.add_argument("--runs", type=positive_int, default=3) | ||
| 211 | + parser.add_argument("--warm-runs", type=positive_int, default=5) | ||
| 212 | + parser.add_argument("--top-k", type=positive_int, default=20) | ||
| 213 | + parser.add_argument("--timeout", type=positive_int, default=600) | ||
| 214 | + parser.add_argument("--query", action="append", help="Repeat to override the default query suite") | ||
| 215 | + parser.add_argument("--sample-resources", action="store_true", help="Sample worker process tree; requires psutil") | ||
| 216 | + parser.add_argument("--max-rss-mib", type=positive_int, help="Stop a sampled worker above this RSS limit") | ||
| 217 | + parser.add_argument("--max-document-mib", type=positive_int, default=2) | ||
| 218 | + args = parser.parse_args(argv) | ||
| 219 | + if args.top_k > 100: | ||
| 220 | + parser.error("--top-k must be <= 100 (the query engine limit)") | ||
| 221 | + if args.max_rss_mib and not args.sample_resources: | ||
| 222 | + parser.error("--max-rss-mib requires --sample-resources") | ||
| 223 | + if args.sample_resources: | ||
| 224 | + try: | ||
| 225 | + import psutil | ||
| 226 | + except ImportError: | ||
| 227 | + parser.error("--sample-resources requires psutil") | ||
| 228 | + if args.project: | ||
| 229 | + args.project = args.project.resolve() | ||
| 230 | + if not args.project.is_dir(): | ||
| 231 | + parser.error("--project must be a directory") | ||
| 232 | + if args.output.resolve().is_relative_to(args.project): | ||
| 233 | + parser.error("--output must be outside --project to avoid recursive copying") | ||
| 234 | + output = args.output.resolve() / datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S_%fZ") | ||
| 235 | + output.mkdir(parents=True, exist_ok=False) | ||
| 236 | + settings = {key: getattr(args, key) for key in ( | ||
| 237 | + "size", "backend", "strategy", "runs", "warm_runs", "top_k", "timeout", | ||
| 238 | + "sample_resources", "max_rss_mib", "max_document_mib")} | ||
| 239 | + report = {"schema_version": 1, "status": "ok", "settings": settings, | ||
| 240 | + "environment": {"python": sys.version, "executable": sys.executable, | ||
| 241 | + "platform": platform.platform(), "checkout": str(REPO)}, | ||
| 242 | + "queries": args.query or QUERIES, "workers": [], "summary": []} | ||
| 243 | + report["environment"]["dependencies"] = {} | ||
| 244 | + implementation = hashlib.sha256() | ||
| 245 | + for path in sorted((REPO / "src" / "project_brain").rglob("*.py")): | ||
| 246 | + implementation.update(path.relative_to(REPO).as_posix().encode() + b"\0") | ||
| 247 | + implementation.update(hashlib.sha256(path.read_bytes()).digest()) | ||
| 248 | + report["environment"]["implementation_sha256"] = implementation.hexdigest() | ||
| 249 | + for package in ("mcp", "tree-sitter", "markitdown", "numpy", "fastembed", "faiss-cpu"): | ||
| 250 | + try: | ||
| 251 | + report["environment"]["dependencies"][package] = version(package) | ||
| 252 | + except PackageNotFoundError: | ||
| 253 | + report["environment"]["dependencies"][package] = None | ||
| 254 | + for iteration in range(args.runs): | ||
| 255 | + corpus = output / f"corpus_{iteration}" | ||
| 256 | + if args.project: | ||
| 257 | + copy_project(args.project, corpus) | ||
| 258 | + else: | ||
| 259 | + generate(corpus, args.size) | ||
| 260 | + inventory = manifest(corpus) | ||
| 261 | + if iteration == 0: | ||
| 262 | + report["dataset"] = inventory | ||
| 263 | + elif inventory != report["dataset"]: | ||
| 264 | + raise RuntimeError("Dataset changed between repetitions") | ||
| 265 | + for mode in ("build", "query"): | ||
| 266 | + print(f"[{iteration + 1}/{args.runs}] {mode}: {corpus}", flush=True) | ||
| 267 | + request = dict(settings, mode=mode, project=str(corpus), queries=report["queries"]) | ||
| 268 | + worker = launch(request, output / f"{mode}_{iteration}", args.timeout) | ||
| 269 | + report["workers"].append(worker) | ||
| 270 | + if worker["status"] != "ok": | ||
| 271 | + report["status"] = "error" | ||
| 272 | + break | ||
| 273 | + if report["status"] != "ok": | ||
| 274 | + break | ||
| 275 | + report["summary"] = summarize(report["workers"]) | ||
| 276 | + (output / "report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8") | ||
| 277 | + (output / "report.md").write_text(markdown(report), encoding="utf-8") | ||
| 278 | + print(f"Report ({report['status']}): {output / 'report.md'}") | ||
| 279 | + return 0 if report["status"] == "ok" else 1 | ||
| 280 | + | ||
| 281 | + | ||
| 282 | +if __name__ == "__main__": | ||
| 283 | + raise SystemExit(main()) | ||
| @@ -0,0 +1,134 @@ | |||
| 1 | +"""Private worker: invoked with the same interpreter in a fresh process.""" | ||
| 2 | +from __future__ import annotations | ||
| 3 | + | ||
| 4 | +from contextlib import ExitStack | ||
| 5 | +import json | ||
| 6 | +from pathlib import Path | ||
| 7 | +import sys | ||
| 8 | +import traceback | ||
| 9 | + | ||
| 10 | +from .metrics import Recorder, rss_bytes | ||
| 11 | + | ||
| 12 | + | ||
| 13 | +def run(request: dict) -> dict: | ||
| 14 | + recorder = Recorder(request.get("events_file")) | ||
| 15 | + with recorder.measure("runtime.imports"): | ||
| 16 | + from project_brain.config import Config | ||
| 17 | + from project_brain.mcp.server import ProjectBrainServer | ||
| 18 | + from project_brain.graph.json_store import JsonStore | ||
| 19 | + from project_brain.graph.sqlite_store import SqliteStore | ||
| 20 | + from project_brain.query.index import KeywordIndex | ||
| 21 | + from project_brain.query.engine import QueryEngine | ||
| 22 | + from project_brain.query.semantic_index import SemanticIndex | ||
| 23 | + from project_brain.build.builder import GraphBuilder | ||
| 24 | + from project_brain.build.code_parser import CodeParser | ||
| 25 | + from project_brain.build.scanner import FileScanner | ||
| 26 | + from project_brain.build.doc_parser import DocumentParser | ||
| 27 | + from project_brain.build.history_parser import HistoryParser | ||
| 28 | + from project_brain.build.relation_resolver import RelationResolver | ||
| 29 | + from project_brain.build.link_engine import LinkEngine | ||
| 30 | + from project_brain.build.convention import ConventionExtractor | ||
| 31 | + from project_brain.graph.generation import GenerationRepository | ||
| 32 | + from project_brain.graph import validation | ||
| 33 | + root = Path(request["project"]) | ||
| 34 | + mode = request["mode"] | ||
| 35 | + recorder.scenario = mode | ||
| 36 | + result = {"mode": mode, "metrics": recorder.rows, "queries": [], "status": "ok"} | ||
| 37 | + hooks = [ | ||
| 38 | + (ProjectBrainServer, "_initialize", "startup.initialize"), | ||
| 39 | + (ProjectBrainServer, "_rebuild_indexes", "startup.query_indexes"), | ||
| 40 | + (ProjectBrainServer, "_requires_relation_fact_rebuild", "startup.schema_check"), | ||
| 41 | + (ProjectBrainServer, "_refresh_capabilities", "startup.capabilities"), | ||
| 42 | + (GraphBuilder, "build_all", "build.total"), | ||
| 43 | + (validation, "validate_graph_state", "build.validation"), | ||
| 44 | + (CodeParser, "parse_all", "build.code_parse"), | ||
| 45 | + (DocumentParser, "parse_file", "build.document_parse"), | ||
| 46 | + (HistoryParser, "parse", "build.history"), | ||
| 47 | + (RelationResolver, "replace_all", "build.relations"), | ||
| 48 | + (DocumentParser, "_convert_snapshot_to_markdown", "build.document_convert"), | ||
| 49 | + (DocumentParser, "_build_chunks", "build.document_chunks"), | ||
| 50 | + (LinkEngine, "replace_all_links", "build.links"), | ||
| 51 | + (ConventionExtractor, "extract_all", "build.conventions"), | ||
| 52 | + (GraphBuilder, "_apply_profile_projection", "build.projection"), | ||
| 53 | + (GraphBuilder, "rebuild_bm25_index", "index.bm25_build"), | ||
| 54 | + (GraphBuilder, "rebuild_symbol_file_indexes", "index.symbol_file_build"), | ||
| 55 | + (GraphBuilder, "build_semantic_index", "index.semantic_build"), | ||
| 56 | + (JsonStore, "load", "storage.json_load"), | ||
| 57 | + (JsonStore, "_rebuild_edge_indexes", "storage.adjacency_build"), | ||
| 58 | + (JsonStore, "save", "storage.json_save"), | ||
| 59 | + (SqliteStore, "load", "storage.sqlite_load"), | ||
| 60 | + (KeywordIndex, "load", "index.keyword_load"), | ||
| 61 | + (KeywordIndex, "save", "index.keyword_save"), | ||
| 62 | + (GenerationRepository, "publish_graph_state", "storage.publish"), | ||
| 63 | + (ProjectBrainServer, "_persist_sqlite_state", "storage.sqlite_publish"), | ||
| 64 | + (SemanticIndex, "load", "index.semantic_load"), | ||
| 65 | + (SemanticIndex, "_embed", "search.embedding"), | ||
| 66 | + (SemanticIndex, "_ensure_model", "semantic.model_ready"), | ||
| 67 | + (SemanticIndex, "search", "search.vector"), | ||
| 68 | + (KeywordIndex, "search", "search.bm25"), | ||
| 69 | + (QueryEngine, "_retrieve", "search.retrieve"), | ||
| 70 | + (QueryEngine, "keyword_search", "search.total"), | ||
| 71 | + ] | ||
| 72 | + server = None | ||
| 73 | + try: | ||
| 74 | + if mode == "build": | ||
| 75 | + config = Config(search_strategy=request["strategy"], storage_backend=request["backend"], | ||
| 76 | + parser_semantic_backend="off", watcher_enabled=False, index_body=True, | ||
| 77 | + document_content_include=["**"], | ||
| 78 | + document_content_max_file_bytes=request.get("max_document_mib", 2) * 1024 ** 2, | ||
| 79 | + document_content_max_total_bytes=1024 ** 3) | ||
| 80 | + config.save(str(root)) | ||
| 81 | + with ExitStack() as stack: | ||
| 82 | + for owner, method, label in hooks: | ||
| 83 | + stack.enter_context(recorder.hook(owner, method, label)) | ||
| 84 | + for kind in ("code", "doc", "manifest"): | ||
| 85 | + stack.enter_context(recorder.hook_iterator( | ||
| 86 | + FileScanner, f"scan_{kind}_files", f"scan.{kind}")) | ||
| 87 | + with recorder.measure("session.ready"): | ||
| 88 | + server = ProjectBrainServer(str(root)) | ||
| 89 | + server._ensure_initialized(start_watcher=False, read_only=True) | ||
| 90 | + if mode == "query" and any(row["stage"] == "build.total" for row in recorder.rows): | ||
| 91 | + raise RuntimeError("Cold query rebuilt the graph; this is not a valid load benchmark") | ||
| 92 | + if mode == "query": | ||
| 93 | + # Each query is measured once in the first pass, then repeatedly warm. | ||
| 94 | + for iteration in range(request["warm_runs"] + 1): | ||
| 95 | + recorder.scenario = "first_pass" if iteration == 0 else "warm" | ||
| 96 | + for query in request["queries"]: | ||
| 97 | + sample_start = len(recorder.rows) | ||
| 98 | + with recorder.measure("query.end_to_end"): | ||
| 99 | + hits = server._query_engine.keyword_search(query, top_k=request["top_k"]) | ||
| 100 | + with recorder.measure("query.serialize"): | ||
| 101 | + payload = json.dumps(hits, ensure_ascii=False) | ||
| 102 | + result["queries"].append({"query": query, "iteration": iteration, | ||
| 103 | + "hits": len(hits), "response_bytes": len(payload.encode()), | ||
| 104 | + "metric_start": sample_start, | ||
| 105 | + "metric_end": len(recorder.rows)}) | ||
| 106 | + # Count only after queries: SQLite full scans would otherwise warm | ||
| 107 | + # its page cache and materialize the graph before the first search. | ||
| 108 | + result["graph"] = {"nodes": len(server._store.get_all_nodes()), | ||
| 109 | + "edges": len(server._store.get_all_edges()), | ||
| 110 | + "stored_documents": sum(n.get("content_complete") is True | ||
| 111 | + for n in server._store.get_nodes_by_type("document")), | ||
| 112 | + "semantic_stale": server._query_engine.semantic_stale} | ||
| 113 | + if mode == "build" and (server._indexed_build_partial or server._query_engine.semantic_stale): | ||
| 114 | + raise RuntimeError("Build degraded or semantic index unavailable; refusing a misleading success") | ||
| 115 | + except Exception: | ||
| 116 | + result.update(status="error", error=traceback.format_exc()) | ||
| 117 | + finally: | ||
| 118 | + if server is not None: | ||
| 119 | + server.close() | ||
| 120 | + result["rss_final_bytes"] = rss_bytes() | ||
| 121 | + artifacts = list((root / ".botbrain" / "graph").rglob("*")) | ||
| 122 | + result["artifacts"] = {p.relative_to(root / ".botbrain").as_posix(): p.stat().st_size | ||
| 123 | + for p in artifacts if p.is_file()} | ||
| 124 | + return result | ||
| 125 | + | ||
| 126 | + | ||
| 127 | +if __name__ == "__main__": | ||
| 128 | + request_file, output_file = map(Path, sys.argv[1:]) | ||
| 129 | + try: | ||
| 130 | + outcome = run(json.loads(request_file.read_text(encoding="utf-8"))) | ||
| 131 | + except Exception: | ||
| 132 | + outcome = {"status": "error", "error": traceback.format_exc(), "metrics": []} | ||
| 133 | + output_file.write_text(json.dumps(outcome, ensure_ascii=False, indent=2), encoding="utf-8") | ||
| 134 | + sys.exit(0 if outcome["status"] == "ok" else 1) | ||
| @@ -165,6 +165,10 @@ Knowledge Graph: | |||
| 165 | bot-brain search "订单超时" | 165 | bot-brain search "订单超时" |
| 166 | bot-brain search "timeout" --top-k 5 | 166 | bot-brain search "timeout" --top-k 5 |
| 167 | 167 | ||
| 168 | +# 对比节点全量加载与按需读取(JSON 后端、keyword 策略) | ||
| 169 | +bot-brain search "timeout" --search-loading full | ||
| 170 | +bot-brain search "timeout" --search-loading lazy | ||
| 171 | + | ||
| 168 | # 按名定位符号 | 172 | # 按名定位符号 |
| 169 | bot-brain locate OrderService | 173 | bot-brain locate OrderService |
| 170 | bot-brain locate Poll --kind class | 174 | bot-brain locate Poll --kind class |
| @@ -193,6 +197,109 @@ bot-brain search "config" --json | |||
| 193 | 197 | ||
| 194 | 用 `bot-brain --help` 查看所有命令。 | 198 | 用 `bot-brain --help` 查看所有命令。 |
| 195 | 199 | ||
| 200 | +### 7.1 search 的全量加载与按需读取 | ||
| 201 | + | ||
| 202 | +以下选项需要使用包含 JSON 偏移索引优化的版本。若 `bot-brain search --help` | ||
| 203 | +没有 `--search-loading`,需先升级到该实现;只同步本指南不会改变旧版程序行为。 | ||
| 204 | + | ||
| 205 | +```bash | ||
| 206 | +bot-brain search "timeout" --search-loading auto # 默认,自动选择 | ||
| 207 | +bot-brain search "timeout" --search-loading full # 强制完整初始化 | ||
| 208 | +bot-brain search "timeout" --search-loading lazy # 强制按需读取,不兼容时报错 | ||
| 209 | +``` | ||
| 210 | + | ||
| 211 | +`auto` 仅在 JSON 后端、全局配置为 `keyword`、图谱 schema 与配置摘要一致, | ||
| 212 | +且有兼容的节点偏移索引时启用按需路径。SQLite、hybrid/semantic、缺少索引或 | ||
| 213 | +配置不兼容时回退原初始化路径;它不会因一次查询临时指定 keyword 就忽略 | ||
| 214 | +全局策略的限制。目前这项优化只接入独立 CLI `search`,其他命令仍沿用原路径。 | ||
| 215 | + | ||
| 216 | +新构建将节点写入 `nodes.json` 时同步生成 `node_offsets.json`: | ||
| 217 | + | ||
| 218 | +```text | ||
| 219 | +BM25 倒排检索 → 候选节点 ID → 节点缓存 | ||
| 220 | + ↓ 未命中 | ||
| 221 | + 偏移索引中的 [字节位置, 长度] | ||
| 222 | + ↓ | ||
| 223 | + seek/read nodes.json → 只解析该节点 | ||
| 224 | +``` | ||
| 225 | + | ||
| 226 | +偏移只覆盖外层 ID 键对应的节点对象,不包括键名或分隔逗号;中文、emoji | ||
| 227 | +和换行按 UTF-8 字节计数。新格式 v2 明确指向 `nodes.json`,无需重复保存 | ||
| 228 | +`nodes.jsonl`;旧格式 v1 的 JSONL 图谱仍兼容。节点数据与偏移索引属于同一 | ||
| 229 | +不可变 generation,不能手工修改节点文件后继续使用旧偏移。 | ||
| 230 | + | ||
| 231 | +按需初始化仍完整加载 `keyword_index.json` 和轻量偏移索引;不全量反序列化 | ||
| 232 | +`nodes.json` / `edges.json`,不重建非搜索辅助索引。命中后的文件路径、文档 | ||
| 233 | +正文等关联信息也通过节点 ID 读取。generation 完整性校验仍会流式读取文件 | ||
| 234 | +计算哈希,因此避免全量反序列化不等于避免所有全文件 I/O。 | ||
| 235 | + | ||
| 236 | +**已加载就复用**:同一个服务实例已加载完整图谱时,search 直接查询内存 | ||
| 237 | +中的节点字典,不切换到按需文件读取。GUI 若通过该服务查询也能复用;独立 | ||
| 238 | +CLI 不会自动连接已运行的 `serve`,两者不能直接共享 Python 内存。 | ||
| 239 | + | ||
| 240 | +### 7.2 搜索启动与性能验证 | ||
| 241 | + | ||
| 242 | +```bash | ||
| 243 | +time bot-brain search 重试 # 含启动 | ||
| 244 | +echo 'search 重试' | bot-brain repl # 常驻进程内查询 | ||
| 245 | +``` | ||
| 246 | + | ||
| 247 | +独立 CLI 的总耗时包含进程启动、依赖导入、图谱初始化和查询。REPL 第一次 | ||
| 248 | +查询也包含初始化,不能直接把上面两条命令的耗时差当作纯启动开销;应在 | ||
| 249 | +同一个 REPL / 服务实例中重复查询,单独比较初始化和后续查询的耗时。 | ||
| 250 | + | ||
| 251 | +JSON keyword 场景可在同一图谱上分别运行 `--search-loading full` 与 `lazy` | ||
| 252 | +进行比较。按需方式主要减少新进程初始化与内存占用;连续查询仍可能因为 | ||
| 253 | +随机读取和单节点反序列化略慢,不能保证每条查询都更快。 | ||
| 254 | + | ||
| 255 | +CPython 实测参考:167,105 个节点,3 轮新进程、8 类查询,每类再连续查询 | ||
| 256 | +5 遍;未清空操作系统文件缓存,full/lazy 交替顺序。两种方式的 288 次查询 | ||
| 257 | +及 2 次真实 CLI 查询结果一致(仅排除随时间变化的 freshness 年龄字段)。 | ||
| 258 | + | ||
| 259 | +| 指标 | 全量加载 | 按需加载 | | ||
| 260 | +|---|---:|---:| | ||
| 261 | +| 初始化耗时中位数(不含依赖导入) | 14.66 秒 | 4.37 秒 | | ||
| 262 | +| 真实 CLI 总耗时(各测一次) | 18.15 秒 | 5.71 秒 | | ||
| 263 | +| RSS 采样峰值中位数(每 0.5 秒采样) | 4015 MiB | 2005 MiB | | ||
| 264 | +| 连续查询 p50 | 1.85 ms | 2.89 ms | | ||
| 265 | +| 连续查询 p95 | 43.77 ms | 44.85 ms | | ||
| 266 | + | ||
| 267 | +全部 167,105 个节点另按偏移逐个读取,与全量解析结果一致;新增偏移索引 | ||
| 268 | +约 5.67 MiB,不再生成 JSONL 节点副本。这是该机器和语料的观测结果, | ||
| 269 | +不代表其他仓库的固定耗时,也不是清空磁盘缓存后的测试。 | ||
| 270 | + | ||
| 271 | +### 7.3 构建时的流式保存 | ||
| 272 | + | ||
| 273 | +图谱 JSON 持久化使用流式编码:`nodes.json` 增量编码节点; | ||
| 274 | +`edges.json` 每次仅转换一条 Edge;`keyword_index.json` 迭代编码 | ||
| 275 | +倒排、文本和长度表,反向 token 集每次只转换一个集合。普通 `JsonStore.save` | ||
| 276 | +和 generation 发布均使用此保存路径。 | ||
| 277 | + | ||
| 278 | +语义索引的 `semantic_ids.json` 和 generation 元数据同样 | ||
| 279 | +迭代编码。通用写入器以约 64 Ki 字符批量输出;单个大字符串值可能超过此 | ||
| 280 | +批量大小。文件格式保持兼容,临时文件完成后原子替换,完整 generation | ||
| 281 | +仍在全部产物写入并校验后发布。FAISS 二进制沿用其原生文件写入接口。 | ||
| 282 | + | ||
| 283 | +这项优化减少保存阶段的大字符串、全量边字典列表和全量 token 列表副本。 | ||
| 284 | +节点 dict、边列表及 BM25 仍在构建内存中,不会因为某条记录写完就删除; | ||
| 285 | +因此它不等同于按需构建、流式加载或降低服务常驻图谱的内存。 | ||
| 286 | + | ||
| 287 | +### 7.4 embedding 的批次内存 | ||
| 288 | + | ||
| 289 | +语义构建先逐节点检查可索引文本,只保留 normal/test 节点 ID,不保留全量 | ||
| 290 | +`normal_contents` / `test_contents`。推理时再按 ID 获取当前批次,生成文本并 | ||
| 291 | +截断为前 2000 字符,批次完成后释放临时文本。实体名称、签名、说明及配置 | ||
| 292 | +选中的正文仍参与文本生成,输入内容与此前相同;未改成只嵌入名称。 | ||
| 293 | + | ||
| 294 | +默认每批 256 条。耗时预估最多准备 50 条,并复用正式推理的截断入口; | ||
| 295 | +预估发生内存异常时跳过预估。正式批次遇到可识别的分配错误或 `MemoryError` | ||
| 296 | +时减半重试,最低到 1;其他错误继续上报。已完成节点不会重复嵌入。 | ||
| 297 | + | ||
| 298 | +首遍检查与按批生成会再次读取有效节点,换取更低的文本驻留内存。单个节点 | ||
| 299 | +的文本仍可能短暂大于 2000 字符,截断发生在拼接后。完整图谱、BM25、模型 | ||
| 300 | +及累计 FAISS 向量仍驻留内存,这项优化不提供进程内存硬上限,也不实现索引 | ||
| 301 | +分片。`build --threads 2` 可以降低推理线程数,具体吞吐与峰值需实测。 | ||
| 302 | + | ||
| 196 | ### 拉取华为内源 Wiki | 303 | ### 拉取华为内源 Wiki |
| 197 | 304 | ||
| 198 | ```bash | 305 | ```bash |
| @@ -899,7 +899,10 @@ def _cmd_query(project_path: Path, args): | |||
| 899 | kwargs = {k: v for k, v in kwargs.items() if v is not None} | 899 | kwargs = {k: v for k, v in kwargs.items() if v is not None} |
| 900 | 900 | ||
| 901 | server = ProjectBrainServer(str(project_path)) | 901 | server = ProjectBrainServer(str(project_path)) |
| 902 | - server._ensure_initialized(start_watcher=False, read_only=True) | 902 | + if args.command == "search": |
| 903 | + server._ensure_search_initialized(getattr(args, "search_loading", "auto")) | ||
| 904 | + else: | ||
| 905 | + server._ensure_initialized(start_watcher=False, read_only=True) | ||
| 903 | 906 | ||
| 904 | tool_name = spec["tool"] | 907 | tool_name = spec["tool"] |
| 905 | if tool_name not in server.tool_names: | 908 | if tool_name not in server.tool_names: |
| @@ -911,6 +914,8 @@ def _cmd_query(project_path: Path, args): | |||
| 911 | except TypeError as e: | 914 | except TypeError as e: |
| 912 | print(f"Error: invalid arguments for '{tool_name}': {e}", file=sys.stderr) | 915 | print(f"Error: invalid arguments for '{tool_name}': {e}", file=sys.stderr) |
| 913 | sys.exit(1) | 916 | sys.exit(1) |
| 917 | + finally: | ||
| 918 | + server.close() | ||
| 914 | 919 | ||
| 915 | result = json.loads(raw) if isinstance(raw, str) else raw | 920 | result = json.loads(raw) if isinstance(raw, str) else raw |
| 916 | # Business errors (e.g. "Module not found", "Symbol not found") return | 921 | # Business errors (e.g. "Module not found", "Symbol not found") return |
| @@ -929,6 +934,8 @@ _QUERY_SPECS = { | |||
| 929 | "help": "Keyword/semantic search for code symbols", | 934 | "help": "Keyword/semantic search for code symbols", |
| 930 | "args": [ | 935 | "args": [ |
| 931 | {"flags": ["query"], "opts": {"help": "search query"}}, | 936 | {"flags": ["query"], "opts": {"help": "search query"}}, |
| 937 | + {"flags": ["--search-loading"], "opts": {"choices": ["auto", "full", "lazy"], | ||
| 938 | + "default": "auto", "help": "Node loading mode; auto uses offsets for compatible keyword graphs"}}, | ||
| 932 | {"flags": ["--top-k"], "opts": {"type": int, "default": 20}}, | 939 | {"flags": ["--top-k"], "opts": {"type": int, "default": 20}}, |
| 933 | {"flags": ["--scope"], "opts": {"default": None}}, | 940 | {"flags": ["--scope"], "opts": {"default": None}}, |
| 934 | {"flags": ["--test-filter"], "opts": {"default": "normal", | 941 | {"flags": ["--test-filter"], "opts": {"default": "normal", |
| @@ -578,16 +578,10 @@ class GraphBuilder: | |||
| 578 | return | 578 | return |
| 579 | sem = self.semantic_index | 579 | sem = self.semantic_index |
| 580 | 580 | ||
| 581 | - # Split nodes into normal / test buckets. | 581 | + # Retain only IDs. Eligibility is checked one node at a time so index |
| 582 | + # selection/counts stay identical, without retaining all joined texts. | ||
| 582 | normal_ids: list[str] = [] | 583 | normal_ids: list[str] = [] |
| 583 | - normal_contents: list[str] = [] | ||
| 584 | test_ids: list[str] = [] | 584 | test_ids: list[str] = [] |
| 585 | - test_contents: list[str] = [] | ||
| 586 | - documents_by_id = { | ||
| 587 | - document.get("id"): document | ||
| 588 | - for document in self.store.get_nodes_by_type("document") | ||
| 589 | - if document.get("id") | ||
| 590 | - } | ||
| 591 | for node_type in _INDEXABLE_TYPES: | 585 | for node_type in _INDEXABLE_TYPES: |
| 592 | for node in self.store.get_nodes_by_type(node_type): | 586 | for node in self.store.get_nodes_by_type(node_type): |
| 593 | if self._skip_index_node(node_type, node): | 587 | if self._skip_index_node(node_type, node): |
| @@ -596,19 +590,13 @@ class GraphBuilder: | |||
| 596 | node, | 590 | node, |
| 597 | self.config.index_body, | 591 | self.config.index_body, |
| 598 | store=self.store, | 592 | store=self.store, |
| 599 | - parent_document=( | ||
| 600 | - documents_by_id.get(node.get("doc_id")) | ||
| 601 | - if node_type == "document_chunk" | ||
| 602 | - else None | ||
| 603 | - ), | ||
| 604 | ) | 593 | ) |
| 605 | if text and text.strip(): | 594 | if text and text.strip(): |
| 606 | if node_type == "function" and node.get("is_test"): | 595 | if node_type == "function" and node.get("is_test"): |
| 607 | test_ids.append(node["id"]) | 596 | test_ids.append(node["id"]) |
| 608 | - test_contents.append(text) | ||
| 609 | else: | 597 | else: |
| 610 | normal_ids.append(node["id"]) | 598 | normal_ids.append(node["id"]) |
| 611 | - normal_contents.append(text) | 599 | + del text |
| 612 | 600 | ||
| 613 | total = len(normal_ids) + len(test_ids) | 601 | total = len(normal_ids) + len(test_ids) |
| 614 | if total == 0: | 602 | if total == 0: |
| @@ -619,7 +607,24 @@ class GraphBuilder: | |||
| 619 | f"test={len(test_ids)}, type={sem.normal._index_type}/" | 607 | f"test={len(test_ids)}, type={sem.normal._index_type}/" |
| 620 | f"{sem.test._index_type})...") | 608 | f"{sem.test._index_type})...") |
| 621 | 609 | ||
| 622 | - def _embed_bucket(idx, doc_ids, contents, label): | 610 | + def _contents(doc_ids): |
| 611 | + texts = [] | ||
| 612 | + for node_id in doc_ids: | ||
| 613 | + node = self.store.get_node(node_id) | ||
| 614 | + if node is None: | ||
| 615 | + raise GraphBuildError(f"semantic input node disappeared: {node_id}") | ||
| 616 | + text = QueryEngine._index_text( | ||
| 617 | + node, self.config.index_body, store=self.store, | ||
| 618 | + ) | ||
| 619 | + texts.append((text or "")[:SemanticIndex.MAX_TEXT_CHARS]) | ||
| 620 | + return texts | ||
| 621 | + | ||
| 622 | + def _is_memory_error(exc): | ||
| 623 | + return isinstance(exc, MemoryError) or any( | ||
| 624 | + word in str(exc).lower() for word in ("alloc", "memory") | ||
| 625 | + ) | ||
| 626 | + | ||
| 627 | + def _embed_bucket(idx, doc_ids, label): | ||
| 623 | bucket_total = len(doc_ids) | 628 | bucket_total = len(doc_ids) |
| 624 | if bucket_total == 0: | 629 | if bucket_total == 0: |
| 625 | return | 630 | return |
| @@ -627,11 +632,27 @@ class GraphBuilder: | |||
| 627 | pending = bucket_total - already | 632 | pending = bucket_total - already |
| 628 | if already: | 633 | if already: |
| 629 | p(f" {label}: resuming {already}/{bucket_total}, {pending} pending") | 634 | p(f" {label}: resuming {already}/{bucket_total}, {pending} pending") |
| 635 | + batch_size = SemanticIndex.EMBED_BATCH_SIZE | ||
| 630 | if pending > 0: | 636 | if pending > 0: |
| 631 | - pending_contents = [c for d, c in zip(doc_ids, contents) if not idx.has(d)] | 637 | + # A small bounded sample, never a full pending-content list. |
| 632 | - est, speed = sem.estimate_embed_time(pending_contents, pending) | 638 | + sample_ids = [] |
| 633 | - del pending_contents # release the copy before the embed loop | 639 | + for node_id in doc_ids: |
| 634 | - p(f" Embedding {label} {pending} texts (est. ~{est:.0f}s at {speed:.0f}/s)...") | 640 | + if not idx.has(node_id): |
| 641 | + sample_ids.append(node_id) | ||
| 642 | + if len(sample_ids) >= min(50, batch_size): | ||
| 643 | + break | ||
| 644 | + try: | ||
| 645 | + sample = _contents(sample_ids) | ||
| 646 | + est, speed = sem.estimate_embed_time(sample, pending) | ||
| 647 | + p(f" Embedding {label} {pending} texts (est. ~{est:.0f}s at {speed:.0f}/s)...") | ||
| 648 | + except (MemoryError, RuntimeError) as exc: | ||
| 649 | + if not _is_memory_error(exc): | ||
| 650 | + raise | ||
| 651 | + # Calibration is optional; actual inference has its own | ||
| 652 | + # per-batch backoff below and uses the same embed path. | ||
| 653 | + p(f" {label}: skipping speed estimate after memory error") | ||
| 654 | + finally: | ||
| 655 | + sample = None | ||
| 635 | 656 | ||
| 636 | batch_n = {"n": 0} | 657 | batch_n = {"n": 0} |
| 637 | 658 | ||
| @@ -644,23 +665,21 @@ class GraphBuilder: | |||
| 644 | sem.save(str(self.pb_dir)) | 665 | sem.save(str(self.pb_dir)) |
| 645 | batch_n["n"] = 0 | 666 | batch_n["n"] = 0 |
| 646 | 667 | ||
| 647 | - # ONNX inference on Windows can intermittently raise a memory | 668 | + # Retry only the current bounded batch. A failed batch must never |
| 648 | - # allocation failure ("bad allocation") on large batches. Retry | 669 | + # cause every remaining node's text to be prepared in advance. |
| 649 | - # with progressively smaller batches; already-embedded ids are | 670 | + cursor = 0 |
| 650 | - # skipped by add_many_batches (resume support), so each retry only | 671 | + done = 0 |
| 651 | - # re-attempts the remaining pending texts. | 672 | + while cursor < bucket_total: |
| 652 | - batch_size = SemanticIndex.EMBED_BATCH_SIZE | 673 | + chunk = doc_ids[cursor:cursor + batch_size] |
| 653 | - while True: | 674 | + batch_ids = [node_id for node_id in chunk if not idx.has(node_id)] |
| 675 | + if not batch_ids: | ||
| 676 | + cursor += len(chunk) | ||
| 677 | + continue | ||
| 654 | try: | 678 | try: |
| 655 | - idx.add_many_batches( | 679 | + contents = _contents(batch_ids) |
| 656 | - doc_ids, contents, | 680 | + idx.add_many(batch_ids, contents) |
| 657 | - batch_size=batch_size, | 681 | + except (MemoryError, RuntimeError) as exc: |
| 658 | - on_batch=_on_batch, | 682 | + if not _is_memory_error(exc): |
| 659 | - ) | ||
| 660 | - break | ||
| 661 | - except RuntimeError as exc: | ||
| 662 | - msg = str(exc).lower() | ||
| 663 | - if "alloc" not in msg and "memory" not in msg: | ||
| 664 | raise | 683 | raise |
| 665 | if batch_size <= 1: | 684 | if batch_size <= 1: |
| 666 | logger.error( | 685 | logger.error( |
| @@ -673,12 +692,16 @@ class GraphBuilder: | |||
| 673 | type(exc).__name__, batch_size * 2, batch_size, | 692 | type(exc).__name__, batch_size * 2, batch_size, |
| 674 | ) | 693 | ) |
| 675 | p(f" {label}: memory error, retrying at batch_size={batch_size}") | 694 | p(f" {label}: memory error, retrying at batch_size={batch_size}") |
| 695 | + continue | ||
| 696 | + finally: | ||
| 697 | + contents = None | ||
| 698 | + cursor += len(chunk) | ||
| 699 | + done += len(batch_ids) | ||
| 700 | + _on_batch(done, pending) | ||
| 676 | 701 | ||
| 677 | - _embed_bucket(sem.normal, normal_ids, normal_contents, "normal") | 702 | + _embed_bucket(sem.normal, normal_ids, "normal") |
| 678 | - # Release the normal text lists before embedding test nodes so the | 703 | + del normal_ids |
| 679 | - # peak memory does not keep both buckets alive simultaneously. | 704 | + _embed_bucket(sem.test, test_ids, "test") |
| 680 | - del normal_ids, normal_contents | ||
| 681 | - _embed_bucket(sem.test, test_ids, test_contents, "test") | ||
| 682 | if persist: | 705 | if persist: |
| 683 | sem.save(str(self.pb_dir)) | 706 | sem.save(str(self.pb_dir)) |
| 684 | p(f" Semantic vectors: {len(sem)} (normal={len(sem.normal)}, test={len(sem.test)})") | 707 | p(f" Semantic vectors: {len(sem)} (normal={len(sem.normal)}, test={len(sem.test)})") |
| @@ -249,7 +249,11 @@ class GenerationRepository: | |||
| 249 | """ | 249 | """ |
| 250 | 250 | ||
| 251 | def write(staging: Path) -> None: | 251 | def write(staging: Path) -> None: |
| 252 | - store.save(str(staging)) | 252 | + from .json_store import JsonStore |
| 253 | + if isinstance(store, JsonStore): | ||
| 254 | + store.save_with_offsets(str(staging)) | ||
| 255 | + else: | ||
| 256 | + store.save(str(staging)) | ||
| 253 | keyword_index.save(staging) | 257 | keyword_index.save(staging) |
| 254 | if semantic_index is not None: | 258 | if semantic_index is not None: |
| 255 | semantic_index.save(str(staging)) | 259 | semantic_index.save(str(staging)) |
| @@ -367,7 +371,19 @@ class GenerationRepository: | |||
| 367 | 371 | ||
| 368 | @classmethod | 372 | @classmethod |
| 369 | def _atomic_write_json(cls, path: Path, payload: dict[str, Any]) -> None: | 373 | def _atomic_write_json(cls, path: Path, payload: dict[str, Any]) -> None: |
| 370 | - cls._atomic_write_text(path, json.dumps(payload, ensure_ascii=False, indent=2)) | 374 | + from ..json_stream import dump_json |
| 375 | + | ||
| 376 | + path.parent.mkdir(parents=True, exist_ok=True) | ||
| 377 | + tmp = path.with_name(path.name + f".{uuid.uuid4().hex}.tmp") | ||
| 378 | + try: | ||
| 379 | + with tmp.open("w", encoding="utf-8") as stream: | ||
| 380 | + dump_json(payload, stream, indent=2) | ||
| 381 | + os.replace(tmp, path) | ||
| 382 | + finally: | ||
| 383 | + try: | ||
| 384 | + tmp.unlink(missing_ok=True) | ||
| 385 | + except OSError: | ||
| 386 | + pass | ||
| 371 | 387 | ||
| 372 | def _cleanup_old_generations(self, exclude: set[str]) -> None: | 388 | def _cleanup_old_generations(self, exclude: set[str]) -> None: |
| 373 | candidates = sorted( | 389 | candidates = sorted( |
| @@ -11,6 +11,19 @@ from typing import Any | |||
| 11 | 11 | ||
| 12 | from project_brain.graph.models import Edge | 12 | from project_brain.graph.models import Edge |
| 13 | from project_brain.graph.store import GraphStore | 13 | from project_brain.graph.store import GraphStore |
| 14 | +from project_brain.json_stream import dump_json | ||
| 15 | + | ||
| 16 | + | ||
| 17 | +def _encode_edge(value: Any) -> dict[str, Any]: | ||
| 18 | + if isinstance(value, Edge): | ||
| 19 | + return value.to_dict() | ||
| 20 | + raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable") | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +def _encode_edge(value: Any) -> dict[str, Any]: | ||
| 24 | + if isinstance(value, Edge): | ||
| 25 | + return value.to_dict() | ||
| 26 | + raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable") | ||
| 14 | 27 | ||
| 15 | 28 | ||
| 16 | class JsonStore(GraphStore): | 29 | class JsonStore(GraphStore): |
| @@ -198,7 +211,7 @@ class JsonStore(GraphStore): | |||
| 198 | 211 | ||
| 199 | return results | 212 | return results |
| 200 | 213 | ||
| 201 | - def save(self, path: str) -> None: | 214 | + def save(self, path: str, *, with_offsets: bool = False) -> None: |
| 202 | p = Path(path) | 215 | p = Path(path) |
| 203 | p.mkdir(parents=True, exist_ok=True) | 216 | p.mkdir(parents=True, exist_ok=True) |
| 204 | nodes_file = p / "nodes.json" | 217 | nodes_file = p / "nodes.json" |
| @@ -208,19 +221,16 @@ class JsonStore(GraphStore): | |||
| 208 | edges_tmp = p / f".edges.json.{token}.tmp" | 221 | edges_tmp = p / f".edges.json.{token}.tmp" |
| 209 | with self._lock: | 222 | with self._lock: |
| 210 | try: | 223 | try: |
| 211 | - nodes_tmp.write_text( | 224 | + if with_offsets: |
| 212 | - json.dumps(self.nodes, ensure_ascii=False, indent=2), | 225 | + from .offset_store import write_node_offsets |
| 213 | - encoding="utf-8", | 226 | + write_node_offsets(self.nodes.values(), p) |
| 214 | - ) | 227 | + else: |
| 215 | - edges_tmp.write_text( | 228 | + with nodes_tmp.open("w", encoding="utf-8") as stream: |
| 216 | - json.dumps( | 229 | + dump_json(self.nodes, stream, indent=2) |
| 217 | - [e.to_dict() for e in self.edges], | 230 | + with edges_tmp.open("w", encoding="utf-8") as stream: |
| 218 | - ensure_ascii=False, | 231 | + dump_json(self.edges, stream, indent=2, default=_encode_edge) |
| 219 | - indent=2, | 232 | + if not with_offsets: |
| 220 | - ), | 233 | + os.replace(nodes_tmp, nodes_file) |
| 221 | - encoding="utf-8", | ||
| 222 | - ) | ||
| 223 | - os.replace(nodes_tmp, nodes_file) | ||
| 224 | os.replace(edges_tmp, edges_file) | 234 | os.replace(edges_tmp, edges_file) |
| 225 | finally: | 235 | finally: |
| 226 | for tmp in (nodes_tmp, edges_tmp): | 236 | for tmp in (nodes_tmp, edges_tmp): |
| @@ -231,6 +241,14 @@ class JsonStore(GraphStore): | |||
| 231 | # temp file cannot collide with a later save. | 241 | # temp file cannot collide with a later save. |
| 232 | pass | 242 | pass |
| 233 | 243 | ||
| 244 | + def save_with_offsets(self, path: str) -> None: | ||
| 245 | + """Save one nodes.json with offsets from the same locked snapshot.""" | ||
| 246 | + self._save(path, with_offsets=True) | ||
| 247 | + | ||
| 248 | + def save_with_offsets(self, path: str) -> None: | ||
| 249 | + """Save one nodes.json with offsets from the same locked snapshot.""" | ||
| 250 | + self.save(path, with_offsets=True) | ||
| 251 | + | ||
| 234 | def load(self, path: str) -> None: | 252 | def load(self, path: str) -> None: |
| 235 | with self._lock: | 253 | with self._lock: |
| 236 | p = Path(path) | 254 | p = Path(path) |
| @@ -0,0 +1,118 @@ | |||
| 1 | +"""Generation-local node records for bounded, read-only search hydration.""" | ||
| 2 | +from __future__ import annotations | ||
| 3 | + | ||
| 4 | +from collections import OrderedDict | ||
| 5 | +import json | ||
| 6 | +import os | ||
| 7 | +from pathlib import Path | ||
| 8 | +import threading | ||
| 9 | +from typing import Any, Iterable | ||
| 10 | +import uuid | ||
| 11 | + | ||
| 12 | + | ||
| 13 | +def write_node_offsets(nodes: Iterable[dict[str, Any]], directory: Path) -> None: | ||
| 14 | + """Write nodes.json and its index together in an unpublished generation. | ||
| 15 | + | ||
| 16 | + Offsets delimit only each nested node object, excluding its outer key and | ||
| 17 | + separator. Binary writes keep positions independent of newline translation. | ||
| 18 | + """ | ||
| 19 | + directory = Path(directory) | ||
| 20 | + token = uuid.uuid4().hex | ||
| 21 | + data_tmp = directory / f".nodes.{token}.tmp" | ||
| 22 | + index_tmp = directory / f".offsets.{token}.tmp" | ||
| 23 | + offsets = {} | ||
| 24 | + try: | ||
| 25 | + with data_tmp.open("wb") as stream: | ||
| 26 | + stream.write(b"{") | ||
| 27 | + for node in nodes: | ||
| 28 | + node_id = node["id"] | ||
| 29 | + if node_id in offsets: | ||
| 30 | + raise ValueError(f"Duplicate node ID: {node_id}") | ||
| 31 | + stream.write(b",\n" if offsets else b"\n") | ||
| 32 | + stream.write((" " + json.dumps(node_id, ensure_ascii=False) + ": ").encode("utf-8")) | ||
| 33 | + record = json.dumps(node, ensure_ascii=False, indent=2).replace("\n", "\n ").encode("utf-8") | ||
| 34 | + offsets[node_id] = [stream.tell(), len(record)] | ||
| 35 | + stream.write(record) | ||
| 36 | + stream.write(b"\n}" if offsets else b"}") | ||
| 37 | + size = stream.tell() | ||
| 38 | + index_tmp.write_text(json.dumps({"format_version": 2, "data_file": "nodes.json", "data_size": size, | ||
| 39 | + "offsets": offsets}, ensure_ascii=False, | ||
| 40 | + separators=(",", ":")), encoding="utf-8") | ||
| 41 | + os.replace(data_tmp, directory / "nodes.json") | ||
| 42 | + os.replace(index_tmp, directory / "node_offsets.json") | ||
| 43 | + finally: | ||
| 44 | + data_tmp.unlink(missing_ok=True) | ||
| 45 | + index_tmp.unlink(missing_ok=True) | ||
| 46 | + | ||
| 47 | + | ||
| 48 | +class OffsetNodeStore: | ||
| 49 | + """Only get_node is supported; broader graph tools use the full store. | ||
| 50 | + | ||
| 51 | + The byte budget bounds serialized record sizes held by the cache, not the | ||
| 52 | + exact Python heap size. Oversized documents are read without caching. | ||
| 53 | + """ | ||
| 54 | + | ||
| 55 | + def __init__(self, directory: Path, *, cache_entries: int = 128, | ||
| 56 | + cache_bytes: int = 8 * 1024 * 1024): | ||
| 57 | + directory = Path(directory) | ||
| 58 | + payload = json.loads((directory / "node_offsets.json").read_text(encoding="utf-8")) | ||
| 59 | + version = payload.get("format_version") | ||
| 60 | + if version == 1: | ||
| 61 | + data_name = "nodes.jsonl" # Read existing immutable generations. | ||
| 62 | + elif version == 2 and payload.get("data_file") == "nodes.json": | ||
| 63 | + data_name = "nodes.json" | ||
| 64 | + else: | ||
| 65 | + raise ValueError("Unsupported node offset format") | ||
| 66 | + size = (directory / data_name).stat().st_size | ||
| 67 | + if payload.get("data_size") != size: | ||
| 68 | + raise ValueError("Node data and offset index size mismatch") | ||
| 69 | + offsets = payload.get("offsets") | ||
| 70 | + if not isinstance(offsets, dict): | ||
| 71 | + raise ValueError("Invalid node offsets") | ||
| 72 | + for node_id, bounds in offsets.items(): | ||
| 73 | + if (not isinstance(node_id, str) or not isinstance(bounds, list) or len(bounds) != 2 | ||
| 74 | + or any(type(n) is not int for n in bounds) | ||
| 75 | + or bounds[0] < 0 or bounds[1] <= 0 or sum(bounds) > size): | ||
| 76 | + raise ValueError("Invalid node record bounds") | ||
| 77 | + self.offsets = offsets | ||
| 78 | + self._file = (directory / data_name).open("rb") | ||
| 79 | + self._lock = threading.RLock() | ||
| 80 | + self._cache: OrderedDict[str, tuple[dict, int]] = OrderedDict() | ||
| 81 | + self._cache_entries = max(0, cache_entries) | ||
| 82 | + self._cache_bytes = max(0, cache_bytes) | ||
| 83 | + self._cached_bytes = 0 | ||
| 84 | + self.reads = 0 | ||
| 85 | + self.cache_hits = 0 | ||
| 86 | + | ||
| 87 | + def get_node(self, node_id: str) -> dict[str, Any] | None: | ||
| 88 | + with self._lock: | ||
| 89 | + if node_id in self._cache: | ||
| 90 | + self.cache_hits += 1 | ||
| 91 | + self._cache.move_to_end(node_id) | ||
| 92 | + return self._cache[node_id][0] | ||
| 93 | + bounds = self.offsets.get(node_id) | ||
| 94 | + if bounds is None: | ||
| 95 | + return None | ||
| 96 | + offset, length = bounds | ||
| 97 | + self._file.seek(offset) | ||
| 98 | + record = self._file.read(length) | ||
| 99 | + if len(record) != length: | ||
| 100 | + raise ValueError("Truncated node record") | ||
| 101 | + node = json.loads(record) | ||
| 102 | + if not isinstance(node, dict) or node.get("id") != node_id: | ||
| 103 | + raise ValueError("Node record ID mismatch") | ||
| 104 | + self.reads += 1 | ||
| 105 | + if self._cache_entries and length <= self._cache_bytes: | ||
| 106 | + while self._cache and (len(self._cache) >= self._cache_entries | ||
| 107 | + or self._cached_bytes + length > self._cache_bytes): | ||
| 108 | + _, (_, evicted_size) = self._cache.popitem(last=False) | ||
| 109 | + self._cached_bytes -= evicted_size | ||
| 110 | + self._cache[node_id] = (node, length) | ||
| 111 | + self._cached_bytes += length | ||
| 112 | + return node | ||
| 113 | + | ||
| 114 | + def close(self) -> None: | ||
| 115 | + with self._lock: | ||
| 116 | + self._file.close() | ||
| 117 | + self._cache.clear() | ||
| 118 | + self._cached_bytes = 0 | ||
| @@ -0,0 +1,28 @@ | |||
| 1 | +"""Buffered, incremental JSON encoding for persisted artifacts.""" | ||
| 2 | +from __future__ import annotations | ||
| 3 | + | ||
| 4 | +import json | ||
| 5 | +from typing import Any, Callable, TextIO | ||
| 6 | + | ||
| 7 | + | ||
| 8 | +def dump_json(value: Any, stream: TextIO, *, indent: int | None = None, | ||
| 9 | + separators: tuple[str, str] | None = None, | ||
| 10 | + default: Callable[[Any], Any] | None = None) -> None: | ||
| 11 | + """Write encoder fragments in batches without constructing a full string. | ||
| 12 | + | ||
| 13 | + A single encoded string value may exceed the batch size. ``default`` is | ||
| 14 | + invoked lazily, so callers can convert one edge or token set at a time. | ||
| 15 | + """ | ||
| 16 | + encoder = json.JSONEncoder(ensure_ascii=False, indent=indent, | ||
| 17 | + separators=separators, default=default) | ||
| 18 | + parts: list[str] = [] | ||
| 19 | + size = 0 | ||
| 20 | + for part in encoder.iterencode(value): | ||
| 21 | + parts.append(part) | ||
| 22 | + size += len(part) | ||
| 23 | + if size >= 64 * 1024: | ||
| 24 | + stream.write("".join(parts)) | ||
| 25 | + parts.clear() | ||
| 26 | + size = 0 | ||
| 27 | + if parts: | ||
| 28 | + stream.write("".join(parts)) | ||
| @@ -84,6 +84,7 @@ class ProjectBrainServer: | |||
| 84 | self._file_index = None | 84 | self._file_index = None |
| 85 | self._query_engine = None | 85 | self._query_engine = None |
| 86 | self._initialized = False | 86 | self._initialized = False |
| 87 | + self._search_only = False | ||
| 87 | self._watcher_manager = None | 88 | self._watcher_manager = None |
| 88 | self._updater = None | 89 | self._updater = None |
| 89 | self._init_lock = threading.Lock() | 90 | self._init_lock = threading.Lock() |
| @@ -119,6 +120,11 @@ class ProjectBrainServer: | |||
| 119 | 120 | ||
| 120 | def _ensure_initialized(self, start_watcher: bool = True, read_only: bool = False): | 121 | def _ensure_initialized(self, start_watcher: bool = True, read_only: bool = False): |
| 121 | with self._init_lock: | 122 | with self._init_lock: |
| 123 | + if getattr(self, "_search_only", False): | ||
| 124 | + self._store.close() | ||
| 125 | + self._search_only = False | ||
| 126 | + self._initialized = False | ||
| 127 | + read_only = True | ||
| 122 | if self._initialized: | 128 | if self._initialized: |
| 123 | # A read-only session must never start the watcher, even if a | 129 | # A read-only session must never start the watcher, even if a |
| 124 | # tool function requests it with the default start_watcher=True. | 130 | # tool function requests it with the default start_watcher=True. |
| @@ -128,6 +134,60 @@ class ProjectBrainServer: | |||
| 128 | self._read_only = read_only | 134 | self._read_only = read_only |
| 129 | self._initialize(start_watcher, read_only=read_only) | 135 | self._initialize(start_watcher, read_only=read_only) |
| 130 | 136 | ||
| 137 | + def _ensure_search_initialized(self, loading: str = "auto") -> None: | ||
| 138 | + """Use generation sidecars only for a one-shot, keyword-only CLI search.""" | ||
| 139 | + if loading not in {"auto", "full", "lazy"}: | ||
| 140 | + raise ValueError("Unknown search loading mode") | ||
| 141 | + if loading == "full": | ||
| 142 | + self._ensure_initialized(start_watcher=False, read_only=True) | ||
| 143 | + return | ||
| 144 | + from ..paths import graph_dir | ||
| 145 | + from ..graph.offset_store import OffsetNodeStore | ||
| 146 | + | ||
| 147 | + with self._init_lock: | ||
| 148 | + if self._initialized: | ||
| 149 | + return | ||
| 150 | + store = None | ||
| 151 | + try: | ||
| 152 | + if self.config.storage_backend == "sqlite" or self.config.search_strategy != "keyword": | ||
| 153 | + raise ValueError("Offset search requires JSON storage and keyword strategy") | ||
| 154 | + repo = GenerationRepository(graph_dir(self.project_path)) | ||
| 155 | + active = repo.current_path() | ||
| 156 | + manifest = json.loads((active / "manifest.json").read_text(encoding="utf-8")) | ||
| 157 | + metadata = manifest.get("metadata", {}) | ||
| 158 | + if (metadata.get("graph_schema_version") != GRAPH_SCHEMA_VERSION | ||
| 159 | + or metadata.get("config_digest") != self._config_digest | ||
| 160 | + or not {"nodes.json", "node_offsets.json"}.issubset(manifest.get("artifacts", {}))): | ||
| 161 | + raise ValueError("No compatible offset artifacts; run bot-brain build") | ||
| 162 | + store = OffsetNodeStore(active) | ||
| 163 | + keyword = KeywordIndex() | ||
| 164 | + if not store.offsets or not keyword.load(active): | ||
| 165 | + raise ValueError("Missing or incompatible keyword index") | ||
| 166 | + self._store = store | ||
| 167 | + self._keyword_index = keyword | ||
| 168 | + self._symbol_index = SymbolIndex() | ||
| 169 | + self._file_index = FileIndex() | ||
| 170 | + self._semantic_index = None | ||
| 171 | + self._query_engine = QueryEngine(store, keyword, self._symbol_index, self._file_index, | ||
| 172 | + search_strategy="keyword", project_path=str(self.project_path), | ||
| 173 | + graph_profile=self.config.graph_profile) | ||
| 174 | + self._query_engine.last_updated = manifest.get("created_at") or 0.0 | ||
| 175 | + if metadata.get("partial"): | ||
| 176 | + self._query_engine.build_status = "degraded" | ||
| 177 | + self._generation_repo = repo | ||
| 178 | + self._active_graph_dir = active | ||
| 179 | + self._read_only = True | ||
| 180 | + self._search_only = True | ||
| 181 | + self._initialized = True | ||
| 182 | + return | ||
| 183 | + except (OSError, ValueError, TypeError, AttributeError) as exc: | ||
| 184 | + if store is not None: | ||
| 185 | + store.close() | ||
| 186 | + if loading == "lazy": | ||
| 187 | + raise RuntimeError(f"Cannot initialize offset search: {exc}") from exc | ||
| 188 | + logger.debug("Offset search unavailable, using full load: %s", exc) | ||
| 189 | + self._ensure_initialized(start_watcher=False, read_only=True) | ||
| 190 | + | ||
| 131 | def _initialize(self, start_watcher: bool, *, read_only: bool = False) -> None: | 191 | def _initialize(self, start_watcher: bool, *, read_only: bool = False) -> None: |
| 132 | from ..paths import graph_dir, migrate_legacy | 192 | from ..paths import graph_dir, migrate_legacy |
| 133 | 193 | ||
| @@ -230,8 +290,8 @@ class ProjectBrainServer: | |||
| 230 | self._file_index = FileIndex() | 290 | self._file_index = FileIndex() |
| 231 | self._semantic_index = ( | 291 | self._semantic_index = ( |
| 232 | SemanticIndexSet(self.config.model_precision) | 292 | SemanticIndexSet(self.config.model_precision) |
| 233 | - if SemanticIndexSet.available() | 293 | + if self.config.search_strategy in ("semantic", "hybrid") |
| 234 | - and self.config.search_strategy in ("semantic", "hybrid") | 294 | + and SemanticIndexSet.available() |
| 235 | else None | 295 | else None |
| 236 | ) | 296 | ) |
| 237 | 297 | ||
| @@ -1139,7 +1199,8 @@ class ProjectBrainServer: | |||
| 1139 | # -- sync implementations ------------------------------------------------ | 1199 | # -- sync implementations ------------------------------------------------ |
| 1140 | 1200 | ||
| 1141 | def _keyword_search(query, scope=None, top_k=20, test_filter="normal"): | 1201 | def _keyword_search(query, scope=None, top_k=20, test_filter="normal"): |
| 1142 | - self._ensure_initialized() | 1202 | + if not self._search_only: |
| 1203 | + self._ensure_initialized() | ||
| 1143 | results = self._query_engine.keyword_search(query, scope, top_k, test_filter) | 1204 | results = self._query_engine.keyword_search(query, scope, top_k, test_filter) |
| 1144 | return json.dumps( | 1205 | return json.dumps( |
| 1145 | {"results": results, "total": len(results), "freshness": self._freshness()}, | 1206 | {"results": results, "total": len(results), "freshness": self._freshness()}, |
| @@ -2103,6 +2164,8 @@ class ProjectBrainServer: | |||
| 2103 | # Read-only sessions (CLI/REPL queries) must not publish a shutdown | 2164 | # Read-only sessions (CLI/REPL queries) must not publish a shutdown |
| 2104 | # generation — they never started the watcher and have nothing to persist. | 2165 | # generation — they never started the watcher and have nothing to persist. |
| 2105 | if self._read_only: | 2166 | if self._read_only: |
| 2167 | + if self._search_only: | ||
| 2168 | + self._store.close() | ||
| 2106 | self._closed = True | 2169 | self._closed = True |
| 2107 | return | 2170 | return |
| 2108 | stopped = self._stop_watcher() | 2171 | stopped = self._stop_watcher() |
| @@ -6,9 +6,18 @@ import re | |||
| 6 | import copy | 6 | import copy |
| 7 | import threading | 7 | import threading |
| 8 | import unicodedata | 8 | import unicodedata |
| 9 | +import tempfile | ||
| 9 | from pathlib import Path | 10 | from pathlib import Path |
| 10 | from typing import Any | 11 | from typing import Any |
| 11 | 12 | ||
| 13 | +from ..json_stream import dump_json | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +def _encode_token_set(value: Any) -> list[str]: | ||
| 17 | + if isinstance(value, set): | ||
| 18 | + return list(value) | ||
| 19 | + raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable") | ||
| 20 | + | ||
| 12 | 21 | ||
| 13 | _CAMEL_PART_RE = re.compile( | 22 | _CAMEL_PART_RE = re.compile( |
| 14 | r"[A-Z]+(?=[A-Z][a-z]|\d|$)|[A-Z]?[a-z]+|\d+", | 23 | r"[A-Z]+(?=[A-Z][a-z]|\d|$)|[A-Z]?[a-z]+|\d+", |
| @@ -164,12 +173,22 @@ class KeywordIndex: | |||
| 164 | "postings": self.postings, | 173 | "postings": self.postings, |
| 165 | "documents": self.documents, | 174 | "documents": self.documents, |
| 166 | "doc_len": self.doc_len, | 175 | "doc_len": self.doc_len, |
| 167 | - "doc_tokens": {k: list(v) for k, v in self._doc_tokens.items()}, | 176 | + "doc_tokens": self._doc_tokens, |
| 168 | } | 177 | } |
| 169 | target = p / "keyword_index.json" | 178 | target = p / "keyword_index.json" |
| 170 | - tmp = p / "keyword_index.json.tmp" | 179 | + # Keep names shorter than the legacy keyword_index.json.tmp. Deep |
| 171 | - tmp.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8") | 180 | + # generation paths on Windows otherwise exceed MAX_PATH sooner. |
| 172 | - os.replace(tmp, target) | 181 | + fd, name = tempfile.mkstemp(prefix=".kw-", suffix=".tmp", dir=p) |
| 182 | + tmp = Path(name) | ||
| 183 | + try: | ||
| 184 | + with os.fdopen(fd, "w", encoding="utf-8") as stream: | ||
| 185 | + dump_json(data, stream, default=_encode_token_set) | ||
| 186 | + os.replace(tmp, target) | ||
| 187 | + finally: | ||
| 188 | + try: | ||
| 189 | + tmp.unlink(missing_ok=True) | ||
| 190 | + except OSError: | ||
| 191 | + pass # Do not mask a serialization or replacement failure. | ||
| 173 | 192 | ||
| 174 | def load(self, path: str | Path) -> bool: | 193 | def load(self, path: str | Path) -> bool: |
| 175 | """Load from ``<path>/keyword_index.json``. Returns True if loaded.""" | 194 | """Load from ``<path>/keyword_index.json``. Returns True if loaded.""" |
| @@ -197,10 +197,9 @@ class SemanticIndex: | |||
| 197 | import time | 197 | import time |
| 198 | if not sample_texts or total <= 0: | 198 | if not sample_texts or total <= 0: |
| 199 | return 0.0, 0.0 | 199 | return 0.0, 0.0 |
| 200 | - self._ensure_model() | ||
| 201 | sample = sample_texts[:50] | 200 | sample = sample_texts[:50] |
| 202 | t0 = time.time() | 201 | t0 = time.time() |
| 203 | - list(self._model.embed(sample)) | 202 | + self._embed(sample) |
| 204 | dt = max(time.time() - t0, 0.01) | 203 | dt = max(time.time() - t0, 0.01) |
| 205 | speed = len(sample) / dt | 204 | speed = len(sample) / dt |
| 206 | return total / speed, speed | 205 | return total / speed, speed |
| @@ -277,6 +276,10 @@ class SemanticIndex: | |||
| 277 | if len(set(doc_ids)) != len(doc_ids): | 276 | if len(set(doc_ids)) != len(doc_ids): |
| 278 | raise ValueError("doc_ids must be unique within a batch") | 277 | raise ValueError("doc_ids must be unique within a batch") |
| 279 | import numpy as np | 278 | import numpy as np |
| 279 | + # Inference can fail before any vectors are committed. Keep existing | ||
| 280 | + # mappings intact so retry/repair never mistakes that batch for done. | ||
| 281 | + arr = self._embed(contents) | ||
| 282 | + self._ensure_index(arr.shape[1]) | ||
| 280 | existing = [self._doc_to_int[d] for d in doc_ids if d in self._doc_to_int] | 283 | existing = [self._doc_to_int[d] for d in doc_ids if d in self._doc_to_int] |
| 281 | if existing: | 284 | if existing: |
| 282 | # Flat supports physical deletion. HNSW does not: version the | 285 | # Flat supports physical deletion. HNSW does not: version the |
| @@ -288,16 +291,12 @@ class SemanticIndex: | |||
| 288 | if d in self._doc_to_int: | 291 | if d in self._doc_to_int: |
| 289 | old = self._doc_to_int.pop(d) | 292 | old = self._doc_to_int.pop(d) |
| 290 | self._int_to_doc.pop(old, None) | 293 | self._int_to_doc.pop(old, None) |
| 291 | - arr = self._embed(contents) | 294 | + ids = list(range(self._next_int, self._next_int + len(doc_ids))) |
| 292 | - self._ensure_index(arr.shape[1]) | 295 | + self._index.add_with_ids(arr, np.array(ids, dtype=np.int64)) |
| 293 | - ids = [] | 296 | + for doc_id, int_id in zip(doc_ids, ids): |
| 294 | - for doc_id in doc_ids: | ||
| 295 | - int_id = self._next_int | ||
| 296 | - self._next_int += 1 | ||
| 297 | self._doc_to_int[doc_id] = int_id | 297 | self._doc_to_int[doc_id] = int_id |
| 298 | self._int_to_doc[int_id] = doc_id | 298 | self._int_to_doc[int_id] = doc_id |
| 299 | - ids.append(int_id) | 299 | + self._next_int += len(ids) |
| 300 | - self._index.add_with_ids(arr, np.array(ids, dtype=np.int64)) | ||
| 301 | self._maybe_compact() | 300 | self._maybe_compact() |
| 302 | 301 | ||
| 303 | def has(self, doc_id: str) -> bool: | 302 | def has(self, doc_id: str) -> bool: |
| @@ -433,15 +432,26 @@ class SemanticIndex: | |||
| 433 | data = { | 432 | data = { |
| 434 | "format_version": 2, | 433 | "format_version": 2, |
| 435 | "doc_to_int": self._doc_to_int, | 434 | "doc_to_int": self._doc_to_int, |
| 436 | - "int_to_doc": {str(k): v for k, v in self._int_to_doc.items()}, | 435 | + "int_to_doc": self._int_to_doc, |
| 437 | "next_int": self._next_int, | 436 | "next_int": self._next_int, |
| 438 | "dim": self._dim, | 437 | "dim": self._dim, |
| 439 | "index_type": self._index_type, | 438 | "index_type": self._index_type, |
| 440 | } | 439 | } |
| 441 | ids_file = p / "semantic_ids.json" | 440 | ids_file = p / "semantic_ids.json" |
| 442 | - ids_tmp = p / "semantic_ids.json.tmp" | 441 | + from ..json_stream import dump_json |
| 443 | - ids_tmp.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8") | 442 | + # Exclusive short names preserve the legacy Windows path budget even |
| 444 | - os.replace(ids_tmp, ids_file) | 443 | + # inside semantic_state/generations/.../semantic_normal. |
| 444 | + fd, name = tempfile.mkstemp(prefix=".si-", suffix=".tmp", dir=p) | ||
| 445 | + ids_tmp = Path(name) | ||
| 446 | + try: | ||
| 447 | + with os.fdopen(fd, "w", encoding="utf-8") as stream: | ||
| 448 | + dump_json(data, stream) | ||
| 449 | + os.replace(ids_tmp, ids_file) | ||
| 450 | + finally: | ||
| 451 | + try: | ||
| 452 | + ids_tmp.unlink(missing_ok=True) | ||
| 453 | + except OSError: | ||
| 454 | + pass | ||
| 445 | 455 | ||
| 446 | def load(self, path: str | Path) -> None: | 456 | def load(self, path: str | Path) -> None: |
| 447 | import faiss | 457 | import faiss |
| @@ -0,0 +1,217 @@ | |||
| 1 | +import json | ||
| 2 | +import shutil | ||
| 3 | +from concurrent.futures import ThreadPoolExecutor | ||
| 4 | + | ||
| 5 | +import pytest | ||
| 6 | + | ||
| 7 | +from project_brain.config import Config | ||
| 8 | +from project_brain.graph.generation import GenerationRepository, GRAPH_SCHEMA_VERSION | ||
| 9 | +from project_brain.graph.json_store import JsonStore | ||
| 10 | +from project_brain.graph.offset_store import OffsetNodeStore, write_node_offsets | ||
| 11 | +from project_brain.query.index import KeywordIndex | ||
| 12 | +from project_brain.mcp.server import ProjectBrainServer | ||
| 13 | +from project_brain.watcher.reconciler import compute_graph_config_digest | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +def test_utf8_offsets_cache_eviction_and_concurrent_reads(tmp_path): | ||
| 17 | + nodes = [{"id": f"n{i}", "name": "连接池🙂", "content": "多行\n内容"} for i in range(6)] | ||
| 18 | + write_node_offsets(nodes, tmp_path) | ||
| 19 | + with_store = OffsetNodeStore(tmp_path, cache_entries=2) | ||
| 20 | + try: | ||
| 21 | + assert with_store.get_node("missing") is None | ||
| 22 | + assert with_store.get_node("n0") == nodes[0] | ||
| 23 | + assert with_store.get_node("n0") == nodes[0] | ||
| 24 | + assert with_store.reads == 1 | ||
| 25 | + assert with_store.cache_hits == 1 | ||
| 26 | + with ThreadPoolExecutor(4) as pool: | ||
| 27 | + actual = list(pool.map(with_store.get_node, [n["id"] for n in nodes] * 5)) | ||
| 28 | + assert actual == nodes * 5 | ||
| 29 | + assert len(with_store._cache) <= 2 | ||
| 30 | + finally: | ||
| 31 | + with_store.close() | ||
| 32 | + assert with_store._file.closed | ||
| 33 | + | ||
| 34 | + | ||
| 35 | +@pytest.mark.parametrize("nodes", [[], [ | ||
| 36 | + {"id": '中文🙂"\\', "name": "连接池", "nested": {"items": [1, {"text": '} , {\n"'}]}, | ||
| 37 | + "content": "首行\r\n下一行🙂"}, | ||
| 38 | + {"id": "last", "type": "function", "nullable": None}, | ||
| 39 | +]]) | ||
| 40 | +def test_offsets_delimit_objects_in_original_json_format(tmp_path, nodes): | ||
| 41 | + write_node_offsets(nodes, tmp_path) | ||
| 42 | + data = (tmp_path / "nodes.json").read_bytes() | ||
| 43 | + expected = {n["id"]: n for n in nodes} | ||
| 44 | + assert data == json.dumps(expected, ensure_ascii=False, indent=2).encode("utf-8") | ||
| 45 | + assert json.loads(data) == expected | ||
| 46 | + assert not (tmp_path / "nodes.jsonl").exists() | ||
| 47 | + index = json.loads((tmp_path / "node_offsets.json").read_text(encoding="utf-8")) | ||
| 48 | + assert index["format_version"] == 2 | ||
| 49 | + assert index["data_file"] == "nodes.json" | ||
| 50 | + for node in nodes: | ||
| 51 | + start, length = index["offsets"][node["id"]] | ||
| 52 | + assert json.loads(data[start:start + length]) == node | ||
| 53 | + full = JsonStore(tmp_path) | ||
| 54 | + full.load(str(tmp_path)) | ||
| 55 | + lazy = OffsetNodeStore(tmp_path) | ||
| 56 | + try: | ||
| 57 | + assert lazy.reads == 0 | ||
| 58 | + for node in nodes: | ||
| 59 | + assert lazy.get_node(node["id"]) == full.get_node(node["id"]) | ||
| 60 | + finally: | ||
| 61 | + lazy.close() | ||
| 62 | + | ||
| 63 | + | ||
| 64 | +def test_existing_jsonl_index_remains_readable(tmp_path): | ||
| 65 | + node = {"id": "old", "content": "旧图谱🙂"} | ||
| 66 | + record = (json.dumps(node, ensure_ascii=False) + "\n").encode("utf-8") | ||
| 67 | + (tmp_path / "nodes.jsonl").write_bytes(record) | ||
| 68 | + (tmp_path / "node_offsets.json").write_text(json.dumps({ | ||
| 69 | + "format_version": 1, "data_size": len(record), "offsets": {"old": [0, len(record)]}, | ||
| 70 | + }), encoding="utf-8") | ||
| 71 | + store = OffsetNodeStore(tmp_path) | ||
| 72 | + try: | ||
| 73 | + assert store.get_node("old") == node | ||
| 74 | + finally: | ||
| 75 | + store.close() | ||
| 76 | + | ||
| 77 | + | ||
| 78 | +def test_mismatched_and_truncated_records_fail(tmp_path): | ||
| 79 | + write_node_offsets([{"id": "n", "name": "test"}], tmp_path) | ||
| 80 | + payload = json.loads((tmp_path / "node_offsets.json").read_text()) | ||
| 81 | + payload["offsets"]["wrong"] = payload["offsets"].pop("n") | ||
| 82 | + (tmp_path / "node_offsets.json").write_text(json.dumps(payload)) | ||
| 83 | + store = OffsetNodeStore(tmp_path) | ||
| 84 | + try: | ||
| 85 | + with pytest.raises(ValueError, match="ID mismatch"): | ||
| 86 | + store.get_node("wrong") | ||
| 87 | + finally: | ||
| 88 | + store.close() | ||
| 89 | + (tmp_path / "nodes.json").write_bytes(b"") | ||
| 90 | + with pytest.raises(ValueError, match="size mismatch"): | ||
| 91 | + OffsetNodeStore(tmp_path) | ||
| 92 | + | ||
| 93 | + | ||
| 94 | +def publish_project(root, extra_nodes=()): | ||
| 95 | + config = Config(search_strategy="keyword", storage_backend="json", watcher_enabled=False) | ||
| 96 | + config.save(str(root)) | ||
| 97 | + store = JsonStore(root) | ||
| 98 | + store.add_node({"id": "file", "type": "file", "path": "src/main.py", "imports": []}) | ||
| 99 | + store.add_node({"id": "fn", "type": "function", "name": "retry", "file_id": "file", | ||
| 100 | + "signature": "retry(timeout)", "calls": [], "references": [], "type_bindings": []}) | ||
| 101 | + keyword = KeywordIndex() | ||
| 102 | + keyword.add("fn", "retry timeout") | ||
| 103 | + for node, text in extra_nodes: | ||
| 104 | + store.add_node(node) | ||
| 105 | + if text: | ||
| 106 | + keyword.add(node["id"], text, retain_source=node["type"] != "document_chunk") | ||
| 107 | + repo = GenerationRepository(root / ".botbrain" / "graph") | ||
| 108 | + path = repo.publish_graph_state(store, keyword, metadata={ | ||
| 109 | + "graph_schema_version": GRAPH_SCHEMA_VERSION, | ||
| 110 | + "config_digest": compute_graph_config_digest(config), "semantic_complete": True}) | ||
| 111 | + return path | ||
| 112 | + | ||
| 113 | + | ||
| 114 | +def test_search_does_not_load_full_graph_and_matches_full_results(tmp_path, monkeypatch): | ||
| 115 | + path = publish_project(tmp_path) | ||
| 116 | + lazy = ProjectBrainServer(str(tmp_path)) | ||
| 117 | + full = ProjectBrainServer(str(tmp_path)) | ||
| 118 | + try: | ||
| 119 | + full._ensure_search_initialized("full") | ||
| 120 | + expected = json.loads(full.call_tool_sync("keyword_search", {"query": "timeout"})) | ||
| 121 | + def forbidden(*args, **kwargs): | ||
| 122 | + raise AssertionError("Lazy search must not load or scan the graph") | ||
| 123 | + monkeypatch.setattr(JsonStore, "load", forbidden) | ||
| 124 | + monkeypatch.setattr(JsonStore, "get_nodes_by_type", forbidden) | ||
| 125 | + lazy._ensure_search_initialized("lazy") | ||
| 126 | + actual = json.loads(lazy.call_tool_sync("keyword_search", {"query": "timeout"})) | ||
| 127 | + actual["freshness"].pop("seconds_since_update") | ||
| 128 | + expected["freshness"].pop("seconds_since_update") | ||
| 129 | + assert actual == expected | ||
| 130 | + assert isinstance(lazy._store, OffsetNodeStore) | ||
| 131 | + assert lazy._store.reads == 2 # Hit and owning file, no edge loading. | ||
| 132 | + finally: | ||
| 133 | + full.close() | ||
| 134 | + lazy.close() | ||
| 135 | + assert lazy._store._file.closed | ||
| 136 | + assert (path / "nodes.json").is_file() | ||
| 137 | + assert not (path / "nodes.jsonl").exists() | ||
| 138 | + | ||
| 139 | + | ||
| 140 | +def test_legacy_fallback_and_upgrade_to_full_store(tmp_path): | ||
| 141 | + publish_project(tmp_path) | ||
| 142 | + server = ProjectBrainServer(str(tmp_path)) | ||
| 143 | + try: | ||
| 144 | + server._ensure_search_initialized("auto") | ||
| 145 | + offset_store = server._store | ||
| 146 | + server._ensure_initialized(start_watcher=False, read_only=True) | ||
| 147 | + assert offset_store._file.closed | ||
| 148 | + assert isinstance(server._store, JsonStore) | ||
| 149 | + assert not server._search_only | ||
| 150 | + finally: | ||
| 151 | + server.close() | ||
| 152 | + | ||
| 153 | + | ||
| 154 | +def test_forced_lazy_rejects_stale_configuration(tmp_path): | ||
| 155 | + publish_project(tmp_path) | ||
| 156 | + config = Config.load(str(tmp_path)) | ||
| 157 | + config.index_body = True | ||
| 158 | + config.save(str(tmp_path)) | ||
| 159 | + server = ProjectBrainServer(str(tmp_path)) | ||
| 160 | + with pytest.raises(RuntimeError, match="No compatible offset"): | ||
| 161 | + server._ensure_search_initialized("lazy") | ||
| 162 | + server.close() | ||
| 163 | + | ||
| 164 | + | ||
| 165 | +def test_auto_falls_back_for_generation_without_offsets(tmp_path): | ||
| 166 | + current = publish_project(tmp_path) | ||
| 167 | + repo = GenerationRepository(current.parent.parent) | ||
| 168 | + metadata = json.loads((current / "manifest.json").read_text())["metadata"] | ||
| 169 | + def legacy_writer(staging): | ||
| 170 | + for name in ("nodes.json", "edges.json", "keyword_index.json"): | ||
| 171 | + shutil.copy2(current / name, staging / name) | ||
| 172 | + repo.publish(legacy_writer, metadata=metadata) | ||
| 173 | + server = ProjectBrainServer(str(tmp_path)) | ||
| 174 | + try: | ||
| 175 | + server._ensure_search_initialized("auto") | ||
| 176 | + assert isinstance(server._store, JsonStore) | ||
| 177 | + assert not server._search_only | ||
| 178 | + finally: | ||
| 179 | + server.close() | ||
| 180 | + | ||
| 181 | + | ||
| 182 | +def test_document_chunk_preview_scope_and_filters_match_full(tmp_path): | ||
| 183 | + content = "连接池🙂 timeout retry\n完整文档正文" | ||
| 184 | + publish_project(tmp_path, [ | ||
| 185 | + ({"id": "doc", "type": "document", "path": "docs/guide.md", "title": "连接池", | ||
| 186 | + "content": content, "content_complete": True}, ""), | ||
| 187 | + ({"id": "chunk", "type": "document_chunk", "doc_id": "doc", "char_start": 0, | ||
| 188 | + "char_end": len(content), "line_start": 1, "line_end": 2}, content), | ||
| 189 | + ]) | ||
| 190 | + servers = [ProjectBrainServer(str(tmp_path)) for _ in range(2)] | ||
| 191 | + try: | ||
| 192 | + for server, loading in zip(servers, ("full", "lazy")): | ||
| 193 | + server._ensure_search_initialized(loading) | ||
| 194 | + for kwargs in ({"query": "连接池"}, {"query": "timeout", "scope": "docs"}, | ||
| 195 | + {"query": "timeout", "test_filter": "test"}, {"query": "missingword"}): | ||
| 196 | + payloads = [json.loads(s.call_tool_sync("keyword_search", kwargs)) for s in servers] | ||
| 197 | + for payload in payloads: | ||
| 198 | + payload["freshness"].pop("seconds_since_update") | ||
| 199 | + assert payloads[0] == payloads[1] | ||
| 200 | + hits = servers[1]._query_engine.keyword_search("连接池") | ||
| 201 | + assert hits[0]["content_preview"] == content | ||
| 202 | + assert hits[0]["content_available"] is True | ||
| 203 | + finally: | ||
| 204 | + for server in servers: | ||
| 205 | + server.close() | ||
| 206 | + | ||
| 207 | + | ||
| 208 | +def test_oversized_record_is_not_cached(tmp_path): | ||
| 209 | + write_node_offsets([{"id": "n", "content": "x" * 1000}], tmp_path) | ||
| 210 | + store = OffsetNodeStore(tmp_path, cache_bytes=100) | ||
| 211 | + try: | ||
| 212 | + store.get_node("n") | ||
| 213 | + store.get_node("n") | ||
| 214 | + assert store.reads == 2 | ||
| 215 | + assert not store._cache | ||
| 216 | + finally: | ||
| 217 | + store.close() | ||
| @@ -0,0 +1,143 @@ | |||
| 1 | +"""Benchmark contracts, including real fresh-process build/load isolation.""" | ||
| 2 | +import json | ||
| 3 | +import subprocess | ||
| 4 | +import os | ||
| 5 | +import sys | ||
| 6 | +import pytest | ||
| 7 | + | ||
| 8 | +from benchmarks.performance.dataset import generate, manifest, copy_project | ||
| 9 | +from benchmarks.performance.metrics import Recorder | ||
| 10 | +from benchmarks.performance.run import launch, main, summarize | ||
| 11 | + | ||
| 12 | + | ||
| 13 | +def test_dataset_is_reproducible_and_mixed(tmp_path): | ||
| 14 | + first, second = tmp_path / "first", tmp_path / "second" | ||
| 15 | + generate(first, "smoke") | ||
| 16 | + generate(second, "smoke") | ||
| 17 | + assert manifest(first) == manifest(second) | ||
| 18 | + assert set(manifest(first)["extensions"]) == {".py", ".rs", ".c", ".ts", ".go", ".md", ".txt"} | ||
| 19 | + (second / "docs" / "guide_0.md").write_text("changed", encoding="utf-8") | ||
| 20 | + assert manifest(first)["sha256"] != manifest(second)["sha256"] | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +def test_copy_excludes_graph_and_preserves_original(tmp_path): | ||
| 24 | + source = tmp_path / "source" | ||
| 25 | + generate(source, "smoke") | ||
| 26 | + (source / ".botbrain").mkdir() | ||
| 27 | + (source / ".botbrain" / "secret").write_text("do not copy") | ||
| 28 | + before = manifest(source) | ||
| 29 | + copy_project(source, tmp_path / "copy") | ||
| 30 | + assert manifest(source) == before | ||
| 31 | + assert not (tmp_path / "copy" / ".botbrain").exists() | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +def test_recorder_nested_time_and_restore_on_error(): | ||
| 35 | + class Example: | ||
| 36 | + def work(self): | ||
| 37 | + raise ValueError("expected") | ||
| 38 | + original = Example.work | ||
| 39 | + recorder = Recorder() | ||
| 40 | + with pytest.raises(ValueError), recorder.hook(Example, "work", "child"): | ||
| 41 | + with recorder.measure("parent"): | ||
| 42 | + Example().work() | ||
| 43 | + child, parent = recorder.rows | ||
| 44 | + assert Example.work is original | ||
| 45 | + assert child["status"] == parent["status"] == "error" | ||
| 46 | + assert parent["self_seconds"] == pytest.approx(parent["seconds"] - child["seconds"]) | ||
| 47 | + assert not recorder.stack | ||
| 48 | + | ||
| 49 | + | ||
| 50 | +def test_summary_separates_call_latency_from_worker_totals(): | ||
| 51 | + def sample(seconds): | ||
| 52 | + return dict(scenario="warm", stage="docs", seconds=seconds, self_seconds=seconds, | ||
| 53 | + rss_after_bytes=None) | ||
| 54 | + rows = summarize([dict(mode="query", metrics=[sample(1), sample(3)]), | ||
| 55 | + dict(mode="query", metrics=[sample(2), sample(4)])]) | ||
| 56 | + assert rows[0]["p50_ms"] == 2500 | ||
| 57 | + assert rows[0]["p95_ms"] == 4000 | ||
| 58 | + assert rows[0]["median_worker_total_ms"] == 5000 | ||
| 59 | + | ||
| 60 | + | ||
| 61 | +def test_iterator_timing_does_not_span_consumer_work(): | ||
| 62 | + class Scanner: | ||
| 63 | + def scan(self): | ||
| 64 | + yield "first" | ||
| 65 | + yield "second" | ||
| 66 | + recorder = Recorder() | ||
| 67 | + with recorder.hook_iterator(Scanner, "scan", "scan"): | ||
| 68 | + iterator = Scanner().scan() | ||
| 69 | + assert next(iterator) == "first" | ||
| 70 | + assert not recorder.stack | ||
| 71 | + with recorder.measure("consumer"): | ||
| 72 | + assert len(recorder.stack) == 1 | ||
| 73 | + assert list(iterator) == ["second"] | ||
| 74 | + assert [row["stage"] for row in recorder.rows] == ["scan", "consumer", "scan", "scan"] | ||
| 75 | + assert all(row["status"] == "ok" for row in recorder.rows) | ||
| 76 | + | ||
| 77 | + | ||
| 78 | +@pytest.mark.parametrize("backend", ["json", "sqlite"]) | ||
| 79 | +def test_real_build_cold_load_and_warm_query(tmp_path, backend): | ||
| 80 | + # Keep generation temp-file paths below Windows' legacy MAX_PATH limit. | ||
| 81 | + output = tmp_path.parent / backend | ||
| 82 | + assert main(["--size", "smoke", "--runs", "1", "--warm-runs", "1", | ||
| 83 | + "--backend", backend, "--output", str(output), | ||
| 84 | + "--query", "retry timeout", "--query", "连接池"]) == 0 | ||
| 85 | + report = json.loads(next(output.glob("*/report.json")).read_text(encoding="utf-8")) | ||
| 86 | + build, query = report["workers"] | ||
| 87 | + assert build["status"] == query["status"] == "ok" | ||
| 88 | + assert build["graph"] == query["graph"] | ||
| 89 | + assert build["graph"]["nodes"] > 20 | ||
| 90 | + assert build["graph"]["stored_documents"] == 4 | ||
| 91 | + assert all(row["stage"] != "build.total" for row in query["metrics"]) | ||
| 92 | + assert len(query["queries"]) == 4 | ||
| 93 | + assert all(row["hits"] > 0 for row in query["queries"]) | ||
| 94 | + stages = {r["stage"] for r in build["metrics"]} | ||
| 95 | + assert {"build.code_parse", "build.document_parse", "build.relations", | ||
| 96 | + "build.document_chunks", "index.bm25_build"} <= stages | ||
| 97 | + assert all(q["metric_end"] > q["metric_start"] for q in query["queries"]) | ||
| 98 | + | ||
| 99 | + | ||
| 100 | +def test_worker_error_retains_diagnostics(tmp_path): | ||
| 101 | + request = dict(project=str(tmp_path / "project"), mode="build", backend="invalid", | ||
| 102 | + strategy="keyword", queries=[], warm_runs=1, top_k=20) | ||
| 103 | + result = launch(request, tmp_path / "worker", timeout=60) | ||
| 104 | + assert result["status"] == "error" | ||
| 105 | + assert "error" in result | ||
| 106 | + assert (tmp_path / "worker" / "worker.log").exists() | ||
| 107 | + | ||
| 108 | + | ||
| 109 | +def test_output_inside_source_rejected_before_copy(tmp_path): | ||
| 110 | + with pytest.raises(SystemExit): | ||
| 111 | + main(["--project", str(tmp_path), "--output", str(tmp_path / "results")]) | ||
| 112 | + assert not (tmp_path / "results").exists() | ||
| 113 | + | ||
| 114 | + | ||
| 115 | +def test_timeout_returns_error_record(tmp_path, monkeypatch): | ||
| 116 | + def timeout(*args, **kwargs): | ||
| 117 | + raise subprocess.TimeoutExpired("worker", 1) | ||
| 118 | + monkeypatch.setattr(subprocess, "run", timeout) | ||
| 119 | + result = launch(dict(project=str(tmp_path / "corpus"), mode="query"), | ||
| 120 | + tmp_path / "timeout", 1) | ||
| 121 | + assert result["status"] == "error" | ||
| 122 | + assert "timed out" in result["error"] | ||
| 123 | + | ||
| 124 | + | ||
| 125 | +def test_resource_monitor_records_success_and_stops_over_limit(tmp_path): | ||
| 126 | + pytest.importorskip("psutil") | ||
| 127 | + from benchmarks.performance.resources import monitored_run | ||
| 128 | + for limit, expected in ((None, 0), (1, None)): | ||
| 129 | + target = tmp_path / f"resources-{limit}.jsonl" | ||
| 130 | + with (tmp_path / f"log-{limit}.txt").open("w") as log: | ||
| 131 | + code, resource = monitored_run( | ||
| 132 | + [sys.executable, "-c", "import time; data=bytearray(8*1024*1024); time.sleep(.7)"], | ||
| 133 | + cwd=tmp_path, env=dict(os.environ), log=log, timeout=10, | ||
| 134 | + samples_file=target, max_rss_mib=limit) | ||
| 135 | + assert resource["samples"] > 0 | ||
| 136 | + assert target.read_text().strip() | ||
| 137 | + assert resource["peak_tree_rss_bytes"] > 0 | ||
| 138 | + if expected == 0: | ||
| 139 | + assert code == 0 | ||
| 140 | + assert resource["stop_reason"] is None | ||
| 141 | + else: | ||
| 142 | + assert code != 0 | ||
| 143 | + assert "RSS" in resource["stop_reason"] | ||
| @@ -0,0 +1,214 @@ | |||
| 1 | +"""Bounded semantic text preparation, retry and vector-commit contracts.""" | ||
| 2 | +import hashlib | ||
| 3 | + | ||
| 4 | +import numpy as np | ||
| 5 | +import pytest | ||
| 6 | + | ||
| 7 | +from project_brain.build.builder import GraphBuilder | ||
| 8 | +from project_brain.config import Config | ||
| 9 | +from project_brain.graph.json_store import JsonStore | ||
| 10 | +from project_brain.query.engine import QueryEngine | ||
| 11 | +from project_brain.query.index import FileIndex, KeywordIndex, SymbolIndex | ||
| 12 | +from project_brain.query.semantic_index import SemanticIndex | ||
| 13 | + | ||
| 14 | + | ||
| 15 | +class Bucket: | ||
| 16 | + def __init__(self): | ||
| 17 | + self.done = {} | ||
| 18 | + self.attempts = [] | ||
| 19 | + self.max_batch = None | ||
| 20 | + self.failure = MemoryError | ||
| 21 | + self._index_type = "flat" | ||
| 22 | + | ||
| 23 | + def has(self, node_id): | ||
| 24 | + return node_id in self.done | ||
| 25 | + | ||
| 26 | + def add_many(self, ids, texts): | ||
| 27 | + self.attempts.append(list(ids)) | ||
| 28 | + assert all(len(t) <= SemanticIndex.MAX_TEXT_CHARS for t in texts) | ||
| 29 | + if self.max_batch is not None and len(ids) > self.max_batch: | ||
| 30 | + raise self.failure("memory allocation failed") | ||
| 31 | + for node_id, text in zip(ids, texts): | ||
| 32 | + assert node_id not in self.done | ||
| 33 | + self.done[node_id] = hashlib.sha256(text.encode()).hexdigest() | ||
| 34 | + | ||
| 35 | + def __len__(self): | ||
| 36 | + return len(self.done) | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +class SemanticSet: | ||
| 40 | + def __init__(self): | ||
| 41 | + self.normal = Bucket() | ||
| 42 | + self.test = Bucket() | ||
| 43 | + self.samples = [] | ||
| 44 | + self.estimate_failure = None | ||
| 45 | + self.saves = 0 | ||
| 46 | + | ||
| 47 | + def configure(self, normal, test): | ||
| 48 | + self.counts = normal, test | ||
| 49 | + | ||
| 50 | + def estimate_embed_time(self, contents, total): | ||
| 51 | + self.samples.append((len(contents), total)) | ||
| 52 | + assert len(contents) <= min(50, SemanticIndex.EMBED_BATCH_SIZE) | ||
| 53 | + assert all(len(t) <= SemanticIndex.MAX_TEXT_CHARS for t in contents) | ||
| 54 | + if self.estimate_failure: | ||
| 55 | + raise self.estimate_failure("memory allocation failed") | ||
| 56 | + return total / 100, 100 | ||
| 57 | + | ||
| 58 | + def save(self, path): | ||
| 59 | + self.saves += 1 | ||
| 60 | + | ||
| 61 | + def __len__(self): | ||
| 62 | + return len(self.normal) + len(self.test) | ||
| 63 | + | ||
| 64 | + | ||
| 65 | +def setup_builder(tmp_path, count=25): | ||
| 66 | + store = JsonStore(tmp_path) | ||
| 67 | + for i in range(count): | ||
| 68 | + store.add_node({"id": f"fn{i}", "type": "function", "name": f"retry_{i}", | ||
| 69 | + "signature": f"retry_{i}(timeout)", "is_test": i % 7 == 0, | ||
| 70 | + "body": "连接池🙂\n" * 2000}) | ||
| 71 | + store.add_node({"id": "blank", "type": "concept", "name": " "}) | ||
| 72 | + store.add_node({"id": "doc", "type": "document", "title": "文档", "path": "guide.md", | ||
| 73 | + "content_complete": True, "content": "连接池 timeout " * 1000}) | ||
| 74 | + store.add_node({"id": "section", "type": "section", "doc_id": "doc", "title": "跳过", | ||
| 75 | + "content": "完整文档通过 chunk 索引"}) | ||
| 76 | + store.add_node({"id": "chunk", "type": "document_chunk", "doc_id": "doc", | ||
| 77 | + "char_start": 3, "char_end": 3000}) | ||
| 78 | + sem = SemanticSet() | ||
| 79 | + builder = GraphBuilder(tmp_path, Config(index_body=True), store, | ||
| 80 | + KeywordIndex(), SymbolIndex(), FileIndex(), sem) | ||
| 81 | + expected = {"normal": {}, "test": {}} | ||
| 82 | + for node in store.nodes.values(): | ||
| 83 | + if builder._skip_index_node(node["type"], node): | ||
| 84 | + continue | ||
| 85 | + text = QueryEngine._index_text(node, True, store=store) | ||
| 86 | + if text and text.strip(): | ||
| 87 | + bucket = "test" if node.get("is_test") else "normal" | ||
| 88 | + expected[bucket][node["id"]] = hashlib.sha256(text[:2000].encode()).hexdigest() | ||
| 89 | + return builder, sem, expected | ||
| 90 | + | ||
| 91 | + | ||
| 92 | +def test_texts_are_released_and_match_previous_inputs(tmp_path, monkeypatch): | ||
| 93 | + builder, sem, expected = setup_builder(tmp_path, 301) | ||
| 94 | + monkeypatch.setattr(SemanticIndex, "EMBED_BATCH_SIZE", 8) | ||
| 95 | + original = QueryEngine._index_text | ||
| 96 | + | ||
| 97 | + class TrackedText(str): | ||
| 98 | + alive = 0 | ||
| 99 | + peak = 0 | ||
| 100 | + | ||
| 101 | + def __new__(cls, value): | ||
| 102 | + result = super().__new__(cls, value) | ||
| 103 | + cls.alive += 1 | ||
| 104 | + cls.peak = max(cls.peak, cls.alive) | ||
| 105 | + return result | ||
| 106 | + | ||
| 107 | + def __del__(self): | ||
| 108 | + type(self).alive -= 1 | ||
| 109 | + | ||
| 110 | + def tracked(*args, **kwargs): | ||
| 111 | + value = original(*args, **kwargs) | ||
| 112 | + return TrackedText(value) if value is not None else None | ||
| 113 | + | ||
| 114 | + monkeypatch.setattr(QueryEngine, "_index_text", staticmethod(tracked)) | ||
| 115 | + builder.build_semantic_index(persist=False) | ||
| 116 | + assert sem.normal.done == expected["normal"] | ||
| 117 | + assert sem.test.done == expected["test"] | ||
| 118 | + assert sem.counts == (len(expected["normal"]), len(expected["test"])) | ||
| 119 | + assert all(len(ids) <= 8 for b in (sem.normal, sem.test) for ids in b.attempts) | ||
| 120 | + assert TrackedText.peak <= 2 # No full-bucket joined-text retention. | ||
| 121 | + assert TrackedText.alive == 0 | ||
| 122 | + assert sem.saves == 0 | ||
| 123 | + | ||
| 124 | + | ||
| 125 | +@pytest.mark.parametrize("error", [MemoryError, RuntimeError]) | ||
| 126 | +def test_backoff_retries_only_unfinished_batch(tmp_path, monkeypatch, error): | ||
| 127 | + builder, sem, expected = setup_builder(tmp_path) | ||
| 128 | + monkeypatch.setattr(SemanticIndex, "EMBED_BATCH_SIZE", 8) | ||
| 129 | + sem.normal.max_batch = sem.test.max_batch = 2 | ||
| 130 | + sem.normal.failure = sem.test.failure = error | ||
| 131 | + first_id = next(iter(expected["normal"])) | ||
| 132 | + sem.normal.done[first_id] = expected["normal"][first_id] | ||
| 133 | + builder.build_semantic_index(persist=True) | ||
| 134 | + assert sem.normal.done == expected["normal"] | ||
| 135 | + assert sem.test.done == expected["test"] | ||
| 136 | + assert all(first_id not in ids for ids in sem.normal.attempts) | ||
| 137 | + assert sem.saves > 0 | ||
| 138 | + | ||
| 139 | + | ||
| 140 | +def test_calibration_oom_does_not_abort_embedding(tmp_path, monkeypatch): | ||
| 141 | + builder, sem, expected = setup_builder(tmp_path) | ||
| 142 | + monkeypatch.setattr(SemanticIndex, "EMBED_BATCH_SIZE", 4) | ||
| 143 | + sem.estimate_failure = MemoryError | ||
| 144 | + builder.build_semantic_index(persist=False) | ||
| 145 | + assert sem.normal.done == expected["normal"] | ||
| 146 | + assert sem.test.done == expected["test"] | ||
| 147 | + | ||
| 148 | + | ||
| 149 | +def test_failure_at_batch_one_propagates(tmp_path, monkeypatch): | ||
| 150 | + builder, sem, _ = setup_builder(tmp_path) | ||
| 151 | + monkeypatch.setattr(SemanticIndex, "EMBED_BATCH_SIZE", 2) | ||
| 152 | + sem.normal.max_batch = 0 | ||
| 153 | + with pytest.raises(MemoryError): | ||
| 154 | + builder.build_semantic_index(persist=False) | ||
| 155 | + assert not sem.normal.done | ||
| 156 | + | ||
| 157 | + | ||
| 158 | +def test_non_memory_error_is_not_retried(tmp_path, monkeypatch): | ||
| 159 | + builder, sem, _ = setup_builder(tmp_path) | ||
| 160 | + monkeypatch.setattr(SemanticIndex, "EMBED_BATCH_SIZE", 4) | ||
| 161 | + | ||
| 162 | + def invalid(*args): | ||
| 163 | + raise RuntimeError("invalid input shape") | ||
| 164 | + | ||
| 165 | + monkeypatch.setattr(sem.normal, "add_many", invalid) | ||
| 166 | + with pytest.raises(RuntimeError, match="invalid input"): | ||
| 167 | + builder.build_semantic_index(persist=False) | ||
| 168 | + | ||
| 169 | + | ||
| 170 | +def test_calibration_uses_same_truncating_inference_path(): | ||
| 171 | + seen = [] | ||
| 172 | + | ||
| 173 | + class Model: | ||
| 174 | + def embed(self, texts, **kwargs): | ||
| 175 | + seen.extend(texts) | ||
| 176 | + return iter(np.ones((len(texts), 3), dtype=np.float32)) | ||
| 177 | + | ||
| 178 | + index = SemanticIndex(shared_model=Model()) | ||
| 179 | + estimate, speed = index.estimate_embed_time(["🙂" * 10000] * 80, 1000) | ||
| 180 | + assert len(seen) == 50 | ||
| 181 | + assert all(len(t) == 2000 for t in seen) | ||
| 182 | + assert estimate > 0 and speed > 0 | ||
| 183 | + | ||
| 184 | + | ||
| 185 | +def test_failed_vector_add_does_not_mark_ids_complete(monkeypatch): | ||
| 186 | + index = SemanticIndex() | ||
| 187 | + | ||
| 188 | + class FailedIndex: | ||
| 189 | + def add_with_ids(self, *args): | ||
| 190 | + raise RuntimeError("memory allocation failed") | ||
| 191 | + | ||
| 192 | + index._index = FailedIndex() | ||
| 193 | + monkeypatch.setattr(index, "_embed", lambda texts: np.ones((len(texts), 3), dtype=np.float32)) | ||
| 194 | + with pytest.raises(RuntimeError, match="memory"): | ||
| 195 | + index.add_many(["new"], ["text"]) | ||
| 196 | + assert not index.has("new") | ||
| 197 | + assert index._int_to_doc == {} | ||
| 198 | + assert index._next_int == 0 | ||
| 199 | + | ||
| 200 | + | ||
| 201 | +def test_inference_failure_preserves_existing_mapping(monkeypatch): | ||
| 202 | + index = SemanticIndex() | ||
| 203 | + index._doc_to_int = {"old": 0} | ||
| 204 | + index._int_to_doc = {0: "old"} | ||
| 205 | + index._next_int = 1 | ||
| 206 | + | ||
| 207 | + def fail(texts): | ||
| 208 | + raise MemoryError("memory") | ||
| 209 | + | ||
| 210 | + monkeypatch.setattr(index, "_embed", fail) | ||
| 211 | + with pytest.raises(MemoryError): | ||
| 212 | + index.add("old", "replacement") | ||
| 213 | + assert index._doc_to_int == {"old": 0} | ||
| 214 | + assert index._int_to_doc == {0: "old"} | ||
| @@ -0,0 +1,154 @@ | |||
| 1 | +"""Persistence compatibility, lazy conversion and failed-publication contracts.""" | ||
| 2 | +import io | ||
| 3 | +import json | ||
| 4 | +from pathlib import Path | ||
| 5 | + | ||
| 6 | +import pytest | ||
| 7 | + | ||
| 8 | +from project_brain.graph.generation import GenerationRepository | ||
| 9 | +from project_brain.graph.json_store import JsonStore | ||
| 10 | +from project_brain.graph.models import Edge | ||
| 11 | +from project_brain.json_stream import dump_json | ||
| 12 | +from project_brain.query.index import KeywordIndex | ||
| 13 | +from project_brain.query.semantic_index import SemanticIndex | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +def test_encoder_flushes_before_converting_every_record(): | ||
| 17 | + converted = [] | ||
| 18 | + writes = [] | ||
| 19 | + | ||
| 20 | + class Record: | ||
| 21 | + pass | ||
| 22 | + | ||
| 23 | + class Sink(io.StringIO): | ||
| 24 | + def write(self, value): | ||
| 25 | + writes.append(len(converted)) | ||
| 26 | + return super().write(value) | ||
| 27 | + | ||
| 28 | + def convert(value): | ||
| 29 | + converted.append(value) | ||
| 30 | + return {"text": "连接池🙂" * 100} | ||
| 31 | + | ||
| 32 | + sink = Sink() | ||
| 33 | + dump_json([Record() for _ in range(1000)], sink, default=convert) | ||
| 34 | + assert 0 < writes[0] < 1000 | ||
| 35 | + assert len(writes) > 1 | ||
| 36 | + assert len(json.loads(sink.getvalue())) == 1000 | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +@pytest.mark.parametrize("empty", [False, True]) | ||
| 40 | +def test_graph_bytes_match_original_serialization(tmp_path, empty): | ||
| 41 | + store = JsonStore(tmp_path) | ||
| 42 | + if not empty: | ||
| 43 | + store.add_node({"id": '节点"🙂', "type": "function", "body": "多行\r\n内容", | ||
| 44 | + "facts": [{"a": [None, True, 1.25]}]}) | ||
| 45 | + store.add_edge(Edge("e", "CALL", '节点"🙂', "target", {"locations": [{"line": 1}]})) | ||
| 46 | + expected_nodes = json.dumps(store.nodes, ensure_ascii=False, indent=2) | ||
| 47 | + expected_edges = json.dumps([e.to_dict() for e in store.edges], ensure_ascii=False, indent=2) | ||
| 48 | + store.save(str(tmp_path)) | ||
| 49 | + assert (tmp_path / "nodes.json").read_text(encoding="utf-8") == expected_nodes | ||
| 50 | + assert (tmp_path / "edges.json").read_text(encoding="utf-8") == expected_edges | ||
| 51 | + loaded = JsonStore(tmp_path) | ||
| 52 | + loaded.load(str(tmp_path)) | ||
| 53 | + assert loaded.nodes == store.nodes | ||
| 54 | + assert loaded.edges == store.edges | ||
| 55 | + | ||
| 56 | + | ||
| 57 | +def test_keyword_bytes_match_and_round_trip(tmp_path): | ||
| 58 | + index = KeywordIndex() | ||
| 59 | + index.add("函数🙂", "连接池 retry timeout") | ||
| 60 | + index.add("chunk", "文档 timeout", retain_source=False) | ||
| 61 | + expected = json.dumps({ | ||
| 62 | + "tokenizer_version": index.TOKENIZER_VERSION, "postings": index.postings, | ||
| 63 | + "documents": index.documents, "doc_len": index.doc_len, | ||
| 64 | + "doc_tokens": {key: list(value) for key, value in index._doc_tokens.items()}, | ||
| 65 | + }, ensure_ascii=False) | ||
| 66 | + index.save(tmp_path) | ||
| 67 | + assert (tmp_path / "keyword_index.json").read_text(encoding="utf-8") == expected | ||
| 68 | + restored = KeywordIndex() | ||
| 69 | + assert restored.load(tmp_path) | ||
| 70 | + assert restored.snapshot() == index.snapshot() | ||
| 71 | + assert restored.search("连接池 timeout") == index.search("连接池 timeout") | ||
| 72 | + assert list(tmp_path.glob(".*.tmp")) == [] | ||
| 73 | + | ||
| 74 | + | ||
| 75 | +@pytest.mark.parametrize("failure", ["encoding", "replace"]) | ||
| 76 | +def test_keyword_failure_preserves_published_file(tmp_path, monkeypatch, failure): | ||
| 77 | + import project_brain.query.index as module | ||
| 78 | + | ||
| 79 | + index = KeywordIndex() | ||
| 80 | + index.add("n", "retry") | ||
| 81 | + index.save(tmp_path) | ||
| 82 | + before = (tmp_path / "keyword_index.json").read_bytes() | ||
| 83 | + if failure == "encoding": | ||
| 84 | + index.documents["n"] = object() | ||
| 85 | + error = TypeError | ||
| 86 | + else: | ||
| 87 | + def fail(*args): | ||
| 88 | + raise OSError("injected replace failure") | ||
| 89 | + monkeypatch.setattr(module.os, "replace", fail) | ||
| 90 | + error = OSError | ||
| 91 | + with pytest.raises(error): | ||
| 92 | + index.save(tmp_path) | ||
| 93 | + assert (tmp_path / "keyword_index.json").read_bytes() == before | ||
| 94 | + assert list(tmp_path.glob(".*.tmp")) == [] | ||
| 95 | + | ||
| 96 | + | ||
| 97 | +def test_streaming_failure_does_not_publish_partial_generation(tmp_path): | ||
| 98 | + repo = GenerationRepository(tmp_path / "graph") | ||
| 99 | + store = JsonStore(tmp_path) | ||
| 100 | + store.add_node({"id": "n", "type": "function"}) | ||
| 101 | + keyword = KeywordIndex() | ||
| 102 | + keyword.add("n", "retry") | ||
| 103 | + before = repo.publish_graph_state(store, keyword) | ||
| 104 | + keyword.documents["n"] = object() | ||
| 105 | + with pytest.raises(TypeError): | ||
| 106 | + repo.publish_graph_state(store, keyword) | ||
| 107 | + assert repo.current_path() == before | ||
| 108 | + assert repo.validate(before) | ||
| 109 | + assert not list(repo.generations.glob("*.tmp")) | ||
| 110 | + | ||
| 111 | + | ||
| 112 | +def test_semantic_mapping_streams_without_faiss_or_model(tmp_path): | ||
| 113 | + # The ID artifact can be tested with no vectors or model downloads. | ||
| 114 | + sem = SemanticIndex() | ||
| 115 | + sem._doc_to_int = {"函数🙂": 0, "other": 1} | ||
| 116 | + sem._int_to_doc = {0: "函数🙂", 1: "other"} | ||
| 117 | + sem._next_int = 2 | ||
| 118 | + expected = json.dumps({ | ||
| 119 | + "format_version": 2, "doc_to_int": sem._doc_to_int, | ||
| 120 | + "int_to_doc": {str(k): v for k, v in sem._int_to_doc.items()}, | ||
| 121 | + "next_int": 2, "dim": None, "index_type": sem._index_type, | ||
| 122 | + }, ensure_ascii=False) | ||
| 123 | + sem.save(tmp_path) | ||
| 124 | + target = tmp_path / "semantic_ids.json" | ||
| 125 | + assert target.read_text(encoding="utf-8") == expected | ||
| 126 | + before = target.read_bytes() | ||
| 127 | + sem._doc_to_int["invalid"] = object() | ||
| 128 | + with pytest.raises(TypeError): | ||
| 129 | + sem.save(tmp_path) | ||
| 130 | + assert target.read_bytes() == before | ||
| 131 | + assert not list(tmp_path.glob(".*.tmp")) | ||
| 132 | + | ||
| 133 | + | ||
| 134 | +def test_index_temp_names_preserve_legacy_windows_path_budget(tmp_path, monkeypatch): | ||
| 135 | + import os | ||
| 136 | + | ||
| 137 | + sources = [] | ||
| 138 | + replace = os.replace | ||
| 139 | + | ||
| 140 | + def record(source, target): | ||
| 141 | + sources.append((Path(source), Path(target))) | ||
| 142 | + return replace(source, target) | ||
| 143 | + | ||
| 144 | + monkeypatch.setattr(os, "replace", record) | ||
| 145 | + keyword = KeywordIndex() | ||
| 146 | + semantic = SemanticIndex() | ||
| 147 | + for _ in range(2): | ||
| 148 | + keyword.save(tmp_path) | ||
| 149 | + semantic.save(tmp_path) | ||
| 150 | + assert len({source for source, _ in sources}) == 4 | ||
| 151 | + for source, target in sources: | ||
| 152 | + assert source.parent == target.parent | ||
| 153 | + assert len(source.name) <= len(target.name + ".tmp") | ||
| 154 | + assert not list(tmp_path.glob(".*.tmp")) | ||