pystepmap 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1091 @@
1
+ """平台的存储:平台数据目录下的一个 SQLite 文件(DB_NAME)。数据目录默认 ~/.pystepmap,环境变量 PYSTEPMAP_HOME 可以改
2
+ (default_home)——放在这里而不是 app.py:pystepmap mcp 要用它们,又不能把平台接口和运行测试的代码导入进来。
3
+
4
+ 五张表(结构版本记在 PRAGMA user_version):
5
+
6
+ - projects:项目。id 是短的随机串;root 是解析过的绝对路径,唯一;config_json 是项目的分析配置(引擎的配置 JSON,
7
+ 用户给的原样,{} 表示全用默认值)。结构版本 3 加的两列:test_command 测试命令(用户填的原文,NULL = 没填)、
8
+ test_confirmed 用户确认过这条命令的影响(0 / 1;命令一改就清零,见 set_test_command、confirm_test_command)。
9
+ - analyses:每次分析。summary_json 是摘要(见 worker.summarize);graph_gz 是 gzip 压缩的图 JSON(引擎输出原样),
10
+ graph_size 是压缩前的字节数;graph_gz 放在最后一列(不取它时 SQLite 不读它的溢出页)。删项目时一起删。
11
+ 结构版本 2 加的五列(版本 1 留下的行:config_json、file_lines_json、diff_json 为 NULL,graph_sha、base_id 升级时补上):
12
+ config_json 这次分析用的配置
13
+ graph_sha 图 JSON 字节的 sha256
14
+ base_id 对比基准的分析 id;NULL = 没有可比的;等于自己的 id = "看过的状态"(标为已看的那次,或之后流程
15
+ 没变、接着带记号的重新分析),对外报成没有基准
16
+ file_lines_json query.file_lines(图):相对路径 → 涉及这个文件的功能线 sid
17
+ diff_json diff_to_json(diff_graphs(基准, 这次));没有基准或差异为空时 NULL
18
+ 保存时定基准、算差异的规则在 flows.compare_with_previous(对比基准只在标为已看时移动);清理旧分析时另外留下
19
+ 最新一次的基准那次。
20
+ - reviews(结构版本 5):变更记录。每次"标为已看"时,把那次的流程差异(diff_json,diff_to_json 的结果原样)连同
21
+ 标的时间、是哪次分析相对哪次(head / base 的 id 和时间)、概要(summary_json,见 review_summary)存一条;每个项目
22
+ 留最近 KEEP_REVIEWS 条。删项目时一起删。结构版本 6 加 graph_size、graph_gz:head 那次分析的图(压缩好的原样,
23
+ 放在最后一列),在画布上回看这条记录用。
24
+ - line_overrides:手工改的功能线标题和分组,按功能线的 sid 存;title / group_name 为空表示这一项不改。删项目时一起删。
25
+ - runs(结构版本 3):在平台上运行测试的结果,全量的、只跑一条功能线的各留最近几次(KEEP_RUNS,见 prune_runs)。
26
+ 删项目时一起删。结构版本 4 加 scope_json(这次运行的范围,NULL = 全部测试),projects 加 mcp_tests(允许 MCP 请平台
27
+ 运行单条功能线的测试,0 / 1)。
28
+ analysis_id 这次运行用的那次分析(不是外键:那次分析以后被清理掉,这一行照样在)
29
+ started_at、finished_at、command(运行时的测试命令原文)
30
+ status ok 命令退出码 0 / tests_failed 有测试失败 / error 命令没跑成或没收到记录 / timeout / cancelled
31
+ exit_code 命令的退出码;没跑完时 NULL
32
+ summary_json 汇总(形状见 flows.run_project_tests):计数、耗时、核对结果、覆盖、不符的前几条、中文说明
33
+ paths_size 运行路径 JSON 压缩前的字节数;没有路径时 NULL
34
+ tests_json 每个测试一项 [{test, outcome, seconds, cases, functions}](取一次运行时用,列运行时不读)
35
+ paths_index {"meta": {键: [起, 止]}, "tests": {测试 node id: [起, 止]}}:运行一级的各项、每个测试在 paths_gz
36
+ 里的那一段(见 _pack_paths)
37
+ functions_gz 函数索引 {"functions": [运行里的函数 sid,每个一次], "tests": {测试 node id: [下标…]}} 的 gzip(按功能
38
+ 线数一个测试执行了几个函数用,不用解开整份路径);没跑完时 NULL。本阶段较早的代码建的版本 3 的库没有
39
+ 这一列,打开时补上(_fix_early_v3)
40
+ paths_gz run_paths_to_json 的结果,一个标准的 gzip(没跑完时 NULL),每个测试前后做了 Z_FULL_FLUSH,一个测试
41
+ 可以只读出、解开它那一段(run_test_paths);放在最后一列,不取它时 SQLite 不读它的溢出页
42
+ 存的只有标识、次数、耗时、退出方式、异常类型名、测试的 node id(去掉参数化后缀)和通过 / 失败——没有任何取值,也
43
+ 没有 pytest 的输出(那个只在 runner 的内存里)。
44
+
45
+ 打开时:新库直接建最新版本的表;旧版本的库先复制一份成同目录的 pystepmap.db.bak-v<旧版本>(0600;已经有这个文件时不再
46
+ 复制、不覆盖;复制失败就不升级,报错),再按 _MIGRATIONS 逐级升级(每一级一个函数),全部在一个写事务里,中途出错
47
+ 整个回滚、库保持原样;更新版本建的库拒绝打开,且在改任何东西(包括切换 WAL)之前就拒绝。副本是旧版本的 pystepmap
48
+ 能直接打开的库(把它改名回 pystepmap.db 就回到升级前)。
49
+
50
+ 每次读写各开一个连接(FastAPI 在线程池里调用,连接不跨线程);写操作用 BEGIN IMMEDIATE 一次拿到写锁,库是 WAL
51
+ 模式,读不被写挡住;平台服务和 MCP 两个进程可以同时打开同一个库。另外 Store 从打开到 close()(或被回收)一直开着
52
+ 一个闲着的连接,不用它读写:SQLite 在所有进程里最后一个连接关上时做检查点并删掉 -wal、-shm,下次再建;两个进程
53
+ 各自每次调用都开关连接时,删和建正好撞上另一个进程在开库、读库,偶尔会读出 disk I/O error(SQLITE_IOERR_SHORT_READ)
54
+ 之类的错误(库本身没坏)。有这个连接在,-wal、-shm 就一直在。sqlite3 的错误都转成 StoreError(中文信息)。
55
+ 这里不是流程代码,不加 pystepkit 标记。
56
+ """
57
+
58
+ from __future__ import annotations
59
+
60
+ import gzip
61
+ import hashlib
62
+ import json
63
+ import logging
64
+ import os
65
+ import secrets
66
+ import sqlite3
67
+ import stat
68
+ import string
69
+ import zlib
70
+ from collections.abc import Callable, Iterator
71
+ from contextlib import contextmanager
72
+ from dataclasses import dataclass
73
+ from datetime import UTC, datetime
74
+ from pathlib import Path
75
+
76
+ SCHEMA_VERSION = 6
77
+ KEEP_REVIEWS = 10 # 每个项目留最近几条变更记录(标为已看时存的那次流程变化)
78
+ DB_NAME = "pystepmap.db" # 平台数据目录里的库文件
79
+ _ID_ALPHABET = string.ascii_lowercase + string.digits
80
+ _ID_LENGTH = 8
81
+
82
+ logger = logging.getLogger(__name__)
83
+
84
+
85
+ def default_home() -> Path:
86
+ """平台数据目录:环境变量 PYSTEPMAP_HOME,没有时 ~/.pystepmap。"""
87
+ return Path(os.environ.get("PYSTEPMAP_HOME") or "~/.pystepmap").expanduser()
88
+
89
+ SERVE_LOCK = "pystepmap.lock" # pystepmap serve 的锁文件(cli.LOCK_NAME 同名):两行,进程号、端口
90
+
91
+
92
+ def serve_port(home: Path) -> int | None:
93
+ """这个数据目录上正在运行的 pystepmap serve 监听的端口;没有在运行(锁文件没人锁着)、读不出端口时 None。
94
+ 只读:试着拿一下锁,拿得到说明没有服务在跑,马上放掉。没有 flock 的系统上只看文件里写的端口。"""
95
+ try:
96
+ fd = os.open(Path(home) / SERVE_LOCK, os.O_RDONLY)
97
+ except OSError:
98
+ return None
99
+ try:
100
+ try:
101
+ import fcntl
102
+ except ImportError:
103
+ fcntl = None
104
+ if fcntl is not None:
105
+ try:
106
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
107
+ except OSError:
108
+ pass # 有人锁着:服务在跑
109
+ else:
110
+ fcntl.flock(fd, fcntl.LOCK_UN)
111
+ return None
112
+ lines = os.read(fd, 100).decode("utf-8", "replace").split("\n")
113
+ port = int(lines[1]) if len(lines) > 1 and lines[1].strip().isdigit() else 0
114
+ return port if 0 < port < 65536 else None
115
+ finally:
116
+ os.close(fd)
117
+
118
+
119
+ _PROJECTS = """
120
+ CREATE TABLE projects (
121
+ id TEXT PRIMARY KEY,
122
+ name TEXT NOT NULL,
123
+ root TEXT NOT NULL UNIQUE,
124
+ config_json TEXT NOT NULL,
125
+ created_at TEXT NOT NULL,
126
+ updated_at TEXT NOT NULL,
127
+ test_command TEXT,
128
+ test_confirmed INTEGER NOT NULL DEFAULT 0,
129
+ mcp_tests INTEGER NOT NULL DEFAULT 0
130
+ )"""
131
+ _ANALYSES = """
132
+ CREATE TABLE {name} (
133
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
134
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
135
+ created_at TEXT NOT NULL,
136
+ engine_version TEXT NOT NULL,
137
+ summary_json TEXT NOT NULL,
138
+ graph_size INTEGER NOT NULL,
139
+ config_json TEXT,
140
+ graph_sha TEXT,
141
+ base_id INTEGER,
142
+ file_lines_json TEXT,
143
+ diff_json TEXT,
144
+ graph_gz BLOB NOT NULL
145
+ )"""
146
+ _ANALYSES_INDEX = "CREATE INDEX analyses_by_project ON analyses(project_id, id)"
147
+ _OVERRIDES = """
148
+ CREATE TABLE line_overrides (
149
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
150
+ line_sid TEXT NOT NULL,
151
+ title TEXT,
152
+ group_name TEXT,
153
+ updated_at TEXT NOT NULL,
154
+ PRIMARY KEY (project_id, line_sid)
155
+ )"""
156
+ _RUNS = """
157
+ CREATE TABLE runs (
158
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
159
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
160
+ analysis_id INTEGER,
161
+ started_at TEXT NOT NULL,
162
+ finished_at TEXT NOT NULL,
163
+ command TEXT NOT NULL,
164
+ status TEXT NOT NULL,
165
+ exit_code INTEGER,
166
+ summary_json TEXT NOT NULL,
167
+ paths_size INTEGER,
168
+ tests_json TEXT,
169
+ paths_index TEXT,
170
+ functions_gz BLOB,
171
+ paths_gz BLOB,
172
+ scope_json TEXT
173
+ )"""
174
+ _RUNS_INDEX = "CREATE INDEX runs_by_project ON runs(project_id, id)"
175
+ _REVIEWS = """
176
+ CREATE TABLE reviews (
177
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
178
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
179
+ acked_at TEXT NOT NULL,
180
+ head_id INTEGER NOT NULL,
181
+ head_at TEXT NOT NULL,
182
+ base_id INTEGER,
183
+ base_at TEXT,
184
+ summary_json TEXT NOT NULL,
185
+ diff_json TEXT NOT NULL,
186
+ graph_size INTEGER,
187
+ graph_gz BLOB
188
+ )"""
189
+ _REVIEWS_INDEX = "CREATE INDEX reviews_by_project ON reviews(project_id, id)"
190
+ _REVIEW_META = "id, acked_at, head_id, head_at, base_id, base_at, summary_json, graph_size"
191
+ # 运行的信息列(不取 tests_json、paths_gz:列运行时不读每个测试的那一列和大字段)
192
+ _RUN_META = "id, analysis_id, started_at, finished_at, command, status, exit_code, summary_json, paths_size, scope_json"
193
+
194
+
195
+ def _base_kept(t: str) -> str:
196
+ """SQL:表别名 t 那一行有一个真正可比的对比基准:基准那次还在库里(不在了——旧版本的服务按旧规则清理掉的——就
197
+ 当作没有可比的),而且不是它自己(自己做基准是"标为已看"的记号,见 Store.clear_base)。"""
198
+ return f"({t}.base_id IS NOT {t}.id AND EXISTS (SELECT 1 FROM analyses kept WHERE kept.id = {t}.base_id))"
199
+
200
+
201
+ def _meta_columns(t: str, prefix: str = "") -> str:
202
+ """SQL:表别名 t 那一行分析的信息列(列名带 prefix),给 _analysis_meta 读。不取 graph_gz(也不取可能较大的
203
+ file_lines_json、diff_json 本身)。base_id、has_diff 按"有真正可比的基准"算(_base_kept):基准不在了、或者是
204
+ "标为已看"的记号时 base_id 为 NULL、has_diff 为假。"""
205
+ kept = _base_kept(t)
206
+ return (f"{t}.id AS {prefix}id, {t}.created_at AS {prefix}created_at, {t}.engine_version AS {prefix}engine_version, "
207
+ f"{t}.summary_json AS {prefix}summary_json, {t}.graph_size AS {prefix}graph_size, "
208
+ f"CASE WHEN {kept} THEN {t}.base_id END AS {prefix}base_id, "
209
+ f"({t}.diff_json IS NOT NULL AND {kept}) AS {prefix}has_diff")
210
+
211
+
212
+ _ANALYSIS_META = _meta_columns("a")
213
+
214
+
215
+ def _create_tables(con: sqlite3.Connection) -> None:
216
+ """新库:直接建最新版本的表。"""
217
+ for statement in (_PROJECTS, _ANALYSES.format(name="analyses"), _ANALYSES_INDEX, _OVERRIDES, _RUNS, _RUNS_INDEX,
218
+ _REVIEWS, _REVIEWS_INDEX):
219
+ con.execute(statement)
220
+
221
+
222
+ def _graph_sha(gz: bytes) -> str | None:
223
+ """压缩存着的图解压后的 sha256;解不开(坏了的数据)时 None。"""
224
+ try:
225
+ return hashlib.sha256(gzip.decompress(gz)).hexdigest()
226
+ except (OSError, EOFError, zlib.error) as e:
227
+ logger.warning("升级时有一张图解不开,这次分析不记指纹:%s", e)
228
+ return None
229
+
230
+
231
+ def _upgrade_1_to_2(con: sqlite3.Connection) -> None:
232
+ """版本 1 → 2:analyses 加五列。按新的列顺序重建这张表(ALTER TABLE ADD COLUMN 只能把列加在 graph_gz 后面,以后
233
+ 每次读这些小字段都要先走完大字段的溢出页),id、AUTOINCREMENT 的计数原样保留。已有的每行解压一次算 graph_sha;
234
+ base_id 填"和它之前(同一项目)最近一次 graph_sha 不同的分析"(指纹不明的算不同),没有就 NULL;不算差异
235
+ (diff_json 留 NULL);config_json、file_lines_json 留 NULL(没有记下来,不猜)。没有对应项目的分析(外键检查
236
+ 关着时删了项目留下的)不拷过去,记一条日志:新表有外键约束,拷了会让整个升级失败。"""
237
+ seq = con.execute("SELECT seq FROM sqlite_sequence WHERE name = 'analyses'").fetchone()
238
+ old = "id, project_id, created_at, engine_version, summary_json, graph_size, graph_gz"
239
+ con.execute(_ANALYSES.format(name="analyses_v2"))
240
+ orphans = con.execute("SELECT count(*) FROM analyses WHERE project_id NOT IN (SELECT id FROM projects)").fetchone()[0]
241
+ if orphans:
242
+ logger.warning("升级数据库时丢掉了 %d 次没有对应项目的分析(项目早已删除,分析却留着)", orphans)
243
+ con.execute(f"INSERT INTO analyses_v2 ({old}) SELECT {old} FROM analyses "
244
+ "WHERE project_id IN (SELECT id FROM projects)")
245
+ con.execute("DROP TABLE analyses") # 它的索引、sqlite_sequence 里的那一行一起删掉
246
+ con.execute("ALTER TABLE analyses_v2 RENAME TO analyses")
247
+ con.execute(_ANALYSES_INDEX)
248
+ if seq is not None: # 删掉过的最大 id 也不再用(AUTOINCREMENT 的保证)
249
+ cur = con.execute("UPDATE sqlite_sequence SET seq = max(seq, ?) WHERE name = 'analyses'", (seq[0],))
250
+ if cur.rowcount == 0:
251
+ con.execute("INSERT INTO sqlite_sequence (name, seq) VALUES ('analyses', ?)", (seq[0],))
252
+ rows = con.execute("SELECT id, project_id FROM analyses ORDER BY project_id, id").fetchall()
253
+ history: dict[str, list[tuple[int, str | None]]] = {}
254
+ for row in rows:
255
+ gz = con.execute("SELECT graph_gz FROM analyses WHERE id = ?", (row["id"],)).fetchone()["graph_gz"]
256
+ sha = _graph_sha(bytes(gz))
257
+ earlier = history.setdefault(row["project_id"], [])
258
+ base = next((i for i, s in reversed(earlier) if s is None or sha is None or s != sha), None)
259
+ con.execute("UPDATE analyses SET graph_sha = ?, base_id = ? WHERE id = ?", (sha, base, row["id"]))
260
+ earlier.append((row["id"], sha))
261
+
262
+
263
+ def _copy_database(source: Path, target: Path) -> None:
264
+ """把库复制到 target(用 SQLite 的备份接口:-wal 里已提交的内容也在,副本是一个完整的库)。先写到临时文件再改名,
265
+ 中途失败不留下半截的 target。target 0600。失败时抛 OSError 或 sqlite3.Error。"""
266
+ tmp = target.with_name(target.name + ".tmp")
267
+ try:
268
+ private_file(tmp)
269
+ src = sqlite3.connect(source)
270
+ try:
271
+ dst = sqlite3.connect(tmp)
272
+ try:
273
+ src.backup(dst)
274
+ finally:
275
+ dst.close()
276
+ finally:
277
+ src.close()
278
+ os.replace(tmp, target)
279
+ except BaseException:
280
+ tmp.unlink(missing_ok=True)
281
+ raise
282
+
283
+
284
+ def _upgrade_2_to_3(con: sqlite3.Connection) -> None:
285
+ """版本 2 → 3:projects 加 test_command、test_confirmed 两列(加在最后,和新库的列顺序相同;已有的项目都是没填
286
+ 命令、没确认),建 runs 表。已有的数据一行不动。"""
287
+ con.execute("ALTER TABLE projects ADD COLUMN test_command TEXT")
288
+ con.execute("ALTER TABLE projects ADD COLUMN test_confirmed INTEGER NOT NULL DEFAULT 0")
289
+ con.execute(_RUNS)
290
+ con.execute(_RUNS_INDEX)
291
+
292
+
293
+ def _fix_early_v3(con: sqlite3.Connection) -> None:
294
+ """本阶段较早的代码建的结构版本 3 的库(没有发布过):runs 还没有 functions_gz 这一列时补上(加在最后;已有的
295
+ 运行这一列为空,按功能线数函数时报 line_known: false)。"""
296
+ if "functions_gz" not in {r[1] for r in con.execute("PRAGMA table_info(runs)")}:
297
+ con.execute("ALTER TABLE runs ADD COLUMN functions_gz BLOB")
298
+
299
+
300
+ def _upgrade_3_to_4(con: sqlite3.Connection) -> None:
301
+ """版本 3 → 4:projects 加 mcp_tests(允许 MCP 请平台运行单条功能线的测试;已有的项目都是不允许),runs 加
302
+ scope_json(这次运行的范围:NULL = 全部测试;{"line", "line_title", "tests", "base_run"} = 只跑了一条功能线的
303
+ 测试)。已有的运行都是全量。已有的数据一行不动。"""
304
+ _fix_early_v3(con)
305
+ con.execute("ALTER TABLE projects ADD COLUMN mcp_tests INTEGER NOT NULL DEFAULT 0")
306
+ # 从版本 1、2 一路升上来的库:runs 是刚才按现在的建表语句建的,已经有这一列
307
+ if "scope_json" not in {r[1] for r in con.execute("PRAGMA table_info(runs)")}:
308
+ con.execute("ALTER TABLE runs ADD COLUMN scope_json TEXT")
309
+
310
+
311
+ def _upgrade_4_to_5(con: sqlite3.Connection) -> None:
312
+ """版本 4 → 5:建 reviews 表(变更记录:每次"标为已看"时存下的那次流程变化)。已有的数据一行不动;升级之前标过
313
+ 已看的变化没有存,记录从这以后才有。"""
314
+ con.execute(_REVIEWS)
315
+ con.execute(_REVIEWS_INDEX)
316
+
317
+
318
+ def _upgrade_5_to_6(con: sqlite3.Connection) -> None:
319
+ """版本 5 → 6:reviews 加 graph_size、graph_gz(标为已看的那次分析的图,压缩好的原样;在画布上回看这条记录用)。
320
+ 已有的记录这两列为空:只能看文字明细。"""
321
+ have = {r[1] for r in con.execute("PRAGMA table_info(reviews)")}
322
+ for column, kind in (("graph_size", "INTEGER"), ("graph_gz", "BLOB")):
323
+ if column not in have: # 从更早的版本一路升上来的库:reviews 是刚按现在的建表语句建的,已经有这两列
324
+ con.execute(f"ALTER TABLE reviews ADD COLUMN {column} {kind}")
325
+
326
+
327
+ def review_summary(diff: dict) -> dict:
328
+ """一份流程差异(diff_to_json 的结果)的概要:{"lines": [{"sid", "title", "group", "status"}](有变化的功能线),
329
+ "functions": 有变化的函数个数, "added" / "removed" / "changed": 新增 / 删除 / 改动的节点个数}。格式不认识的地方
330
+ 当作没有。"""
331
+ lines = [{"sid": ln.get("sid", ""), "title": ln.get("title", ""), "group": ln.get("group", ""),
332
+ "status": ln.get("status", "")} for ln in diff.get("lines") or [] if isinstance(ln, dict)]
333
+ functions = [f for f in (diff.get("functions") or {}).values() if isinstance(f, dict)]
334
+ counts = {"added": 0, "removed": 0, "changed": 0}
335
+ for f in functions:
336
+ for node in f.get("nodes") or []:
337
+ if isinstance(node, dict) and node.get("status") in counts:
338
+ counts[node["status"]] += 1
339
+ return {"lines": lines, "functions": len(functions), **counts}
340
+
341
+
342
+ def _review_meta(row: sqlite3.Row) -> dict:
343
+ """变更记录的信息(没有差异本身):{id, acked_at, head_id, head_at, base_id, base_at, summary, graph_size}。head 是
344
+ 标为已看的那次分析,base 是它当时的对比基准(上一次标为已看时,或第一次分析);summary 见 review_summary;
345
+ graph_size 是存着的当时的图(head 那次的)压缩前的字节数,没有存图的记录(结构版本 5 时存的)为 None。"""
346
+ return {"id": row["id"], "acked_at": row["acked_at"], "head_id": row["head_id"], "head_at": row["head_at"],
347
+ "base_id": row["base_id"], "base_at": row["base_at"], "summary": json.loads(row["summary_json"]),
348
+ "graph_size": row["graph_size"]}
349
+
350
+
351
+ # 从版本 n 升到 n + 1 的函数。以后加一个版本:SCHEMA_VERSION 加一,这里加一项,_create_tables 建新版本的表
352
+ _MIGRATIONS: dict[int, Callable[[sqlite3.Connection], None]] = {
353
+ 1: _upgrade_1_to_2,
354
+ 2: _upgrade_2_to_3,
355
+ 3: _upgrade_3_to_4,
356
+ 4: _upgrade_4_to_5,
357
+ 5: _upgrade_5_to_6,
358
+ }
359
+
360
+
361
+ class StoreError(Exception):
362
+ """存储读写失败。信息是给用户看的中文。"""
363
+
364
+
365
+ class DuplicateRootError(StoreError):
366
+ """同一个目录已经添加过。"""
367
+
368
+ def __init__(self, root: str, project_id: str | None):
369
+ super().__init__(f"这个目录已经添加过:{root}")
370
+ self.root = root
371
+ self.project_id = project_id
372
+
373
+
374
+ class OverlapRootError(StoreError):
375
+ """目录和一个已添加的项目重叠(在它里面,或者包含它)。"""
376
+
377
+ def __init__(self, reason: str, project_id: str):
378
+ super().__init__(reason)
379
+ self.project_id = project_id
380
+
381
+
382
+ class ProjectMissingError(StoreError):
383
+ """项目不存在(没有添加过,或者已经删除了)。"""
384
+
385
+ def __init__(self, project_id: str):
386
+ super().__init__(f"项目不存在(可能已经删除了):{project_id}")
387
+ self.project_id = project_id
388
+
389
+
390
+ @dataclass(frozen=True)
391
+ class NewAnalysis:
392
+ """一次分析要保存的内容。config 等四项不给时存 NULL(graph_sha 总是按 graph_json 算)。acknowledged 为真时这次分析
393
+ 记成"看过的状态"(存成以自己为基准,同 clear_base;base_id、diff 要为 None):标为已看之后、流程没变的重新分析
394
+ 接着带这个记号,下一次改流程时就知道对比基准是"上次标为已看时"。"""
395
+
396
+ engine_version: str
397
+ summary: dict
398
+ graph_json: str # 引擎输出的图 JSON 原文(to_json 的结果)
399
+ config: dict | None = None # 这次分析用的配置
400
+ file_lines: dict | None = None # query.file_lines(图)
401
+ base_id: int | None = None # 对比基准的分析 id
402
+ diff: dict | None = None # diff_to_json(...);没有基准或差异为空时 None
403
+ acknowledged: bool = False
404
+
405
+
406
+ @dataclass(frozen=True)
407
+ class NewRun:
408
+ """一次测试运行要保存的内容(见模块说明里 runs 表的各列)。tests、paths_json 在没跑完(没有路径)时为 None。"""
409
+
410
+ analysis_id: int | None # 这次运行用的那次分析
411
+ started_at: str
412
+ finished_at: str
413
+ command: str
414
+ status: str # ok / tests_failed / error / timeout / cancelled
415
+ exit_code: int | None
416
+ summary: dict
417
+ tests: list[dict] | None = None # [{test, outcome, seconds, cases, functions}]
418
+ paths: dict | None = None # run_paths_to_json(...) 的结果
419
+ function_index: dict | None = None # {"functions": [函数 sid…], "tests": {测试 node id: [下标…]}}
420
+ scope: dict | None = None # None = 全部测试;只跑一条功能线时 {"line", "line_title", "tests", "base_run"}
421
+
422
+
423
+ @dataclass(frozen=True)
424
+ class _Packed:
425
+ engine_version: str
426
+ summary_json: str
427
+ graph_size: int
428
+ graph_gz: bytes
429
+ config_json: str | None
430
+ graph_sha: str
431
+ base_id: int | None
432
+ file_lines_json: str | None
433
+ diff_json: str | None
434
+ acknowledged: bool
435
+
436
+
437
+ def _now() -> str:
438
+ return datetime.now(UTC).isoformat(timespec="seconds")
439
+
440
+
441
+ def _new_id() -> str:
442
+ return "".join(secrets.choice(_ID_ALPHABET) for _ in range(_ID_LENGTH))
443
+
444
+
445
+ def _dumps(value: object) -> str | None:
446
+ return None if value is None else json.dumps(value, ensure_ascii=False)
447
+
448
+
449
+ def _loads(text: str | None) -> object:
450
+ return None if text is None else json.loads(text)
451
+
452
+
453
+ def _pack(a: NewAnalysis) -> _Packed:
454
+ """在拿写锁之前压缩好:压缩一张 10 MB 的图要几十毫秒,不该占着锁做。mtime=0:同样的图压出同样的字节。"""
455
+ raw = a.graph_json.encode("utf-8")
456
+ return _Packed(a.engine_version, json.dumps(a.summary, ensure_ascii=False), len(raw),
457
+ gzip.compress(raw, compresslevel=6, mtime=0), _dumps(a.config), hashlib.sha256(raw).hexdigest(),
458
+ a.base_id, _dumps(a.file_lines), _dumps(a.diff), a.acknowledged)
459
+
460
+
461
+ def _analysis_meta(row: sqlite3.Row, prefix: str = "") -> dict:
462
+ """分析的信息(没有图数据):{id, created_at, engine_version, summary, graph_size, base_id, has_diff}。"""
463
+ return {"id": row[prefix + "id"], "created_at": row[prefix + "created_at"],
464
+ "engine_version": row[prefix + "engine_version"], "summary": json.loads(row[prefix + "summary_json"]),
465
+ "graph_size": row[prefix + "graph_size"], "base_id": row[prefix + "base_id"],
466
+ "has_diff": bool(row[prefix + "has_diff"])}
467
+
468
+
469
+ def _project(row: sqlite3.Row) -> dict:
470
+ return {"id": row["id"], "name": row["name"], "root": row["root"], "config": json.loads(row["config_json"]),
471
+ "created_at": row["created_at"], "updated_at": row["updated_at"], "test_command": row["test_command"],
472
+ "test_confirmed": bool(row["test_confirmed"]), "mcp_tests": bool(row["mcp_tests"])}
473
+
474
+
475
+ def _pack_paths(paths: dict) -> tuple[bytes, int, dict]:
476
+ """运行路径 → (压缩包, 压缩前的字节数, 索引)。压缩包是一个标准的 gzip(解开就是整个 JSON,接口原样发出去):
477
+ {"<运行一级的项>": 值, …, "tests": [测试, …]}。每个运行一级的值(version、shapes、function_dups……除 tests 以外
478
+ run_paths_to_json 给的每一项)和每个测试的 JSON 前后各做一次 Z_FULL_FLUSH:压缩状态在那里重新开始、按字节对齐,
479
+ 所以 [起, 止) 这一段可以单独用原始 deflate 解开,正好是那个值的 JSON(取一个测试时不用解开、解析整个几十 MB 的
480
+ JSON)。索引:{"meta": {键: [起, 止]}, "tests": {测试 node id: [起, 止]}}。mtime 为 0:同样的路径压出同样的字节。
481
+ 这里只认 tests 和每个测试的 test;其余内容不看(形状由 pystepmap.runpath 定)。"""
482
+ co = zlib.compressobj(6, zlib.DEFLATED, 16 + zlib.MAX_WBITS) # gzip 头和尾由 zlib 写
483
+ out = bytearray()
484
+ size = 0
485
+ index: dict = {"meta": {}, "tests": {}}
486
+
487
+ def put(data: bytes) -> None:
488
+ nonlocal size
489
+ out.extend(co.compress(data))
490
+ size += len(data)
491
+
492
+ def piece(data: bytes) -> list[int]:
493
+ out.extend(co.flush(zlib.Z_FULL_FLUSH))
494
+ start = len(out)
495
+ put(data)
496
+ out.extend(co.flush(zlib.Z_FULL_FLUSH))
497
+ return [start, len(out)]
498
+
499
+ def dumps(value: object) -> bytes:
500
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
501
+
502
+ put(b"{")
503
+ for key, value in paths.items():
504
+ if key == "tests":
505
+ continue
506
+ put(dumps(key) + b":")
507
+ index["meta"][key] = piece(dumps(value))
508
+ put(b",")
509
+ put(b'"tests":[')
510
+ for i, test in enumerate(paths.get("tests", [])):
511
+ if i:
512
+ put(b",")
513
+ index["tests"][test["test"]] = piece(dumps(test))
514
+ put(b"]}")
515
+ out.extend(co.flush())
516
+ return bytes(out), size, index
517
+
518
+
519
+ def _base_sid(sid: str) -> str:
520
+ """去掉结尾的重名编号 "#数字"(pystepmap.runpath 模块说明里的 base(sid))。"""
521
+ head, sep, tail = sid.rpartition("#")
522
+ return head if sep and tail.isdigit() else sid
523
+
524
+
525
+ def _run_meta(row: sqlite3.Row) -> dict:
526
+ """运行的信息(没有每个测试的那一列、没有路径):{id, analysis_id, started_at, finished_at, command, status,
527
+ exit_code, summary, paths_size, scope};paths_size 是路径 JSON 压缩前的字节数,没有路径时 None;scope 是这次运行的
528
+ 范围:None = 全部测试,{"line": 功能线 sid, "line_title", "tests": 名单里的个数, "base_run": 名单取自哪次全量运行} =
529
+ 只跑了一条功能线的测试。"""
530
+ return {"id": row["id"], "analysis_id": row["analysis_id"], "started_at": row["started_at"],
531
+ "finished_at": row["finished_at"], "command": row["command"], "status": row["status"],
532
+ "exit_code": row["exit_code"], "summary": json.loads(row["summary_json"]), "paths_size": row["paths_size"],
533
+ "scope": None if row["scope_json"] is None else json.loads(row["scope_json"])}
534
+
535
+
536
+ def private_dir(path: Path) -> None:
537
+ """建平台数据目录,只有本人能进(0700);已有的目录比这宽时收紧(不是自己的目录不动)。里面存着被分析项目的
538
+ 源码路径、图和手工改的标题,不该让本机别的用户读到。"""
539
+ path.mkdir(mode=0o700, parents=True, exist_ok=True)
540
+ if os.name != "posix":
541
+ return
542
+ st = path.stat()
543
+ if st.st_uid == os.getuid() and stat.S_IMODE(st.st_mode) != 0o700:
544
+ path.chmod(0o700)
545
+
546
+
547
+ def private_file(path: Path, create: bool = True) -> None:
548
+ """让文件只有本人能读写(0600):不存在时(create 为真)新建一个空文件,已有的比这宽时收紧。"""
549
+ if not create and not path.exists():
550
+ return
551
+ fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o600)
552
+ try:
553
+ if os.name == "posix" and stat.S_IMODE(os.fstat(fd).st_mode) != 0o600:
554
+ os.fchmod(fd, 0o600)
555
+ finally:
556
+ os.close(fd)
557
+
558
+
559
+ class Store:
560
+ """包住一个 SQLite 文件。线程安全:每次调用各开各的连接;另外开着一个闲着的连接(见模块说明),用 close() 关,
561
+ 或者 Store 被回收时自动关。数据目录 0700,库文件 0600;SQLite 建 -wal、-shm 时照库文件的权限,所以它们也是 0600。"""
562
+
563
+ def __init__(self, path: Path):
564
+ self.path = Path(path)
565
+ self._keeper: sqlite3.Connection | None = None
566
+ try:
567
+ private_dir(self.path.parent)
568
+ private_file(self.path) # 先建好空的库文件(0600),SQLite 打开时照用;-wal、-shm 跟着它的权限
569
+ for side in ("-wal", "-shm"): # 以前的版本留下的:收紧
570
+ private_file(self.path.with_name(self.path.name + side), create=False)
571
+ except OSError as e:
572
+ raise StoreError(f"无法创建平台数据目录 {self.path.parent}:{e.strerror or e}") from None
573
+ with self._connect() as con:
574
+ self._refuse_newer(con) # 先看版本:更新版本建的库一个字节都不动(切换 WAL 也会改文件头)
575
+ con.execute("PRAGMA journal_mode = WAL") # 持久设置;不能在事务里改
576
+ with self._write() as con: # 拿着写锁再看一次:另一个进程(MCP、另一个服务)可能刚升级完
577
+ version = self._refuse_newer(con)
578
+ if version == 0:
579
+ _create_tables(con)
580
+ elif version == SCHEMA_VERSION:
581
+ _fix_early_v3(con)
582
+ else:
583
+ if version < SCHEMA_VERSION:
584
+ self._keep_old_copy(version) # 拿着写锁复制:复制期间没人能改库
585
+ for start in range(version, SCHEMA_VERSION):
586
+ _MIGRATIONS[start](con)
587
+ if version != SCHEMA_VERSION:
588
+ con.execute(f"PRAGMA user_version = {SCHEMA_VERSION}")
589
+ self._keeper = self._open_keeper()
590
+
591
+ def _keep_old_copy(self, version: int) -> None:
592
+ """升级之前把库复制成 pystepmap.db.bak-v<version>;已经有了就不动。复制不了时抛 StoreError(这次不升级)。"""
593
+ target = self.path.with_name(f"{self.path.name}.bak-v{version}")
594
+ if target.exists():
595
+ return
596
+ try:
597
+ _copy_database(self.path, target)
598
+ except (OSError, sqlite3.Error) as e:
599
+ raise StoreError(f"升级之前没能备份数据库到 {target}:{getattr(e, 'strerror', None) or e};这次没有升级,"
600
+ f"库保持原样(结构版本 {version})") from None
601
+ logger.warning("数据库从结构版本 %d 升级到 %d,升级前的库复制在 %s", version, SCHEMA_VERSION, target)
602
+
603
+ def _open_keeper(self) -> sqlite3.Connection:
604
+ """开那个闲着的连接:读一次(连上 -wal、-shm),读完不留读事务(不挡检查点)。可以在任何线程里关。"""
605
+ try:
606
+ con = sqlite3.connect(self.path, timeout=30, isolation_level=None, check_same_thread=False)
607
+ except sqlite3.Error as e:
608
+ raise StoreError(f"无法打开数据库 {self.path}:{e}") from None
609
+ try:
610
+ cur = con.execute("SELECT count(*) FROM sqlite_master")
611
+ cur.fetchall()
612
+ cur.close()
613
+ except sqlite3.Error as e:
614
+ con.close()
615
+ raise StoreError(f"数据库读写失败:{e}") from None
616
+ return con
617
+
618
+ def close(self) -> None:
619
+ """关掉闲着的连接(可以重复调用)。之后照常能读写,只是又回到每次调用开关连接、-wal 可能被删了再建。"""
620
+ keeper, self._keeper = getattr(self, "_keeper", None), None
621
+ if keeper is not None:
622
+ keeper.close()
623
+
624
+ def __del__(self) -> None:
625
+ self.close()
626
+
627
+ def _refuse_newer(self, con: sqlite3.Connection) -> int:
628
+ version = con.execute("PRAGMA user_version").fetchone()[0]
629
+ if version > SCHEMA_VERSION:
630
+ raise StoreError(f"数据库 {self.path} 是更新版本的 pystepmap 建的(结构版本 {version},"
631
+ f"这个版本只认识 {SCHEMA_VERSION}),请升级 pystepmap 或换一个数据目录(PYSTEPMAP_HOME)")
632
+ return version
633
+
634
+ # ---------- 连接 ----------
635
+
636
+ @contextmanager
637
+ def _connect(self) -> Iterator[sqlite3.Connection]:
638
+ try:
639
+ con = sqlite3.connect(self.path, timeout=30, isolation_level=None) # 自己管事务
640
+ except sqlite3.Error as e:
641
+ raise StoreError(f"无法打开数据库 {self.path}:{e}") from None
642
+ con.row_factory = sqlite3.Row
643
+ try:
644
+ con.execute("PRAGMA foreign_keys = ON")
645
+ yield con
646
+ except sqlite3.Error as e:
647
+ raise StoreError(f"数据库读写失败:{e}") from None
648
+ finally:
649
+ con.close()
650
+
651
+ @contextmanager
652
+ def _write(self) -> Iterator[sqlite3.Connection]:
653
+ """一个写事务:正常结束时提交,出任何异常都回滚。"""
654
+ with self._connect() as con:
655
+ con.execute("BEGIN IMMEDIATE")
656
+ try:
657
+ yield con
658
+ except BaseException:
659
+ if con.in_transaction: # 有的错误(磁盘满等)SQLite 已经自己回滚了,再回滚会盖掉原来的错误
660
+ con.execute("ROLLBACK")
661
+ raise
662
+ con.execute("COMMIT")
663
+
664
+ # ---------- 项目 ----------
665
+
666
+ def add_project(self, *, name: str, root: str, config: dict, analysis: NewAnalysis,
667
+ conflict: Callable[[list[dict]], StoreError | None] | None = None) -> tuple[str, int]:
668
+ """新项目和它的第一次分析,在同一个事务里写入:要么都在,要么都不在。返回 (项目 id, 分析 id)。
669
+ 同一个 root 已经有了时抛 DuplicateRootError。conflict 给出时,在写事务里(拿着写锁,别的写入进不来)用全部
670
+ 已有项目([{"id", "name", "root"}])调用它,它返回的错误照抛:查重和写入之间不会插进别的项目。"""
671
+ packed = _pack(analysis)
672
+ config_json = json.dumps(config, ensure_ascii=False)
673
+ with self._write() as con:
674
+ same = con.execute("SELECT id FROM projects WHERE root = ?", (root,)).fetchone()
675
+ if same is not None:
676
+ raise DuplicateRootError(root, same["id"])
677
+ if conflict is not None:
678
+ rows = con.execute("SELECT id, name, root FROM projects ORDER BY created_at, rowid").fetchall()
679
+ error = conflict([dict(r) for r in rows])
680
+ if error is not None:
681
+ raise error
682
+ project_id = _new_id()
683
+ while con.execute("SELECT 1 FROM projects WHERE id = ?", (project_id,)).fetchone():
684
+ project_id = _new_id()
685
+ now = _now()
686
+ con.execute("INSERT INTO projects (id, name, root, config_json, created_at, updated_at) "
687
+ "VALUES (?, ?, ?, ?, ?, ?)", (project_id, name, root, config_json, now, now))
688
+ analysis_id = self._insert_analysis(con, project_id, packed, now)
689
+ return project_id, analysis_id
690
+
691
+ def get_project(self, project_id: str) -> dict | None:
692
+ with self._connect() as con:
693
+ row = con.execute("SELECT * FROM projects WHERE id = ?", (project_id,)).fetchone()
694
+ return None if row is None else _project(row)
695
+
696
+ def find_project_by_root(self, root: str) -> dict | None:
697
+ with self._connect() as con:
698
+ row = con.execute("SELECT * FROM projects WHERE root = ?", (root,)).fetchone()
699
+ return None if row is None else _project(row)
700
+
701
+ def list_projects(self) -> list[dict]:
702
+ """全部项目(按添加的先后),每个带最新一次分析的信息("analysis",没有图数据)。"""
703
+ with self._connect() as con:
704
+ rows = con.execute(
705
+ f"SELECT p.*, {_meta_columns('a', 'a_')} "
706
+ "FROM projects p LEFT JOIN analyses a "
707
+ "ON a.id = (SELECT max(id) FROM analyses WHERE project_id = p.id) "
708
+ "ORDER BY p.created_at, p.rowid").fetchall()
709
+ out = []
710
+ for row in rows:
711
+ item = _project(row)
712
+ item["analysis"] = None if row["a_id"] is None else _analysis_meta(row, "a_")
713
+ out.append(item)
714
+ return out
715
+
716
+ def delete_project(self, project_id: str) -> bool:
717
+ """删除项目和它的全部分析、手工项、测试运行。项目不存在时返回 False。"""
718
+ with self._write() as con:
719
+ return con.execute("DELETE FROM projects WHERE id = ?", (project_id,)).rowcount > 0
720
+
721
+ def set_config(self, project_id: str, config: dict) -> bool:
722
+ with self._write() as con:
723
+ cur = con.execute("UPDATE projects SET config_json = ?, updated_at = ? WHERE id = ?",
724
+ (json.dumps(config, ensure_ascii=False), _now(), project_id))
725
+ return cur.rowcount > 0
726
+
727
+ # ---------- 分析 ----------
728
+
729
+ def _insert_analysis(self, con: sqlite3.Connection, project_id: str, packed: _Packed, now: str) -> int:
730
+ cur = con.execute(
731
+ "INSERT INTO analyses (project_id, created_at, engine_version, summary_json, graph_size, config_json, "
732
+ "graph_sha, base_id, file_lines_json, diff_json, graph_gz) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
733
+ (project_id, now, packed.engine_version, packed.summary_json, packed.graph_size, packed.config_json,
734
+ packed.graph_sha, packed.base_id, packed.file_lines_json, packed.diff_json, packed.graph_gz))
735
+ analysis_id = int(cur.lastrowid)
736
+ if packed.acknowledged: # "看过的状态":以自己为基准(id 插入后才知道,同一个事务里补上)
737
+ con.execute("UPDATE analyses SET base_id = id, diff_json = NULL WHERE id = ?", (analysis_id,))
738
+ return analysis_id
739
+
740
+ def add_analysis(self, project_id: str, analysis: NewAnalysis) -> int:
741
+ """给已有项目存一次新分析,返回分析 id。项目不存在(比如分析期间被删了)时抛 ProjectMissingError。"""
742
+ packed = _pack(analysis)
743
+ with self._write() as con:
744
+ if con.execute("SELECT 1 FROM projects WHERE id = ?", (project_id,)).fetchone() is None:
745
+ raise ProjectMissingError(project_id)
746
+ now = _now()
747
+ analysis_id = self._insert_analysis(con, project_id, packed, now)
748
+ con.execute("UPDATE projects SET updated_at = ? WHERE id = ?", (now, project_id))
749
+ return analysis_id
750
+
751
+ def list_analyses(self, project_id: str) -> list[dict]:
752
+ """项目的全部分析(不含图数据),新的在前。"""
753
+ with self._connect() as con:
754
+ rows = con.execute(f"SELECT {_ANALYSIS_META} FROM analyses a WHERE a.project_id = ? ORDER BY a.id DESC",
755
+ (project_id,)).fetchall()
756
+ return [_analysis_meta(r) for r in rows]
757
+
758
+ def latest_analysis(self, project_id: str) -> dict | None:
759
+ """项目最新一次分析的信息(没有时 None)"""
760
+ with self._connect() as con:
761
+ row = con.execute(f"SELECT {_ANALYSIS_META} FROM analyses a WHERE a.project_id = ? ORDER BY a.id DESC LIMIT 1",
762
+ (project_id,)).fetchone()
763
+ return None if row is None else _analysis_meta(row)
764
+
765
+ def analysis_extra(self, analysis_id: int) -> dict | None:
766
+ """结构版本 2 加的那些:{"config", "graph_sha", "file_lines", "base_id", "diff", "acknowledged"}(JSON 的已解析;
767
+ 版本 1 留下的行 config、file_lines、diff 为 None)。没有真正可比的基准(基准那次已经不在了,或者这次是"标为已看"
768
+ 的记号)时 base_id、diff 都为 None;acknowledged:这次分析是"看过的状态"(标为已看的那次,或者之后流程没变、接着
769
+ 带记号的重新分析)。分析不存在(已被清理)时 None。"""
770
+ kept = _base_kept("a")
771
+ with self._connect() as con:
772
+ row = con.execute(f"SELECT a.config_json, a.graph_sha, a.file_lines_json, "
773
+ f"CASE WHEN {kept} THEN a.base_id END AS base_id, "
774
+ f"CASE WHEN {kept} THEN a.diff_json END AS diff_json, "
775
+ "a.base_id IS a.id AS acknowledged "
776
+ "FROM analyses a WHERE a.id = ?", (analysis_id,)).fetchone()
777
+ if row is None:
778
+ return None
779
+ return {"config": _loads(row["config_json"]), "graph_sha": row["graph_sha"],
780
+ "file_lines": _loads(row["file_lines_json"]), "base_id": row["base_id"], "diff": _loads(row["diff_json"]),
781
+ "acknowledged": bool(row["acknowledged"])}
782
+
783
+ def latest_diff(self, project_id: str) -> dict | None:
784
+ """最新一次分析的流程差异:{"head": 分析信息, "base": 基准那次的分析信息 | None, "diff": 差异 | None,
785
+ "baseline": {"kind", "at"} | None},一条语句读出(同一个快照,不会一半是别的进程写之前、一半是写之后)。没有
786
+ 真正可比的基准(基准那次已经不在了,或者最新一次就是标为已看的那次)时 base、diff、baseline 都为 None。项目
787
+ 没有分析时 None。
788
+ baseline 说对比基准代表的是什么状态:kind "acknowledged"——上次标为已看时(基准那次是"看过的状态"),at 是
789
+ 基准那次分析的时间;kind "first"——没标为已看过,相对第一次分析,at 是第一次分析的时间(添加项目的时间)。"""
790
+ with self._connect() as con:
791
+ row = con.execute(
792
+ f"SELECT {_meta_columns('h', 'h_')}, {_meta_columns('b', 'b_')}, h.diff_json AS diff_json, "
793
+ "b.base_id IS b.id AS b_acknowledged, p.created_at AS p_created_at "
794
+ "FROM analyses h JOIN projects p ON p.id = h.project_id "
795
+ "LEFT JOIN analyses b ON b.id = h.base_id AND h.base_id IS NOT h.id "
796
+ "WHERE h.id = (SELECT max(id) FROM analyses WHERE project_id = ?)", (project_id,)).fetchone()
797
+ if row is None:
798
+ return None
799
+ base = None if row["b_id"] is None else _analysis_meta(row, "b_")
800
+ baseline = None if base is None else (
801
+ {"kind": "acknowledged", "at": base["created_at"]} if row["b_acknowledged"]
802
+ else {"kind": "first", "at": row["p_created_at"]})
803
+ return {"head": _analysis_meta(row, "h_"), "base": base,
804
+ "diff": None if base is None else _loads(row["diff_json"]), "baseline": baseline}
805
+
806
+ def clear_base(self, project_id: str, analysis_id: int | None = None) -> bool:
807
+ """把项目最新一次分析标为已看:清掉它的流程差异,记成"看过的状态"(以自己为基准:base_id = 自己的 id,对外报
808
+ 成没有基准)。以后的分析从这个状态起比,界面能说"相对上次标为已看时"。analysis_id 给出时(用户看的是哪一次),
809
+ 只在最新一次还是它时才清——同一条语句里判断,别的进程刚存了新的一次时不会误清。清了返回 True;最新一次已经
810
+ 不是 analysis_id,或者项目没有分析(不存在)时 False。
811
+ 清掉之前,这次的流程差异(有、而且基准那次还在时)先存成一条变更记录(reviews),同一个事务里;每个项目只留
812
+ 最近 KEEP_REVIEWS 条。"""
813
+ with self._write() as con:
814
+ head = con.execute(
815
+ "SELECT a.id, a.created_at, a.base_id, a.diff_json, a.graph_size, a.graph_gz, b.created_at AS base_at "
816
+ "FROM analyses a "
817
+ "LEFT JOIN analyses b ON b.id = a.base_id "
818
+ "WHERE a.id = (SELECT max(id) FROM analyses WHERE project_id = ?) AND (? IS NULL OR a.id = ?)",
819
+ (project_id, analysis_id, analysis_id)).fetchone()
820
+ if head is not None and head["diff_json"] is not None and head["base_id"] != head["id"] \
821
+ and head["base_at"] is not None:
822
+ try:
823
+ summary = review_summary(json.loads(head["diff_json"]))
824
+ except ValueError:
825
+ summary = review_summary({})
826
+ con.execute("INSERT INTO reviews (project_id, acked_at, head_id, head_at, base_id, base_at, summary_json, "
827
+ "diff_json, graph_size, graph_gz) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
828
+ (project_id, _now(), head["id"], head["created_at"], head["base_id"], head["base_at"],
829
+ json.dumps(summary, ensure_ascii=False), head["diff_json"], head["graph_size"],
830
+ head["graph_gz"]))
831
+ con.execute("DELETE FROM reviews WHERE project_id = ? AND id NOT IN "
832
+ "(SELECT id FROM reviews WHERE project_id = ? ORDER BY id DESC LIMIT ?)",
833
+ (project_id, project_id, KEEP_REVIEWS))
834
+ cur = con.execute("UPDATE analyses SET base_id = id, diff_json = NULL "
835
+ "WHERE id = (SELECT max(id) FROM analyses WHERE project_id = ?) AND (? IS NULL OR id = ?)",
836
+ (project_id, analysis_id, analysis_id))
837
+ return cur.rowcount > 0
838
+
839
+ def list_reviews(self, project_id: str) -> list[dict]:
840
+ """项目的变更记录(信息,不含差异本身),新的在前。"""
841
+ with self._connect() as con:
842
+ rows = con.execute(f"SELECT {_REVIEW_META} FROM reviews WHERE project_id = ? ORDER BY id DESC",
843
+ (project_id,)).fetchall()
844
+ return [_review_meta(r) for r in rows]
845
+
846
+ def get_review(self, project_id: str, review_id: int) -> dict | None:
847
+ """一条变更记录的信息加 "diff"(diff_to_json 的结果,存的时候的原样)。不是这个项目的、不存在的:None。"""
848
+ with self._connect() as con:
849
+ row = con.execute(f"SELECT {_REVIEW_META}, diff_json FROM reviews WHERE id = ? AND project_id = ?",
850
+ (review_id, project_id)).fetchone()
851
+ return None if row is None else {**_review_meta(row), "diff": json.loads(row["diff_json"])}
852
+
853
+ def review_graph_gz(self, project_id: str, review_id: int) -> bytes | None:
854
+ """一条变更记录存着的当时的图(压缩好的原样)。记录不存在、不是这个项目的、没有存图时 None。"""
855
+ with self._connect() as con:
856
+ row = con.execute("SELECT graph_gz FROM reviews WHERE id = ? AND project_id = ?", (review_id, project_id)).fetchone()
857
+ return None if row is None or row["graph_gz"] is None else bytes(row["graph_gz"])
858
+
859
+ def prune_analyses(self, project_id: str, keep: int) -> int:
860
+ """只留项目最近的 keep 次分析,另外留下最新一次的 base_id 指向的那次(重新算差异要用它的图),以及最近一次
861
+ 跑完的全量运行用的那次(没走到的结局要用它的图分出哪些函数、结局是运行之后才有的)。返回删掉了几次。"""
862
+ with self._write() as con:
863
+ cur = con.execute(
864
+ "DELETE FROM analyses WHERE project_id = ? AND id NOT IN "
865
+ "(SELECT id FROM analyses WHERE project_id = ? ORDER BY id DESC LIMIT ?) "
866
+ "AND id IS NOT (SELECT base_id FROM analyses WHERE project_id = ? ORDER BY id DESC LIMIT 1) "
867
+ "AND id IS NOT (SELECT analysis_id FROM runs WHERE project_id = ? AND scope_json IS NULL "
868
+ "AND paths_size IS NOT NULL ORDER BY id DESC LIMIT 1)",
869
+ (project_id, project_id, keep, project_id, project_id))
870
+ return cur.rowcount
871
+
872
+ def graph_gz(self, analysis_id: int) -> bytes | None:
873
+ """存着的压缩图数据,原样(接口直接带 Content-Encoding: gzip 发出去)。"""
874
+ with self._connect() as con:
875
+ row = con.execute("SELECT graph_gz FROM analyses WHERE id = ?", (analysis_id,)).fetchone()
876
+ return None if row is None else bytes(row["graph_gz"])
877
+
878
+ def graph_json(self, analysis_id: int) -> str | None:
879
+ gz = self.graph_gz(analysis_id)
880
+ return None if gz is None else gzip.decompress(gz).decode("utf-8")
881
+
882
+ # ---------- 手工改的标题和分组 ----------
883
+
884
+ def get_overrides(self, project_id: str) -> dict[str, dict]:
885
+ """{功能线 sid: {"title"?: …, "group"?: …}},只列出改了的项。"""
886
+ with self._connect() as con:
887
+ rows = con.execute("SELECT line_sid, title, group_name FROM line_overrides WHERE project_id = ? "
888
+ "ORDER BY line_sid", (project_id,)).fetchall()
889
+ out: dict[str, dict] = {}
890
+ for r in rows:
891
+ item = {}
892
+ if r["title"] is not None:
893
+ item["title"] = r["title"]
894
+ if r["group_name"] is not None:
895
+ item["group"] = r["group_name"]
896
+ out[r["line_sid"]] = item
897
+ return out
898
+
899
+ def set_override(self, project_id: str, line_sid: str, title: str | None, group: str | None) -> None:
900
+ """整条改写一条手工项;title、group 都是 None 时删掉这条。项目不存在时抛 ProjectMissingError。"""
901
+ with self._write() as con:
902
+ if con.execute("SELECT 1 FROM projects WHERE id = ?", (project_id,)).fetchone() is None:
903
+ raise ProjectMissingError(project_id)
904
+ if title is None and group is None:
905
+ con.execute("DELETE FROM line_overrides WHERE project_id = ? AND line_sid = ?", (project_id, line_sid))
906
+ return
907
+ con.execute(
908
+ "INSERT INTO line_overrides (project_id, line_sid, title, group_name, updated_at) VALUES (?, ?, ?, ?, ?) "
909
+ "ON CONFLICT (project_id, line_sid) DO UPDATE SET title = excluded.title, "
910
+ "group_name = excluded.group_name, updated_at = excluded.updated_at",
911
+ (project_id, line_sid, title, group, _now()))
912
+
913
+ # ---------- 测试命令 ----------
914
+
915
+ def get_test_command(self, project_id: str) -> dict | None:
916
+ """{"command": 测试命令 | None, "confirmed": 用户确认过这条命令};项目不存在时 None。"""
917
+ with self._connect() as con:
918
+ row = con.execute("SELECT test_command, test_confirmed FROM projects WHERE id = ?", (project_id,)).fetchone()
919
+ return None if row is None else {"command": row["test_command"], "confirmed": bool(row["test_confirmed"])}
920
+
921
+ def set_test_command(self, project_id: str, command: str | None) -> dict:
922
+ """改测试命令(None = 清掉)。和原来的不同时确认清零;相同时保持。返回改后的 {"command", "confirmed"}。项目
923
+ 不存在时抛 ProjectMissingError。"""
924
+ with self._write() as con:
925
+ row = con.execute("SELECT test_command, test_confirmed FROM projects WHERE id = ?", (project_id,)).fetchone()
926
+ if row is None:
927
+ raise ProjectMissingError(project_id)
928
+ confirmed = command is not None and command == row["test_command"] and bool(row["test_confirmed"])
929
+ con.execute("UPDATE projects SET test_command = ?, test_confirmed = ?, updated_at = ? WHERE id = ?",
930
+ (command, int(confirmed), _now(), project_id))
931
+ return {"command": command, "confirmed": confirmed}
932
+
933
+ def confirm_test_command(self, project_id: str, command: str | None) -> bool:
934
+ """用户确认了 command 的影响:只在项目现在的测试命令还是它时记下(同一条语句里判断,别处刚改了命令时不会把
935
+ 新命令当成确认过)。记下了返回 True。"""
936
+ if command is None:
937
+ return False
938
+ with self._write() as con:
939
+ cur = con.execute("UPDATE projects SET test_confirmed = 1 WHERE id = ? AND test_command = ?",
940
+ (project_id, command))
941
+ return cur.rowcount > 0
942
+
943
+ def set_mcp_tests(self, project_id: str, allow: bool) -> bool:
944
+ """允许 / 不允许 MCP 请平台运行这个项目单条功能线的测试。返回改后的值;项目不存在时抛 ProjectMissingError。"""
945
+ with self._write() as con:
946
+ cur = con.execute("UPDATE projects SET mcp_tests = ? WHERE id = ?", (int(bool(allow)), project_id))
947
+ if cur.rowcount == 0:
948
+ raise ProjectMissingError(project_id)
949
+ return bool(allow)
950
+
951
+ def latest_full_run(self, project_id: str) -> dict | None:
952
+ """最近一次跑完、有运行路径的**全量**运行的信息(没有时 None):没走到的结局、单条线要跑哪些测试都用它。"""
953
+ with self._connect() as con:
954
+ row = con.execute(f"SELECT {_RUN_META} FROM runs WHERE project_id = ? AND scope_json IS NULL "
955
+ "AND paths_size IS NOT NULL ORDER BY id DESC LIMIT 1", (project_id,)).fetchone()
956
+ return None if row is None else _run_meta(row)
957
+
958
+ # ---------- 测试运行 ----------
959
+
960
+ def add_run(self, project_id: str, run: NewRun) -> int:
961
+ """存一次运行,返回运行 id。路径在拿写锁之前压缩好(_pack_paths)。项目不存在(运行期间被删)时抛
962
+ ProjectMissingError。"""
963
+ gz, size, index = (None, None, None) if run.paths is None else _pack_paths(run.paths)
964
+ tests = None if run.tests is None else json.dumps(run.tests, ensure_ascii=False)
965
+ summary = json.dumps(run.summary, ensure_ascii=False)
966
+ functions = None if run.function_index is None else gzip.compress(
967
+ json.dumps(run.function_index, ensure_ascii=False, separators=(",", ":")).encode("utf-8"), 6, mtime=0)
968
+ with self._write() as con:
969
+ if con.execute("SELECT 1 FROM projects WHERE id = ?", (project_id,)).fetchone() is None:
970
+ raise ProjectMissingError(project_id)
971
+ cur = con.execute(
972
+ "INSERT INTO runs (project_id, analysis_id, started_at, finished_at, command, status, exit_code, "
973
+ "summary_json, paths_size, tests_json, paths_index, functions_gz, paths_gz, scope_json) "
974
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
975
+ (project_id, run.analysis_id, run.started_at, run.finished_at, run.command, run.status, run.exit_code,
976
+ summary, size, tests, _dumps(index), functions, gz,
977
+ None if run.scope is None else json.dumps(run.scope, ensure_ascii=False)))
978
+ return int(cur.lastrowid)
979
+
980
+ def list_runs(self, project_id: str) -> list[dict]:
981
+ """项目的全部运行(信息,不含每个测试和路径),新的在前。"""
982
+ with self._connect() as con:
983
+ rows = con.execute(f"SELECT {_RUN_META} FROM runs WHERE project_id = ? ORDER BY id DESC",
984
+ (project_id,)).fetchall()
985
+ return [_run_meta(r) for r in rows]
986
+
987
+ def latest_run(self, project_id: str) -> dict | None:
988
+ with self._connect() as con:
989
+ row = con.execute(f"SELECT {_RUN_META} FROM runs WHERE project_id = ? ORDER BY id DESC LIMIT 1",
990
+ (project_id,)).fetchone()
991
+ return None if row is None else _run_meta(row)
992
+
993
+ def run_info(self, project_id: str, run_id: int) -> dict | None:
994
+ """一次运行的信息(同 list_runs 的一项,不读每个测试的那一列)。不是这个项目的、不存在的:None。"""
995
+ with self._connect() as con:
996
+ row = con.execute(f"SELECT {_RUN_META} FROM runs WHERE id = ? AND project_id = ?",
997
+ (run_id, project_id)).fetchone()
998
+ return None if row is None else _run_meta(row)
999
+
1000
+ def get_run(self, project_id: str, run_id: int) -> dict | None:
1001
+ """一次运行的信息加 "tests"(每个测试一项;没跑完的运行为空表)。不是这个项目的、不存在的:None。"""
1002
+ with self._connect() as con:
1003
+ row = con.execute(f"SELECT {_RUN_META}, tests_json FROM runs WHERE id = ? AND project_id = ?",
1004
+ (run_id, project_id)).fetchone()
1005
+ if row is None:
1006
+ return None
1007
+ return {**_run_meta(row), "tests": [] if row["tests_json"] is None else json.loads(row["tests_json"])}
1008
+
1009
+ def run_paths_gz(self, project_id: str, run_id: int) -> bytes | None:
1010
+ """存着的压缩运行路径,原样(接口直接带 Content-Encoding: gzip 发出去)。运行不存在、不是这个项目的、没有路径
1011
+ (没跑完)时 None。"""
1012
+ with self._connect() as con:
1013
+ row = con.execute("SELECT paths_gz FROM runs WHERE id = ? AND project_id = ?", (run_id, project_id)).fetchone()
1014
+ return None if row is None or row["paths_gz"] is None else bytes(row["paths_gz"])
1015
+
1016
+ def _segments(self, project_id: str, run_id: int, test: str | None) -> tuple[dict, dict] | None:
1017
+ """按 paths_index 只读出压缩包里运行一级的各段(和 test 给出时那个测试的一段),各自解开、解析:
1018
+ ({键: 值}, {"test": 那个测试} 或 {})。运行不存在、不是这个项目的、没有路径、没有这个测试时 None。"""
1019
+ with self._connect() as con:
1020
+ con.execute("BEGIN") # 索引和压缩包在同一个读事务里读:中间别的连接清理掉这次运行,看到的也是同一个快照
1021
+ try:
1022
+ row = con.execute("SELECT paths_index FROM runs WHERE id = ? AND project_id = ?",
1023
+ (run_id, project_id)).fetchone()
1024
+ index = None if row is None or row["paths_index"] is None else json.loads(row["paths_index"])
1025
+ if index is None or (test is not None and test not in index["tests"]):
1026
+ return None
1027
+ spans = {("meta", k): v for k, v in index["meta"].items()}
1028
+ if test is not None:
1029
+ spans[("test", test)] = index["tests"][test]
1030
+ pieces: dict[tuple[str, str], bytes] = {}
1031
+ with con.blobopen("runs", "paths_gz", run_id, readonly=True) as blob:
1032
+ for name, (start, end) in spans.items():
1033
+ blob.seek(start)
1034
+ pieces[name] = blob.read(end - start)
1035
+ finally:
1036
+ con.execute("COMMIT")
1037
+ try:
1038
+ values = {name: json.loads(zlib.decompressobj(-zlib.MAX_WBITS).decompress(data))
1039
+ for name, data in pieces.items()}
1040
+ except (zlib.error, ValueError) as e:
1041
+ raise StoreError(f"运行 #{run_id} 存着的路径解不开:{e}") from None
1042
+ meta = {k: values[("meta", k)] for k in index["meta"]}
1043
+ return meta, ({} if test is None else {"test": values[("test", test)]})
1044
+
1045
+ def run_paths_meta(self, project_id: str, run_id: int) -> dict | None:
1046
+ """运行一级的各项(version、shapes、function_dups……,就是 run_paths_to_json 里 tests 以外的那些),只读那几段。
1047
+ 没有路径时 None。"""
1048
+ found = self._segments(project_id, run_id, None)
1049
+ return None if found is None else found[0]
1050
+
1051
+ def run_test_paths(self, project_id: str, run_id: int, test: str) -> dict | None:
1052
+ """一次运行里一个测试的路径,和整份同一个形状:{运行一级的各项, "tests": [这个测试]};其中 shapes(每个函数
1053
+ 运行时的形状)只留这个测试里有的函数和重名组(基础 sid 在 function_dups 里)的每个定义——core 的放置规则要用
1054
+ 整组判断"这一组变没变"(pystepmap.runpath 模块说明"叠到图上");别的项(version、function_dups……)原样。
1055
+ 按 paths_index 只读出压缩包里这几段(SQLite 的增量读,不读整个大字段)单独解开。运行不存在、不是这个项目的、
1056
+ 没有路径、没有这个测试时 None。test 为 "" 是测试之外的执行(收集测试时导入模块等)。"""
1057
+ found = self._segments(project_id, run_id, test)
1058
+ if found is None:
1059
+ return None
1060
+ meta, picked = found
1061
+ one = picked["test"]
1062
+ dups = set(meta.get("function_dups") or ())
1063
+ out = {}
1064
+ for key, value in meta.items():
1065
+ if key == "shapes" and isinstance(value, dict): # 这个测试的函数,加上重名组的每个定义(core 判断这一组变没变要用)
1066
+ mine = one.get("functions", {})
1067
+ value = {f: v for f, v in value.items() if f in mine or _base_sid(f) in dups}
1068
+ out[key] = value
1069
+ out["tests"] = [one]
1070
+ return out
1071
+
1072
+ def run_function_index(self, project_id: str, run_id: int) -> dict | None:
1073
+ """这次运行的函数索引 {"functions": [函数 sid…], "tests": {测试 node id: [下标…]}}(存的时候算好的,见
1074
+ NewRun.function_index)。没有(没跑完、本阶段较早的代码存的运行)时 None。"""
1075
+ with self._connect() as con:
1076
+ row = con.execute("SELECT functions_gz FROM runs WHERE id = ? AND project_id = ?",
1077
+ (run_id, project_id)).fetchone()
1078
+ if row is None or row["functions_gz"] is None:
1079
+ return None
1080
+ return json.loads(gzip.decompress(row["functions_gz"]))
1081
+
1082
+ def prune_runs(self, project_id: str, keep: int) -> int:
1083
+ """全量的运行、只跑一条功能线的运行各留项目最近的 keep 次(分开数:单条线的运行跑得勤,不该把全量的挤掉——
1084
+ 没走到的结局、单条线要跑哪些测试都靠全量的那次),返回删掉了几次。"""
1085
+ with self._write() as con:
1086
+ cur = con.execute(
1087
+ "DELETE FROM runs WHERE project_id = ? AND id NOT IN "
1088
+ "(SELECT id FROM runs WHERE project_id = ? AND scope_json IS NULL ORDER BY id DESC LIMIT ?) AND id NOT IN "
1089
+ "(SELECT id FROM runs WHERE project_id = ? AND scope_json IS NOT NULL ORDER BY id DESC LIMIT ?)",
1090
+ (project_id, project_id, keep, project_id, keep))
1091
+ return cur.rowcount