Open
feat/search-lazy-loading #15
feat/search-lazy-loading #15
Open
hid24429644Add on Oct 20
Total: 20 files changed+1677-16
@@ -17,3 +17,6 @@ dist/
17 17 
18# ZCode agent workspace18# 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```bash790```bash
791# 克隆仓库791# 克隆仓库
792-git clone https://gitcode.com/DeepRust/project-brain.git792+git clone https://gitcode.com/xuanwu/bot-brain.git
793-cd project-brain793+cd bot-brain
794 794 
795# 安装依赖795# 安装依赖
796uv sync --extra dev796uv sync --extra dev
@@ -970,8 +970,8 @@ MIT License
970 970 
971## 联系方式971## 联系方式
972 972 
973-- 项目地址:https://gitcode.com/DeepRust/project-brain973+- 项目地址:https://gitcode.com/xuanwu/bot-brain
974-- 问题反馈:https://gitcode.com/DeepRust/project-brain/issues974+- 问题反馈:https://gitcode.com/xuanwu/bot-brain/issues
975 975 
976## 致谢976## 致谢
977 977 
@@ -0,0 +1,104 @@
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 完整性验证仍会流式校验文件哈希,不会将所有节点反序列化到内存。
@@ -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)
@@ -133,6 +133,11 @@ bot-brain build --explain-profile
133bot-brain build --store-doc-content "README.md" --store-doc-content "docs/**"133bot-brain build --store-doc-content "README.md" --store-doc-content "docs/**"
134```134```
135 135 
136+源码解析期间会显示 `AST parse: 已处理文件数/总数 (百分比)`,附带失败数、
137+解析阶段已用时间和最近处理的文件路径;常规更新最多每秒一次,结束时输出最终进度。
138+计数包括读取或解析失败的文件,失败信息会在阶段汇总中列出。AST 达到 100% 后还会
139+继续安装图谱节点和解析跨文件关系,这两个步骤会分别输出阶段提示。
140+ 
136## 6. 查看项目信息141## 6. 查看项目信息
137 142 
138```bash143```bash
@@ -165,6 +170,10 @@ Knowledge Graph:
165bot-brain search "订单超时"170bot-brain search "订单超时"
166bot-brain search "timeout" --top-k 5171bot-brain search "timeout" --top-k 5
167 172 
173+# 对比节点全量加载与按需读取(JSON 后端、keyword 策略)
174+bot-brain search "timeout" --search-loading full
175+bot-brain search "timeout" --search-loading lazy
176+ 
168# 按名定位符号177# 按名定位符号
169bot-brain locate OrderService178bot-brain locate OrderService
170bot-brain locate Poll --kind class179bot-brain locate Poll --kind class
@@ -193,6 +202,77 @@ bot-brain search "config" --json
193 202 
194用 `bot-brain --help` 查看所有命令。203用 `bot-brain --help` 查看所有命令。
195 204 
205+### 7.1 search 的全量加载与按需读取
206+ 
207+以下选项需要使用包含 JSON 偏移索引优化的版本。若 `bot-brain search --help`
208+没有 `--search-loading`,需先升级到该实现;只同步本指南不会改变旧版程序行为。
209+ 
210+```bash
211+bot-brain search "timeout" --search-loading auto # 默认,自动选择
212+bot-brain search "timeout" --search-loading full # 强制完整初始化
213+bot-brain search "timeout" --search-loading lazy # 强制按需读取,不兼容时报错
214+```
215+ 
216+`auto` 仅在 JSON 后端、全局配置为 `keyword`、图谱 schema 与配置摘要一致,
217+且有兼容的节点偏移索引时启用按需路径。SQLite、hybrid/semantic、缺少索引或
218+配置不兼容时回退原初始化路径;它不会因一次查询临时指定 keyword 就忽略
219+全局策略的限制。目前这项优化只接入独立 CLI `search`,其他命令仍沿用原路径。
220+ 
221+新构建将节点写入 `nodes.json` 时同步生成 `node_offsets.json`:
222+ 
223+```text
224+BM25 倒排检索 → 候选节点 ID → 节点缓存
225+ ↓ 未命中
226+ 偏移索引中的 [字节位置, 长度]
227+ ↓
228+ seek/read nodes.json → 只解析该节点
229+```
230+ 
231+偏移只覆盖外层 ID 键对应的节点对象,不包括键名或分隔逗号;中文、emoji
232+和换行按 UTF-8 字节计数。新格式 v2 明确指向 `nodes.json`,无需重复保存
233+`nodes.jsonl`;旧格式 v1 的 JSONL 图谱仍兼容。节点数据与偏移索引属于同一
234+不可变 generation,不能手工修改节点文件后继续使用旧偏移。
235+ 
236+按需初始化仍完整加载 `keyword_index.json` 和轻量偏移索引;不全量反序列化
237+`nodes.json` / `edges.json`,不重建非搜索辅助索引。命中后的文件路径、文档
238+正文等关联信息也通过节点 ID 读取。generation 完整性校验仍会流式读取文件
239+计算哈希,因此避免全量反序列化不等于避免所有全文件 I/O。
240+ 
241+**已加载就复用**:同一个服务实例已加载完整图谱时,search 直接查询内存
242+中的节点字典,不切换到按需文件读取。GUI 若通过该服务查询也能复用;独立
243+CLI 不会自动连接已运行的 `serve`,两者不能直接共享 Python 内存。
244+ 
245+### 7.2 搜索启动与性能验证
246+ 
247+```bash
248+time bot-brain search 重试 # 含启动
249+echo 'search 重试' | bot-brain repl # 常驻进程内查询
250+```
251+ 
252+独立 CLI 的总耗时包含进程启动、依赖导入、图谱初始化和查询。REPL 第一次
253+查询也包含初始化,不能直接把上面两条命令的耗时差当作纯启动开销;应在
254+同一个 REPL / 服务实例中重复查询,单独比较初始化和后续查询的耗时。
255+ 
256+JSON keyword 场景可在同一图谱上分别运行 `--search-loading full` 与 `lazy`
257+进行比较。按需方式主要减少新进程初始化与内存占用;连续查询仍可能因为
258+随机读取和单节点反序列化略慢,不能保证每条查询都更快。
259+ 
260+CPython 实测参考:167,105 个节点,3 轮新进程、8 类查询,每类再连续查询
261+5 遍;未清空操作系统文件缓存,full/lazy 交替顺序。两种方式的 288 次查询
262+及 2 次真实 CLI 查询结果一致(仅排除随时间变化的 freshness 年龄字段)。
263+ 
264+| 指标 | 全量加载 | 按需加载 |
265+|---|---:|---:|
266+| 初始化耗时中位数(不含依赖导入) | 14.66 秒 | 4.37 秒 |
267+| 真实 CLI 总耗时(各测一次) | 18.15 秒 | 5.71 秒 |
268+| RSS 采样峰值中位数(每 0.5 秒采样) | 4015 MiB | 2005 MiB |
269+| 连续查询 p50 | 1.85 ms | 2.89 ms |
270+| 连续查询 p95 | 43.77 ms | 44.85 ms |
271+ 
272+全部 167,105 个节点另按偏移逐个读取,与全量解析结果一致;新增偏移索引
273+约 5.67 MiB,不再生成 JSONL 节点副本。这是该机器和语料的观测结果,
274+不代表其他仓库的固定耗时,也不是清空磁盘缓存后的测试。
275+ 
196### 拉取华为内源 Wiki276### 拉取华为内源 Wiki
197 277 
198```bash278```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 raw920 result = json.loads(raw) if isinstance(raw, str) else raw
916 # Business errors (e.g. "Module not found", "Symbol not found") return921 # 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",
@@ -159,6 +159,7 @@ class GraphBuilder:
159 )159 )
160 result = code_parser.parse_all(160 result = code_parser.parse_all(
161 self.store, self.keyword_index, self.symbol_index, self.file_index,161 self.store, self.keyword_index, self.symbol_index, self.file_index,
162+ progress=progress,
162 )163 )
163 p(f" Files: {result.files_parsed}, Functions: {result.functions_found}, "164 p(f" Files: {result.files_parsed}, Functions: {result.functions_found}, "
164 f"Classes: {result.classes_found}, Symbols: {result.symbols_found}")165 f"Classes: {result.classes_found}, Symbols: {result.symbols_found}")
@@ -1,9 +1,10 @@
1from __future__ import annotations1from __future__ import annotations
2 2 
3import hashlib3import hashlib
4+import time
4from dataclasses import asdict, dataclass, field, is_dataclass5from dataclasses import asdict, dataclass, field, is_dataclass
5from pathlib import Path6from pathlib import Path
6-from typing import Any7+from typing import Any, Callable
7 8 
8from .scanner import FileScanner, decode_file_bytes9from .scanner import FileScanner, decode_file_bytes
9from .languages.base import FunctionInfo, LanguageRule10from .languages.base import FunctionInfo, LanguageRule
@@ -121,6 +122,8 @@ class CodeParser:
121 keyword_index: KeywordIndex,122 keyword_index: KeywordIndex,
122 symbol_index: SymbolIndex,123 symbol_index: SymbolIndex,
123 file_index: FileIndex,124 file_index: FileIndex,
125+ *,
126+ progress: Callable[[str], None] | None = None,
124 ) -> BuildResult:127 ) -> BuildResult:
125 result = BuildResult()128 result = BuildResult()
126 modules_seen: dict[str, str] = {}129 modules_seen: dict[str, str] = {}
@@ -146,7 +149,32 @@ class CodeParser:
146 rust_crate_root_dirs: set[str] = set()149 rust_crate_root_dirs: set[str] = set()
147 file_parse_results: list[tuple[Path, str, str, Any, str, bytes]] = []150 file_parse_results: list[tuple[Path, str, str, Any, str, bytes]] = []
148 151 
149- for file_path, language in self.scanner.scan_code_files():152+ code_files = self.scanner.scan_code_files()
153+ total = 0
154+ if progress is not None:
155+ progress(" Scanning source files for AST parsing...")
156+ code_files = [(path, lang) for path, lang in code_files if lang in self.rules]
157+ total = len(code_files)
158+ started = time.monotonic()
159+ last_report = started
160+ 
161+ def report(completed: int, path: str = "", *, force: bool = False) -> None:
162+ nonlocal last_report
163+ if progress is None:
164+ return
165+ now = time.monotonic()
166+ if not force and completed != total and now - last_report < 1.0:
167+ return
168+ percent = 100.0 * completed / total if total else 100.0
169+ progress(
170+ f" AST parse: {completed}/{total} ({percent:.1f}%)"
171+ f" | failed={result.files_failed} | elapsed={now - started:.1f}s"
172+ + (f" | {path}" if path else "")
173+ )
174+ last_report = now
175+ 
176+ report(0, force=True)
177+ for completed, (file_path, language) in enumerate(code_files, 1):
150 rule = self.rules.get(language)178 rule = self.rules.get(language)
151 if not rule:179 if not rule:
152 continue180 continue
@@ -162,6 +190,7 @@ class CodeParser:
162 except Exception as e:190 except Exception as e:
163 result.files_failed += 1191 result.files_failed += 1
164 result.errors.append(f"{file_path}: {e}")192 result.errors.append(f"{file_path}: {e}")
193+ report(completed, rel_path)
165 continue194 continue
166 195 
167 try:196 try:
@@ -237,6 +266,12 @@ class CodeParser:
237 parse_error=str(e),266 parse_error=str(e),
238 )267 )
239 result.fallback_files.append(rel_path)268 result.fallback_files.append(rel_path)
269+ finally:
270+ report(completed, rel_path)
271+ 
272+ del code_files
273+ if progress is not None:
274+ progress(f" Installing code graph nodes ({len(file_parse_results)} parsed files)...")
240 275 
241 # Create all directory ancestors before installing files. This avoids276 # Create all directory ancestors before installing files. This avoids
242 # dangling parent references for a file added directly in a deep tree.277 # dangling parent references for a file added directly in a deep tree.
@@ -572,10 +607,15 @@ class CodeParser:
572 # Resolve every derived relation from facts persisted on the completed607 # Resolve every derived relation from facts persisted on the completed
573 # node set. Incremental builds use the same resolver after installing608 # node set. Incremental builds use the same resolver after installing
574 # their whole debounce batch, so the two paths cannot drift.609 # their whole debounce batch, so the two paths cannot drift.
610+ if progress is not None:
611+ progress(" Resolving cross-file code relations...")
575 refresh_module_metadata(store)612 refresh_module_metadata(store)
576 relation_edges = RelationResolver(store).replace_all()613 relation_edges = RelationResolver(store).replace_all()
577 result.edges_created += len(relation_edges)614 result.edges_created += len(relation_edges)
578 615 
616+ if progress is not None:
617+ progress(" Code graph installation and relation resolution complete.")
618+ 
579 return result619 return result
580 620 
581 # ---- Fallback for files that fail to tree-sitter parse --------------621 # ---- Fallback for files that fail to tree-sitter parse --------------
@@ -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))
@@ -199,6 +199,9 @@ class JsonStore(GraphStore):
199 return results199 return results
200 200 
201 def save(self, path: str) -> None:201 def save(self, path: str) -> None:
202+ self._save(path, with_offsets=False)
203+ 
204+ def _save(self, path: str, *, with_offsets: bool) -> None:
202 p = Path(path)205 p = Path(path)
203 p.mkdir(parents=True, exist_ok=True)206 p.mkdir(parents=True, exist_ok=True)
204 nodes_file = p / "nodes.json"207 nodes_file = p / "nodes.json"
@@ -208,10 +211,14 @@ class JsonStore(GraphStore):
208 edges_tmp = p / f".edges.json.{token}.tmp"211 edges_tmp = p / f".edges.json.{token}.tmp"
209 with self._lock:212 with self._lock:
210 try:213 try:
211- nodes_tmp.write_text(214+ if with_offsets:
212- json.dumps(self.nodes, ensure_ascii=False, indent=2),215+ from .offset_store import write_node_offsets
213- encoding="utf-8",216+ write_node_offsets(self.nodes.values(), p)
214- )217+ else:
218+ nodes_tmp.write_text(
219+ json.dumps(self.nodes, ensure_ascii=False, indent=2),
220+ encoding="utf-8",
221+ )
215 edges_tmp.write_text(222 edges_tmp.write_text(
216 json.dumps(223 json.dumps(
217 [e.to_dict() for e in self.edges],224 [e.to_dict() for e in self.edges],
@@ -220,7 +227,8 @@ class JsonStore(GraphStore):
220 ),227 ),
221 encoding="utf-8",228 encoding="utf-8",
222 )229 )
223- os.replace(nodes_tmp, nodes_file)230+ if not with_offsets:
231+ os.replace(nodes_tmp, nodes_file)
224 os.replace(edges_tmp, edges_file)232 os.replace(edges_tmp, edges_file)
225 finally:233 finally:
226 for tmp in (nodes_tmp, edges_tmp):234 for tmp in (nodes_tmp, edges_tmp):
@@ -231,6 +239,10 @@ class JsonStore(GraphStore):
231 # temp file cannot collide with a later save.239 # temp file cannot collide with a later save.
232 pass240 pass
233 241 
242+ def save_with_offsets(self, path: str) -> None:
243+ """Save one nodes.json with offsets from the same locked snapshot."""
244+ self._save(path, with_offsets=True)
245+ 
234 def load(self, path: str) -> None:246 def load(self, path: str) -> None:
235 with self._lock:247 with self._lock:
236 p = Path(path)248 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+ with index_tmp.open("w", encoding="utf-8") as stream:
39+ json.dump({"format_version": 2, "data_file": "nodes.json", "data_size": size,
40+ "offsets": offsets}, stream, ensure_ascii=False, separators=(",", ":"))
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
@@ -84,6 +84,7 @@ class ProjectBrainServer:
84 self._file_index = None84 self._file_index = None
85 self._query_engine = None85 self._query_engine = None
86 self._initialized = False86 self._initialized = False
87+ self._search_only = False
87 self._watcher_manager = None88 self._watcher_manager = None
88 self._updater = None89 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 a129 # 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_only134 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_legacy192 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 None295 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 shutdown2164 # 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 = True2169 self._closed = True
2107 return2170 return
2108 stopped = self._stop_watcher()2171 stopped = self._stop_watcher()
@@ -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"]