Datasets:
Modalities:
Text
Formats:
json
Languages:
English
Size:
10K - 100K
Tags:
graph
network-topology
topology-reasoning
graph-qa
long-horizon-reasoning
retrieval-augmented-generation
License:
Download tests/test_contract.py from huzhzh/graph_rag: direct link, hf CLI and curl.
- Browser
- Download file 11.8 kB
-
https://huggingface.co/datasets/huzhzh/graph_rag/resolve/main/tests/test_contract.py
- Command line
-
hf download hf://datasets/huzhzh/graph_rag/tests/test_contract.py
-
curl -L -o test_contract.py https://huggingface.co/datasets/huzhzh/graph_rag/resolve/main/tests/test_contract.py
11.8 kB
| """数据集契约校验(零依赖,可直接跑,也可 pytest 收集)。 | |
| python dataset/tests/test_contract.py # 全量检查 | |
| python dataset/tests/test_contract.py --recompute 200 # 抽样重算 gold 的条数 | |
| 检查项: | |
| C1 每行可解析、必填字段齐、schema 版本对 | |
| C2 id 唯一、符合命名规则;id 里的 graph 与 graph 字段一致 | |
| C3 graph 在清单里;split 与清单一致;dev/test/holdout 图集合互不相交;ood 只含预留族 | |
| C4 每 (图, 任务) 条数不超过该任务配额,尾号从 q00 起连续 | |
| C5 gold 与 answer 自洽,且能从图重算(抽样) | |
| C6 answer.type / gold.kind 与任务匹配;anchor 节点出现在题面里 | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import re | |
| import sys | |
| from collections import Counter, defaultdict | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parents[2] | |
| if str(ROOT) not in sys.path: | |
| sys.path.insert(0, str(ROOT)) | |
| from dataset.build.common import ( # noqa: E402 | |
| DATASET, SCHEMA_VERSION, bfs, load_adj, load_manifest, path_of, | |
| ) | |
| from dataset.build.gen_mid import ( # noqa: E402 | |
| _comm_of, dismantle_order, modularity, triangles_at, triangles_total, | |
| ) | |
| FILES = { | |
| "node_degree": DATASET / "01-base" / "01-node" / "instances.jsonl", | |
| "edge_existence": DATASET / "01-base" / "02-edge" / "instances.jsonl", | |
| "path_length": DATASET / "01-base" / "03-connection" / "instances.jsonl", | |
| "partition_modularity": DATASET / "02-mid" / "01-community" / "instances.jsonl", | |
| "triangle_count": DATASET / "02-mid" / "02-triangle" / "instances.jsonl", | |
| "dismantle_order": DATASET / "02-mid" / "03-dismantle" / "instances.jsonl", | |
| } | |
| ID_RE = re.compile(r"^(base|mid|large)\.([a-z_]+)\.(.+)\.q(\d{2})$") | |
| REQUIRED = ["schema", "id", "task", "split", "graph", "question", | |
| "anchor", "answer", "gold"] | |
| ANSWER_TYPE = { | |
| "node_degree": "int", "edge_existence": "bool", "path_length": "int", | |
| "partition_modularity": "choice", "triangle_count": "int", | |
| "dismantle_order": "sequence", | |
| } | |
| GOLD_KIND = { | |
| "node_degree": {"neighbors"}, | |
| "edge_existence": {"edge", "non_edge"}, | |
| "path_length": {"shortest_path"}, | |
| "partition_modularity": {"modularity"}, | |
| "triangle_count": {"triangle"}, | |
| "dismantle_order": {"dismantle"}, | |
| } | |
| #: 每图每任务的目标条数;dismantle 允许少于这个数(退化实例会被丢弃) | |
| K_BY_TASK = { | |
| "node_degree": 5, "edge_existence": 5, "path_length": 5, | |
| "partition_modularity": 3, "triangle_count": 2, "dismantle_order": 1, | |
| } | |
| def load_rows() -> list[dict]: | |
| rows = [] | |
| for task, path in FILES.items(): | |
| if not path.exists(): | |
| raise SystemExit(f"[x] 缺文件 {path};先跑 dataset/build/gen_base.py / gen_mid.py") | |
| with open(path, encoding="utf-8") as f: | |
| for i, line in enumerate(f, 1): | |
| try: | |
| rows.append(json.loads(line)) | |
| except json.JSONDecodeError as e: | |
| raise SystemExit(f"[x] {path.name}:{i} JSON 解析失败 {e}") | |
| return rows | |
| def check(rows: list[dict], gman: dict[str, dict], n_recompute: int) -> list[str]: | |
| errs: list[str] = [] | |
| # C1 字段 | |
| for r in rows: | |
| miss = [k for k in REQUIRED if k not in r] | |
| if miss: | |
| errs.append(f"C1 {r.get('id')}: 缺字段 {miss}") | |
| elif r["schema"] != SCHEMA_VERSION: | |
| errs.append(f"C1 {r['id']}: schema={r['schema']} != {SCHEMA_VERSION}") | |
| # C2 id | |
| dup = [k for k, v in Counter(r["id"] for r in rows).items() if v > 1] | |
| if dup: | |
| errs.append(f"C2 {len(dup)} 个重复 id,例如 {dup[:3]}") | |
| for r in rows: | |
| m = ID_RE.match(r["id"]) | |
| if not m: | |
| errs.append(f"C2 {r['id']}: 不符合命名规则") | |
| continue | |
| if m.group(2) != r["task"] or m.group(3) != r["graph"]: | |
| errs.append(f"C2 {r['id']}: id 与 task/graph 不一致") | |
| # C3 graph / split | |
| by_split: dict[str, set[str]] = defaultdict(set) | |
| for r in rows: | |
| g = gman.get(r["graph"]) | |
| if g is None: | |
| errs.append(f"C3 {r['id']}: graph 不在清单") | |
| continue | |
| if r["split"] != g["split"]: | |
| errs.append(f"C3 {r['id']}: split={r['split']} 清单={g['split']}") | |
| by_split[r["split"]].add(r["graph"]) | |
| names = ("dev", "test", "holdout") | |
| for i, a in enumerate(names): | |
| for b in names[i + 1:]: | |
| inter = by_split.get(a, set()) & by_split.get(b, set()) | |
| if inter: | |
| errs.append(f"C3 {a}/{b} 图集合相交 {len(inter)} 张") | |
| ood_fam = {gman[k]["family"] for k in by_split.get("ood", set()) if k in gman} | |
| if ood_fam - {"unseen"}: | |
| errs.append(f"C3 ood 混入非预留族 {ood_fam - {'unseen'}}") | |
| # C4 每图每任务条数 + 尾号(必须从 q00 连续) | |
| cnt = Counter((r["graph"], r["task"]) for r in rows) | |
| over = {k: v for k, v in cnt.items() if v > K_BY_TASK[k[1]]} | |
| if over: | |
| errs.append(f"C4 {len(over)} 个 (图,任务) 超过配额,例如 {list(over.items())[:3]}") | |
| tails: dict[tuple[str, str], set[str]] = defaultdict(set) | |
| for r in rows: | |
| tails[(r["graph"], r["task"])].add(r["id"][-3:]) | |
| bad_tail = {} | |
| for k, v in tails.items(): | |
| want = {f"q{i:02d}" for i in range(len(v))} | |
| if v != want: | |
| bad_tail[k] = sorted(v) | |
| if bad_tail: | |
| errs.append(f"C4 {len(bad_tail)} 个 (图,任务) 尾号不连续," | |
| f"例如 {list(bad_tail.items())[:3]}") | |
| # C6 answer.type / gold.kind / anchor | |
| for r in rows: | |
| if ANSWER_TYPE.get(r["task"]) != r["answer"]["type"]: | |
| errs.append(f"C6 {r['id']}: answer.type={r['answer']['type']} 与任务不符") | |
| if r["gold"]["kind"] not in GOLD_KIND.get(r["task"], set()): | |
| errs.append(f"C6 {r['id']}: gold.kind={r['gold']['kind']} 与任务不符") | |
| for v in r["anchor"]["nodes"]: | |
| if str(v) not in r["question"]: | |
| errs.append(f"C6 {r['id']}: 锚点 {v} 未出现在题面") | |
| break | |
| if r["task"] == "partition_modularity": | |
| if sorted(r["gold"]["specs"]) != ["A", "B", "C"]: | |
| errs.append(f"C6 {r['id']}: specs 不是 A/B/C 三选") | |
| if r["task"] == "dismantle_order": | |
| seq = r["answer"]["value"] | |
| if not isinstance(seq, list) or not seq: | |
| errs.append(f"C6 {r['id']}: 答案不是序列") | |
| elif len(set(seq)) == 1: | |
| errs.append(f"C6 {r['id']}: 度数序列是常数 {seq[0]},无信息量") | |
| # C5 gold 重算(抽样;同一张图只载一次) | |
| if n_recompute > 0: | |
| step = max(1, len(rows) // n_recompute) | |
| cache: dict[str, tuple[int, list[list[int]]]] = {} | |
| for r in rows[::step][:n_recompute]: | |
| k = r["graph"] | |
| if k not in cache: | |
| cache[k] = load_adj(gman[k]) | |
| n, adj = cache[k] | |
| a = r["answer"]["value"] | |
| gd = r["gold"] | |
| if r["task"] == "node_degree": | |
| v = gd.get("of") | |
| if v is None or v != r["anchor"]["nodes"][0]: | |
| errs.append(f"C5 {r['id']}: gold.of 与锚点不一致") | |
| elif len(adj[v]) != a: | |
| errs.append(f"C5 {r['id']}: 度数重算 {len(adj[v])} != {a}") | |
| elif r["task"] == "edge_existence": | |
| u, v = gd.get("u"), gd.get("v") | |
| if {u, v} != set(r["anchor"]["nodes"]): | |
| errs.append(f"C5 {r['id']}: gold 端点与锚点不一致") | |
| elif (v in adj[u]) is not bool(a): | |
| errs.append(f"C5 {r['id']}: 邻接重算与 gold={a} 矛盾") | |
| elif (gd["kind"] == "edge") is not bool(a): | |
| errs.append(f"C5 {r['id']}: gold.kind 与 answer 矛盾") | |
| elif gd["kind"] == "non_edge" and gd.get("via") not in adj[u]: | |
| errs.append(f"C5 {r['id']}: via 不是 u 的邻居") | |
| elif r["task"] == "path_length": | |
| s, t = gd.get("src"), gd.get("dst") | |
| dist, par = bfs(adj, s) | |
| if dist[t] != a or gd.get("len") != a: | |
| errs.append(f"C5 {r['id']}: 最短路重算 {dist[t]} != {a}") | |
| elif "path" in gd: | |
| if path_of(par, s, t) != gd["path"]: | |
| errs.append(f"C5 {r['id']}: 见证路径与重算不一致") | |
| elif any(y not in adj[x] | |
| for x, y in zip(gd["path"], gd["path"][1:])): | |
| errs.append(f"C5 {r['id']}: 见证路径上有不存在的边") | |
| elif gd.get("truncated") and not (gd.get("head") and gd.get("tail")): | |
| errs.append(f"C5 {r['id']}: 截断路径缺 head/tail") | |
| elif r["task"] == "partition_modularity": | |
| m = sum(len(x) for x in adj) // 2 | |
| dcache: dict[int, list[int]] = {} | |
| qs = {} | |
| for letter, spec in gd["specs"].items(): | |
| qs[letter] = round(modularity(n, adj, m, _comm_of(spec, n, adj, dcache)), 6) | |
| if len(set(qs.values())) != 3: | |
| errs.append(f"C5 {r['id']}: 三个候选 Q 有并列 {qs}") | |
| for letter, q in qs.items(): | |
| if abs(q - gd["q"][letter]) > 1e-6: | |
| errs.append(f"C5 {r['id']}: Q[{letter}] 重算 {q} != {gd['q'][letter]}") | |
| want = (max if gd["ask"] == "max" else min)(qs, key=lambda x: qs[x]) | |
| if a != want: | |
| errs.append(f"C5 {r['id']}: 答案 {a} != Q 极值 {want}") | |
| elif r["task"] == "triangle_count": | |
| adjset = [set(x) for x in adj] | |
| if gd["scope"] == "graph": | |
| got = triangles_total(n, adj, adjset) | |
| else: | |
| if gd["of"] != r["anchor"]["nodes"][0]: | |
| errs.append(f"C5 {r['id']}: gold.of 与锚点不一致") | |
| got = triangles_at(adj, adjset, gd["of"]) | |
| if got != a or gd.get("count") != a: | |
| errs.append(f"C5 {r['id']}: 三角形重算 {got} != {a}") | |
| elif r["task"] == "dismantle_order": | |
| order, deg_at, _ = dismantle_order(n, adj, len(a)) | |
| if deg_at != list(a): | |
| errs.append(f"C5 {r['id']}: 度数序列重算 {deg_at} != {a}") | |
| elif gd.get("order") != order: | |
| errs.append(f"C5 {r['id']}: 见证 order 与重算不一致") | |
| return errs | |
| def main() -> int: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--recompute", type=int, default=120, help="抽样重算 gold 的条数") | |
| args = ap.parse_args() | |
| rows = load_rows() | |
| gman = {r["key"]: r for r in load_manifest()} | |
| errs = check(rows, gman, args.recompute) | |
| per_task = Counter(r["task"] for r in rows) | |
| per_split = Counter(r["split"] for r in rows) | |
| graphs = {r["graph"] for r in rows} | |
| print(f"行 {len(rows)} 图 {len(graphs)}") | |
| for t in FILES: | |
| print(f" {t:<22} {per_task.get(t, 0):>6}") | |
| print(f"split {dict(sorted(per_split.items()))}") | |
| print(f"重算样例 {min(args.recompute, len(rows))} 条") | |
| if errs: | |
| print(f"\n[x] {len(errs)} 项失败:", file=sys.stderr) | |
| for e in errs[:25]: | |
| print(" ", e, file=sys.stderr) | |
| return 1 | |
| print("[ok] 契约检查全部通过") | |
| return 0 | |
| def test_contract_default() -> None: | |
| rows = load_rows() | |
| assert check(rows, {r["key"]: r for r in load_manifest()}, 40) == [] | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |