ctxloop 0.3.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.
graphsnip/bench.py ADDED
@@ -0,0 +1,208 @@
1
+ """Offline, reproducible benchmark.
2
+
3
+ For each task it prices three approaches and checks the answer is actually there:
4
+
5
+ naive grep the terms, read the best-matching files in full (capped) <- realistic baseline
6
+ graphify Graphify's own `query` (budgeted) <- graph map, no source code
7
+ graphsnip pack / find+symbol / impact+symbol <- map + exact code
8
+
9
+ Quality is checked, not assumed: a task counts as answered only when the
10
+ expected symbol shows up in the output (and, for graphsnip, with its source).
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import re
16
+ import time
17
+ from pathlib import Path
18
+
19
+ from graphsnip.baseline import Baseline, query_terms
20
+ from graphsnip.engine import Engine
21
+ from graphsnip.project import Project
22
+ from graphsnip.tokens import count_tokens, method
23
+
24
+ TYPES = ("understand", "impact", "locate")
25
+
26
+
27
+ def _short(label: str) -> str:
28
+ return re.sub(r"\([^()]*\)\s*$", "", label).strip()
29
+
30
+
31
+ def _resolvable(G, project: Project, name: str) -> bool:
32
+ """Auto-generated tasks must be answerable by the tools; user-written tasks are never filtered."""
33
+ try:
34
+ from graphify.affected import resolve_seed_outcome
35
+ from graphify.serve import _resolve_single_node
36
+
37
+ nid, err = _resolve_single_node(G, name.split(".")[-1] if "." not in name else name)
38
+ seed, _ = resolve_seed_outcome(G, name.split(".")[-1], project.root)
39
+ return nid is not None and not err and seed is not None
40
+ except Exception:
41
+ return False
42
+
43
+
44
+ def default_tasks(project: Project, n: int = 8) -> list[dict]:
45
+ eng = Engine(project.root, source="bench", auto_refresh=False)
46
+ G = project.graph()
47
+ seen_files: dict[str, int] = {}
48
+ picks = []
49
+ idx = project.label_index()
50
+ from graphsnip.project import bare
51
+
52
+ for row in project.top_symbols(80):
53
+ lab = _short(str(row["label"]))
54
+ if len(lab) < 4 or lab.startswith("_") or row["file"] in seen_files and seen_files[row["file"]] >= 1:
55
+ continue
56
+ if len(idx.get(bare(lab), [])) != 1: # ambiguous names make impact/symbol lookups refuse; skip them
57
+ continue
58
+ if not _resolvable(G, project, eng._display(G, row["id"]).replace("()", "")):
59
+ continue
60
+ seen_files[row["file"]] = seen_files.get(row["file"], 0) + 1
61
+ picks.append(row)
62
+ if len(picks) >= n:
63
+ break
64
+ tasks = []
65
+ for i, row in enumerate(picks):
66
+ name = _short(eng._display(G, row["id"]))
67
+ t = TYPES[i % 3]
68
+ q = {"understand": f"how does {name} work and what does it depend on",
69
+ "impact": f"what breaks if I change {name}",
70
+ "locate": f"where is {name} defined and where is it used"}[t]
71
+ tasks.append({"id": f"t{i + 1}", "type": t, "question": q, "expect": [name.split(".")[-1]],
72
+ "target_file": row["file"]})
73
+ return tasks
74
+
75
+
76
+ def load_tasks(project: Project, path: str | None) -> list[dict]:
77
+ p = Path(path) if path else project.gs_dir / "tasks.json"
78
+ if p.exists():
79
+ data = json.loads(p.read_text(encoding="utf-8"))
80
+ tasks = data["tasks"] if isinstance(data, dict) else data
81
+ for i, t in enumerate(tasks):
82
+ t.setdefault("id", f"t{i + 1}")
83
+ t.setdefault("type", "understand")
84
+ t.setdefault("expect", [])
85
+ return tasks
86
+ return default_tasks(project)
87
+
88
+
89
+ def save_default_tasks(project: Project) -> Path:
90
+ project.gs_dir.mkdir(parents=True, exist_ok=True)
91
+ p = project.gs_dir / "tasks.json"
92
+ p.write_text(json.dumps({"_note": "Edit freely. type: understand | impact | locate. expect: symbol names that must appear in a correct answer.",
93
+ "tasks": default_tasks(project)}, indent=2) + "\n", encoding="utf-8")
94
+ return p
95
+
96
+
97
+ def run_bench(root: str = ".", tasks_path: str | None = None, quiet: bool = False) -> dict:
98
+ eng = Engine(root, source="bench")
99
+ p = eng.p
100
+ p.ensure_graph(True)
101
+ G = p.graph()
102
+ tasks = load_tasks(p, tasks_path)
103
+ base = Baseline(p)
104
+ eng.ledger.clear(source="bench")
105
+ from graphify.serve import _query_graph_text
106
+
107
+ corpus_tokens = sum(base.file_tokens(p.rel(f)) for f in p.files()[:20000])
108
+ rows = []
109
+ t0 = time.time()
110
+ for t in tasks:
111
+ q = t["question"]
112
+ expect = [e.lower() for e in t.get("expect", [])]
113
+ e2 = Engine(root, source="bench", auto_refresh=False) # fresh session per task
114
+ naive_tokens, naive_files = base.grep_read(query_terms(q))
115
+ naive_text = " ".join((p.read(f) or "") for f in naive_files).lower()
116
+ naive_hit = all(x in naive_text for x in expect) if expect else bool(naive_files)
117
+
118
+ gtext = _query_graph_text(G, q, mode="bfs", depth=3, token_budget=2000, graph_path=str(p.graph_json))
119
+ gtokens = 0 if gtext.startswith("No matching") else count_tokens(gtext)
120
+ ghit = all(x in gtext.lower() for x in expect) if expect else bool(gtokens)
121
+ # what an agent using Graphify alone then does: read the files its top hits point to
122
+ g_files: list[str] = []
123
+ for m in re.finditer(r"src=([^\s\]]+)", gtext):
124
+ f = m.group(1)
125
+ if f and f not in g_files and (p.root / f).is_file():
126
+ g_files.append(f)
127
+ if len(g_files) >= 3:
128
+ break
129
+ gread_tokens = (gtokens + sum(base.file_tokens(f) for f in g_files)) if gtokens else 0
130
+
131
+ typ = t.get("type", "understand")
132
+ name = (t.get("expect") or [q])[0]
133
+ parts = []
134
+ if typ == "understand":
135
+ parts.append(e2.pack(q, budget=3500))
136
+ elif typ == "impact":
137
+ parts.append(e2.impact(name))
138
+ parts.append(e2.symbol(name))
139
+ else:
140
+ parts.append(e2.find(q, budget=1200))
141
+ parts.append(e2.symbol(name))
142
+ gs_text = "\n".join(r.text for r in parts if r.ok)
143
+ gs_tokens = sum(r.returned for r in parts if r.ok)
144
+ has_code = "```" in gs_text
145
+ gs_hit = (all(x in gs_text.lower() for x in expect) if expect else bool(gs_tokens)) and has_code
146
+ # second read of the same symbol in the same session
147
+ again = e2.symbol(name)
148
+ rows.append({
149
+ "id": t["id"], "type": typ, "question": q, "expect": t.get("expect", []),
150
+ "naive_tokens": naive_tokens, "naive_files": len(naive_files), "naive_hit": naive_hit,
151
+ "graphify_tokens": gtokens, "graphify_hit": ghit, "graphify_read_tokens": gread_tokens,
152
+ "graphsnip_tokens": gs_tokens, "graphsnip_hit": gs_hit, "graphsnip_has_code": has_code,
153
+ "reread_tokens": again.returned if again.ok else None,
154
+ "reduction_vs_naive": round(naive_tokens / gs_tokens, 1) if gs_tokens else None,
155
+ })
156
+ ok = [r for r in rows if r["graphsnip_tokens"]]
157
+ tot_n = sum(r["naive_tokens"] for r in ok)
158
+ tot_c = sum(r["graphsnip_tokens"] for r in ok)
159
+ tot_g = sum(r["graphify_tokens"] for r in rows)
160
+ tot_gr = sum(r["graphify_read_tokens"] for r in rows)
161
+ result = {
162
+ "ts": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
163
+ "root": str(p.root),
164
+ "token_method": method(),
165
+ "baseline_definition": "grep the question's terms, read the top 8 matching files in full",
166
+ "graph": p.graph_stats(),
167
+ "corpus_tokens": corpus_tokens,
168
+ "tasks": rows,
169
+ "totals": {
170
+ "naive_tokens": tot_n, "graphsnip_tokens": tot_c, "graphify_tokens": tot_g, "graphify_read_tokens": tot_gr,
171
+ "saved_vs_graphify_read_pct": round(100 * (tot_gr - tot_c) / tot_gr, 1) if tot_gr else 0.0,
172
+ "saved_tokens": tot_n - tot_c,
173
+ "saved_pct": round(100 * (tot_n - tot_c) / tot_n, 1) if tot_n else 0.0,
174
+ "ratio": round(tot_n / tot_c, 1) if tot_c else 0.0,
175
+ "vs_corpus_ratio": round(corpus_tokens / (tot_c / len(ok)), 1) if ok and tot_c else 0.0,
176
+ "answered": sum(1 for r in rows if r["graphsnip_hit"]),
177
+ "naive_answered": sum(1 for r in rows if r["naive_hit"]),
178
+ "graphify_answered": sum(1 for r in rows if r["graphify_hit"]),
179
+ "tasks": len(rows),
180
+ "seconds": round(time.time() - t0, 1),
181
+ },
182
+ }
183
+ p.gs_dir.mkdir(parents=True, exist_ok=True)
184
+ (p.gs_dir / "bench.json").write_text(json.dumps(result, indent=2), encoding="utf-8")
185
+ return result
186
+
187
+
188
+ def format_table(res: dict) -> str:
189
+ rows = res["tasks"]
190
+ t = res["totals"]
191
+ w = max(8, min(44, max(len(r["question"]) for r in rows)))
192
+ hdr = f"{'task':<{w}} {'grep+read':>9} {'graphify':>8} {'gfy+read':>8} {'graphsnip':>9} {'saved':>6} ok"
193
+ out = [hdr, "-" * len(hdr)]
194
+ for r in rows:
195
+ saved = f"{100 * (1 - r['graphsnip_tokens'] / r['naive_tokens']):.0f}%" if r["naive_tokens"] and r["graphsnip_tokens"] else "-"
196
+ out.append(f"{r['question'][:w]:<{w}} {r['naive_tokens']:>9,} {r['graphify_tokens']:>8,} {r['graphify_read_tokens']:>8,} "
197
+ f"{r['graphsnip_tokens']:>9,} {saved:>6} {'✓' if r['graphsnip_hit'] else '✗'}")
198
+ out.append("-" * len(hdr))
199
+ out.append(f"{'TOTAL':<{w}} {t['naive_tokens']:>9,} {t['graphify_tokens']:>8,} {t['graphify_read_tokens']:>8,} "
200
+ f"{t['graphsnip_tokens']:>9,} {t['saved_pct']:>5}% {t['answered']}/{t['tasks']}")
201
+ out.append(f"\ngrep+read = {res['baseline_definition']} (what an agent does with no graph)")
202
+ out.append("graphify = Graphify `query` alone: a map with no source code")
203
+ out.append("gfy+read = that map, then reading the whole files its top hits point to (3 files max)")
204
+ out.append("graphsnip = exact code, ranked and budgeted (pack / find+symbol / impact+symbol)")
205
+ out.append(f"Saved column is vs grep+read; vs graphify+read it is {t['saved_vs_graphify_read_pct']}%. Tokens: {res['token_method']}.")
206
+ out.append(f"Answered (expected symbol + source present): graphsnip {t['answered']}/{t['tasks']}, "
207
+ f"grep+read {t['naive_answered']}/{t['tasks']}.")
208
+ return "\n".join(out)